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
SET SESSION AUTHORIZATION 'bien';
13

    
14
--
15
-- Name: py_functions; Type: SCHEMA; Schema: -; Owner: bien
16
--
17

    
18
CREATE SCHEMA py_functions;
19

    
20

    
21
SET search_path = py_functions, pg_catalog;
22

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

    
27
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
28
    LANGUAGE plpythonu IMMUTABLE
29
    AS $$
30
global date, year, month, day
31

    
32
import datetime
33
import dateutil.tz
34

    
35
def e_str(e):
36
    msg = e.__class__.__name__+': '+e.args[0]
37
    return msg.rstrip()
38

    
39
class ExceptionWithCause(Exception):
40
    def __init__(self, msg, cause):
41
        msg += ': '+e_str(cause)
42
        Exception.__init__(self, msg)
43

    
44
utc = dateutil.tz.tzutc()
45

    
46
def naive2utc(datetime_):
47
    assert datetime_.tzinfo == None
48
    return datetime_.replace(tzinfo=utc)
49

    
50
def from_timestamp(utc_timestamp):
51
    return naive2utc(datetime.datetime.utcfromtimestamp(utc_timestamp))
52

    
53
epoch = from_timestamp(0)
54

    
55
def strtotime(str_, default=epoch):
56
    import dateutil.parser
57
    return dateutil.parser.parse(str_, default=default)
58

    
59
class FormatException(ExceptionWithCause):
60
    def __init__(self, cause):
61
        ExceptionWithCause.__init__(self, 'Invalid input value', cause)
62

    
63
if date != None:
64
    str_ = date
65
    try: year = float(str_)
66
    except ValueError:
67
        try: date = strtotime(str_)
68
        except ImportError: return str_
69
        except ValueError, e: raise FormatException(e)
70
    else: date = (datetime.date(int(year), 1, 1) +
71
        datetime.timedelta(round((year % 1.)*365)))
72
else:
73
    # Year is required
74
    if year == None:
75
        if month == None and day == None: return None # entire date is empty
76
        else: raise FormatException(ValueError('Year is required'))
77
    
78
    # Convert month name to number
79
    if month != None and not month.isdigit(): # month is name
80
        try: month = str(strtotime(month).month)
81
        except ValueError, e: raise FormatException(e)
82
    
83
    if month == None: month = 1
84
    if day == None: day = 1
85
    year, month, day = map(int, (year, month, day))
86
    
87
    for try_num in xrange(2):
88
        try:
89
            date = datetime.date(year, month, day)
90
            break
91
        except ValueError, e:
92
            if try_num > 0: raise FormatException(e)
93
                # exception still raised after retry
94
            msg = e_str(e)
95
            if msg == 'month must be in 1..12': # try swapping month and day
96
                month, day = day, month
97
            else: raise FormatException(e)
98

    
99
return str(date)
100
$$;
101

    
102

    
103
--
104
-- Name: _dateRangeEnd(); Type: FUNCTION; Schema: py_functions; Owner: bien
105
--
106

    
107
CREATE FUNCTION "_dateRangeEnd"() RETURNS trigger
108
    LANGUAGE plpgsql IMMUTABLE
109
    AS $$
110
BEGIN
111
    new.result := py_functions."_dateRangeEnd"(new.value);
112
    RETURN new;
113
END;
114
$$;
115

    
116

    
117
--
118
-- Name: _dateRangeEnd(text); Type: FUNCTION; Schema: py_functions; Owner: bien
119
--
120

    
121
CREATE FUNCTION "_dateRangeEnd"(value text) RETURNS text
122
    LANGUAGE sql IMMUTABLE
123
    AS $_$
124
SELECT (py_functions.parse_date_range($1))[2]
125
$_$;
126

    
127

    
128
--
129
-- Name: _dateRangeStart(); Type: FUNCTION; Schema: py_functions; Owner: bien
130
--
131

    
132
CREATE FUNCTION "_dateRangeStart"() RETURNS trigger
133
    LANGUAGE plpgsql IMMUTABLE
134
    AS $$
135
BEGIN
136
    new.result := py_functions."_dateRangeStart"(new.value);
137
    RETURN new;
138
END;
139
$$;
140

    
141

    
142
--
143
-- Name: _dateRangeStart(text); Type: FUNCTION; Schema: py_functions; Owner: bien
144
--
145

    
146
CREATE FUNCTION "_dateRangeStart"(value text) RETURNS text
147
    LANGUAGE sql IMMUTABLE
148
    AS $_$
149
SELECT (py_functions.parse_date_range($1))[1]
150
$_$;
151

    
152

    
153
--
154
-- Name: _namePart(); Type: FUNCTION; Schema: py_functions; Owner: bien
155
--
156

    
157
CREATE FUNCTION "_namePart"() RETURNS trigger
158
    LANGUAGE plpgsql IMMUTABLE
159
    AS $$
160
BEGIN
161
    new.result := py_functions."_namePart"(new.first, new.middle, new.last);
162
    RETURN new;
163
END;
164
$$;
165

    
166

    
167
--
168
-- Name: _namePart(text, text, text); Type: FUNCTION; Schema: py_functions; Owner: bien
169
--
170

    
171
CREATE FUNCTION "_namePart"(first text DEFAULT NULL::text, middle text DEFAULT NULL::text, last text DEFAULT NULL::text) RETURNS text
172
    LANGUAGE plpythonu IMMUTABLE
173
    AS $$
174
params = dict(first=first, middle=middle, last=last)
175

    
176
_name_parts_slices_items = [
177
    ('first', slice(None, 1)),
178
    ('middle', slice(1, -1)),
179
    ('last', slice(-1, None)),
180
]
181
name_parts_slices = dict(_name_parts_slices_items)
182
name_parts = [name for name, slice_ in _name_parts_slices_items]
183

    
184
def _name(items):
185
    items = dict(items)
186
    parts = []
187
    for part in name_parts:
188
        if part in items: parts.append(items[part])
189
    return ' '.join(parts)
190

    
191
out_items = []
192
for part, value in params.iteritems():
193
    if value == None: continue
194
    
195
    try: slice_ = name_parts_slices[part]
196
    except KeyError: pass # a non-value column
197
    else: out_items.append((part, ' '.join(value.split(' ')[slice_])))
198

    
199
return _name(out_items)
200
$$;
201

    
202

    
203
--
204
-- Name: parse_date_range(text); Type: FUNCTION; Schema: py_functions; Owner: bien
205
--
206

    
207
CREATE FUNCTION parse_date_range(str_ text) RETURNS text[]
208
    LANGUAGE plpythonu IMMUTABLE STRICT
209
    AS $$
210
import re
211

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

    
214
def could_be_year(str_): return str_.isdigit() and len(str_) == 4
215

    
216
def could_be_day(str_): return str_.isdigit() and len(str_) <= 2
217

    
218
range_sep='-'
219
part_sep=' '
220

    
221
default = (str_, None)
222
# range_sep might be used as date part separator instead
223
if str_.find(part_sep) < 0: return default
224

    
225
start, sep, end = str_.partition(range_sep)
226
if sep == '': return default # not a range
227
start, end = (single_space(d).split(part_sep) for d in (start, end))
228

    
229
# Has form M D1-D2 or M D1-D2 Y (not M1 Y1-M2 Y2 or M1 D1-M2 D2)
230
if len(start) == 2 and (len(end) == 1 or (
231
        len(end) == 2 and could_be_day(start[-1]) and could_be_day(end[0])
232
        and could_be_year(end[-1])
233
    )):
234
    end.insert(0, start[0]) # make end fully specified
235
ct_diff = len(end) - len(start)
236
# Has form D1-D2 M Y, M1 D1-M2 D2 Y, M1-M2 Y, etc.
237
if ct_diff > 0: start += end[-ct_diff:] # make start fully specified
238
# Other forms are invalid and will be left as-is
239

    
240
return [part_sep.join(d) for d in (start, end)]
241
$$;
242

    
243

    
244
SET default_tablespace = '';
245

    
246
SET default_with_oids = false;
247

    
248
--
249
-- Name: _dateRangeEnd; Type: TABLE; Schema: py_functions; Owner: bien; Tablespace: 
250
--
251

    
252
CREATE TABLE "_dateRangeEnd" (
253
    result text,
254
    not_null_col boolean DEFAULT true NOT NULL,
255
    value text
256
);
257

    
258

    
259
--
260
-- Name: _dateRangeStart; Type: TABLE; Schema: py_functions; Owner: bien; Tablespace: 
261
--
262

    
263
CREATE TABLE "_dateRangeStart" (
264
    result text,
265
    not_null_col boolean DEFAULT true NOT NULL,
266
    value text
267
);
268

    
269

    
270
--
271
-- Name: _namePart; Type: TABLE; Schema: py_functions; Owner: bien; Tablespace: 
272
--
273

    
274
CREATE TABLE "_namePart" (
275
    result text,
276
    not_null_col boolean DEFAULT true NOT NULL,
277
    first text,
278
    middle text,
279
    last text
280
);
281

    
282

    
283
--
284
-- Name: _dateRangeEnd_unique; Type: INDEX; Schema: py_functions; Owner: bien; Tablespace: 
285
--
286

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

    
289

    
290
--
291
-- Name: _dateRangeStart_unique; Type: INDEX; Schema: py_functions; Owner: bien; Tablespace: 
292
--
293

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

    
296

    
297
--
298
-- Name: _namePart_unique; Type: INDEX; Schema: py_functions; Owner: bien; Tablespace: 
299
--
300

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

    
303

    
304
--
305
-- Name: _dateRangeEnd; Type: TRIGGER; Schema: py_functions; Owner: bien
306
--
307

    
308
CREATE TRIGGER "_dateRangeEnd" BEFORE INSERT OR UPDATE ON "_dateRangeEnd" FOR EACH ROW EXECUTE PROCEDURE "_dateRangeEnd"();
309

    
310

    
311
--
312
-- Name: _dateRangeStart; Type: TRIGGER; Schema: py_functions; Owner: bien
313
--
314

    
315
CREATE TRIGGER "_dateRangeStart" BEFORE INSERT OR UPDATE ON "_dateRangeStart" FOR EACH ROW EXECUTE PROCEDURE "_dateRangeStart"();
316

    
317

    
318
--
319
-- Name: _namePart; Type: TRIGGER; Schema: py_functions; Owner: bien
320
--
321

    
322
CREATE TRIGGER "_namePart" BEFORE INSERT OR UPDATE ON "_namePart" FOR EACH ROW EXECUTE PROCEDURE py_functions."_namePart"();
323

    
324

    
325
--
326
-- PostgreSQL database dump complete
327
--
328

    
(8-8/19)