Project

General

Profile

1
--
2
-- PostgreSQL database dump
3
--
4

    
5
SET statement_timeout = 0;
6
SET client_encoding = 'UTF8';
7
SET standard_conforming_strings = off;
8
SET check_function_bodies = false;
9
SET client_min_messages = warning;
10
SET escape_string_warning = off;
11

    
12
--
13
-- Name: py_functions; Type: SCHEMA; Schema: -; Owner: bien
14
--
15

    
16
CREATE SCHEMA py_functions;
17

    
18

    
19
ALTER SCHEMA py_functions OWNER TO bien;
20

    
21
SET search_path = py_functions, pg_catalog;
22

    
23
--
24
-- Name: __dateRangeEnd(); Type: FUNCTION; Schema: py_functions; Owner: bien
25
--
26

    
27
CREATE FUNCTION "__dateRangeEnd"() RETURNS trigger
28
    LANGUAGE plpgsql IMMUTABLE
29
    AS $$
30
BEGIN
31
    new.result := py_functions."_dateRangeEnd"(new.value);
32
    RETURN new;
33
END;
34
$$;
35

    
36

    
37
ALTER FUNCTION py_functions."__dateRangeEnd"() OWNER TO bien;
38

    
39
--
40
-- Name: __dateRangeStart(); Type: FUNCTION; Schema: py_functions; Owner: bien
41
--
42

    
43
CREATE FUNCTION "__dateRangeStart"() RETURNS trigger
44
    LANGUAGE plpgsql IMMUTABLE
45
    AS $$
46
BEGIN
47
    new.result := py_functions."_dateRangeStart"(new.value);
48
    RETURN new;
49
END;
50
$$;
51

    
52

    
53
ALTER FUNCTION py_functions."__dateRangeStart"() OWNER TO bien;
54

    
55
--
56
-- Name: __namePart(); Type: FUNCTION; Schema: py_functions; Owner: bien
57
--
58

    
59
CREATE FUNCTION "__namePart"() RETURNS trigger
60
    LANGUAGE plpgsql IMMUTABLE
61
    AS $$
62
BEGIN
63
    new.result := py_functions."_namePart"(new.first, new.middle, new.last);
64
    RETURN new;
65
END;
66
$$;
67

    
68

    
69
ALTER FUNCTION py_functions."__namePart"() OWNER TO bien;
70

    
71
--
72
-- Name: _date(text, text, text, text); Type: FUNCTION; Schema: py_functions; Owner: bien
73
--
74

    
75
CREATE FUNCTION _date(date text DEFAULT NULL::text, year text DEFAULT NULL::text, month text DEFAULT NULL::text, day text DEFAULT NULL::text) RETURNS text
76
    LANGUAGE plpythonu IMMUTABLE
77
    AS $$
78
global date, year, month, day
79

    
80
import datetime
81
import dateutil.tz
82

    
83
def e_str(e):
84
    msg = e.__class__.__name__+': '+e.args[0]
85
    return msg.rstrip()
86

    
87
class ExceptionWithCause(Exception):
88
    def __init__(self, msg, cause):
89
        msg += '\nDETAIL:  '+e_str(cause)
90
        Exception.__init__(self, msg)
91

    
92
utc = dateutil.tz.tzutc()
93

    
94
def naive2utc(datetime_):
95
    assert datetime_.tzinfo == None
96
    return datetime_.replace(tzinfo=utc)
97

    
98
def from_timestamp(utc_timestamp):
99
    return naive2utc(datetime.datetime.utcfromtimestamp(utc_timestamp))
100

    
101
epoch = from_timestamp(0)
102

    
103
def strtotime(str_, default=epoch):
104
    import dateutil.parser
105
    return dateutil.parser.parse(str_, default=default)
106

    
107
class FormatException(ExceptionWithCause):
108
    def __init__(self, cause, value=None):
109
        msg = 'invalid input value'
110
        if value != None: msg += ': "'+str(value)+'"'
111
        ExceptionWithCause.__init__(self, msg, cause)
112

    
113
if date != None:
114
    str_ = date
115
    try: year = float(str_)
116
    except ValueError:
117
        try: date = strtotime(str_)
118
        except ImportError: return str_
119
        except ValueError, e: raise FormatException(e, str_)
120
    else: date = (datetime.date(int(year), 1, 1) +
121
        datetime.timedelta(round((year % 1.)*365)))
122
else:
123
    # Year is required
124
    if year == None:
125
        if month == None and day == None: return None # entire date is empty
126
        else: raise FormatException(ValueError('Year is required'))
127
    
128
    # Convert month name to number
129
    if month != None and not month.isdigit(): # month is name
130
        try: month = str(strtotime(month).month)
131
        except ValueError, e: raise FormatException(e)
132
    
133
    if month == None: month = 1
134
    if day == None: day = 1
135
    year, month, day = map(int, (year, month, day))
136
    
137
    for try_num in xrange(2):
138
        try:
139
            date = datetime.date(year, month, day)
140
            break
141
        except ValueError, e:
142
            if try_num > 0: raise FormatException(e)
143
                # exception still raised after retry
144
            msg = e_str(e)
145
            if msg == 'month must be in 1..12': # try swapping month and day
146
                month, day = day, month
147
            else: raise FormatException(e)
148

    
149
return str(date)
150
$$;
151

    
152

    
153
ALTER FUNCTION py_functions._date(date text, year text, month text, day text) OWNER TO bien;
154

    
155
--
156
-- Name: _dateRangeEnd(text); Type: FUNCTION; Schema: py_functions; Owner: bien
157
--
158

    
159
CREATE FUNCTION "_dateRangeEnd"(value text) RETURNS text
160
    LANGUAGE sql IMMUTABLE
161
    AS $_$
162
SELECT (py_functions.parse_date_range($1))[2]
163
$_$;
164

    
165

    
166
ALTER FUNCTION py_functions."_dateRangeEnd"(value text) OWNER TO bien;
167

    
168
--
169
-- Name: _dateRangeStart(text); Type: FUNCTION; Schema: py_functions; Owner: bien
170
--
171

    
172
CREATE FUNCTION "_dateRangeStart"(value text) RETURNS text
173
    LANGUAGE sql IMMUTABLE
174
    AS $_$
175
SELECT (py_functions.parse_date_range($1))[1]
176
$_$;
177

    
178

    
179
ALTER FUNCTION py_functions."_dateRangeStart"(value text) OWNER TO bien;
180

    
181
--
182
-- Name: _namePart(text, text, text); Type: FUNCTION; Schema: py_functions; Owner: bien
183
--
184

    
185
CREATE FUNCTION "_namePart"(first text DEFAULT NULL::text, middle text DEFAULT NULL::text, last text DEFAULT NULL::text) RETURNS text
186
    LANGUAGE plpythonu IMMUTABLE
187
    AS $$
188
params = dict(first=first, middle=middle, last=last)
189

    
190
_name_parts_slices_items = [
191
    ('first', slice(None, 1)),
192
    ('middle', slice(1, -1)),
193
    ('last', slice(-1, None)),
194
]
195
name_parts_slices = dict(_name_parts_slices_items)
196
name_parts = [name for name, slice_ in _name_parts_slices_items]
197

    
198
def _name(items):
199
    items = dict(items)
200
    parts = []
201
    for part in name_parts:
202
        if part in items: parts.append(items[part])
203
    return ' '.join(parts)
204

    
205
out_items = []
206
for part, value in params.iteritems():
207
    if value == None: continue
208
    
209
    try: slice_ = name_parts_slices[part]
210
    except KeyError: pass # a non-value column
211
    else: out_items.append((part, ' '.join(value.split(' ')[slice_])))
212

    
213
return _name(out_items)
214
$$;
215

    
216

    
217
ALTER FUNCTION py_functions."_namePart"(first text, middle text, last text) OWNER TO bien;
218

    
219
--
220
-- Name: parse_date_range(text); Type: FUNCTION; Schema: py_functions; Owner: bien
221
--
222

    
223
CREATE FUNCTION parse_date_range(str_ text) RETURNS text[]
224
    LANGUAGE plpythonu IMMUTABLE STRICT
225
    AS $$
226
import re
227

    
228
def single_space(str_): return re.sub(r' {2,}', r' ', str_.strip())
229

    
230
def could_be_year(str_): return str_.isdigit() and len(str_) == 4
231

    
232
def could_be_day(str_): return str_.isdigit() and len(str_) <= 2
233

    
234
range_sep='-'
235
part_sep=' '
236

    
237
default = (str_, None)
238
# range_sep might be used as date part separator instead
239
if str_.find(part_sep) < 0: return default
240

    
241
start, sep, end = str_.partition(range_sep)
242
if sep == '': return default # not a range
243
start, end = (single_space(d).split(part_sep) for d in (start, end))
244

    
245
# Has form M D1-D2 or M D1-D2 Y (not M1 Y1-M2 Y2 or M1 D1-M2 D2)
246
if len(start) == 2 and (len(end) == 1 or (
247
        len(end) == 2 and could_be_day(start[-1]) and could_be_day(end[0])
248
        and could_be_year(end[-1])
249
    )):
250
    end.insert(0, start[0]) # make end fully specified
251
ct_diff = len(end) - len(start)
252
# Has form D1-D2 M Y, M1 D1-M2 D2 Y, M1-M2 Y, etc.
253
if ct_diff > 0: start += end[-ct_diff:] # make start fully specified
254
# Other forms are invalid and will be left as-is
255

    
256
return [part_sep.join(d) for d in (start, end)]
257
$$;
258

    
259

    
260
ALTER FUNCTION py_functions.parse_date_range(str_ text) OWNER TO bien;
261

    
262
SET default_tablespace = '';
263

    
264
SET default_with_oids = false;
265

    
266
--
267
-- Name: _dateRangeEnd; Type: TABLE; Schema: py_functions; Owner: bien; Tablespace: 
268
--
269

    
270
CREATE TABLE "_dateRangeEnd" (
271
    result text,
272
    not_null_col boolean DEFAULT true NOT NULL,
273
    value text
274
);
275

    
276

    
277
ALTER TABLE py_functions."_dateRangeEnd" OWNER TO bien;
278

    
279
--
280
-- Name: _dateRangeStart; Type: TABLE; Schema: py_functions; Owner: bien; Tablespace: 
281
--
282

    
283
CREATE TABLE "_dateRangeStart" (
284
    result text,
285
    not_null_col boolean DEFAULT true NOT NULL,
286
    value text
287
);
288

    
289

    
290
ALTER TABLE py_functions."_dateRangeStart" OWNER TO bien;
291

    
292
--
293
-- Name: _namePart; Type: TABLE; Schema: py_functions; Owner: bien; Tablespace: 
294
--
295

    
296
CREATE TABLE "_namePart" (
297
    result text,
298
    not_null_col boolean DEFAULT true NOT NULL,
299
    first text,
300
    middle text,
301
    last text
302
);
303

    
304

    
305
ALTER TABLE py_functions."_namePart" OWNER TO bien;
306

    
307
--
308
-- Name: _dateRangeEnd_unique; Type: INDEX; Schema: py_functions; Owner: bien; Tablespace: 
309
--
310

    
311
CREATE UNIQUE INDEX "_dateRangeEnd_unique" ON "_dateRangeEnd" USING btree ((COALESCE(value, '\\N'::text)));
312

    
313

    
314
--
315
-- Name: _dateRangeStart_unique; Type: INDEX; Schema: py_functions; Owner: bien; Tablespace: 
316
--
317

    
318
CREATE UNIQUE INDEX "_dateRangeStart_unique" ON "_dateRangeStart" USING btree ((COALESCE(value, '\\N'::text)));
319

    
320

    
321
--
322
-- Name: _namePart_unique; Type: INDEX; Schema: py_functions; Owner: bien; Tablespace: 
323
--
324

    
325
CREATE UNIQUE INDEX "_namePart_unique" ON "_namePart" USING btree ((COALESCE(first, '\\N'::text)), (COALESCE(middle, '\\N'::text)), (COALESCE(last, '\\N'::text)));
326

    
327

    
328
--
329
-- Name: _dateRangeEnd; Type: TRIGGER; Schema: py_functions; Owner: bien
330
--
331

    
332
CREATE TRIGGER "_dateRangeEnd" BEFORE INSERT OR UPDATE ON "_dateRangeEnd" FOR EACH ROW EXECUTE PROCEDURE "__dateRangeEnd"();
333

    
334

    
335
--
336
-- Name: _dateRangeStart; Type: TRIGGER; Schema: py_functions; Owner: bien
337
--
338

    
339
CREATE TRIGGER "_dateRangeStart" BEFORE INSERT OR UPDATE ON "_dateRangeStart" FOR EACH ROW EXECUTE PROCEDURE "__dateRangeStart"();
340

    
341

    
342
--
343
-- Name: _namePart; Type: TRIGGER; Schema: py_functions; Owner: bien
344
--
345

    
346
CREATE TRIGGER "_namePart" BEFORE INSERT OR UPDATE ON "_namePart" FOR EACH ROW EXECUTE PROCEDURE "__namePart"();
347

    
348

    
349
--
350
-- PostgreSQL database dump complete
351
--
352

    
(8-8/19)