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 = on;
8
SET check_function_bodies = false;
9
SET client_min_messages = warning;
10

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

    
15
CREATE SCHEMA py_functions;
16

    
17

    
18
ALTER SCHEMA py_functions OWNER TO bien;
19

    
20
--
21
-- Name: SCHEMA py_functions; Type: COMMENT; Schema: -; Owner: bien
22
--
23

    
24
COMMENT ON SCHEMA py_functions IS 'IMPORTANT: Functions must always return NULL in place of '''' (the empty string). This ensures that empty strings do not find their way into VegBIEN.';
25

    
26

    
27
SET search_path = py_functions, pg_catalog;
28

    
29
--
30
-- Name: _date(timestamp with time zone); Type: FUNCTION; Schema: py_functions; Owner: bien
31
--
32

    
33
CREATE FUNCTION _date(date timestamp with time zone) RETURNS timestamp with time zone
34
    LANGUAGE sql IMMUTABLE STRICT
35
    AS $_$
36
SELECT $1
37
$_$;
38

    
39

    
40
ALTER FUNCTION py_functions._date(date timestamp with time zone) OWNER TO bien;
41

    
42
--
43
-- Name: _date(text, text, text, text); Type: FUNCTION; Schema: py_functions; Owner: bien
44
--
45

    
46
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
47
    LANGUAGE plpython3u IMMUTABLE
48
    AS $$
49
global date, year, month, day
50

    
51
import datetime
52
import dateutil.tz
53

    
54
def e_msg(e): return e.args[0].rstrip()
55

    
56
def e_str(e): return e.__class__.__name__+': '+e_msg(e)
57

    
58
def raise_invalid_value(cause, value):
59
    raise ValueError('invalid input value: "'+str(value)+'"\nDETAIL:  '
60
        +e_str(cause))
61

    
62
utc = dateutil.tz.tzutc()
63

    
64
def naive2utc(datetime_):
65
    assert datetime_.tzinfo == None
66
    return datetime_.replace(tzinfo=utc)
67

    
68
def from_timestamp(utc_timestamp):
69
    return naive2utc(datetime.datetime.utcfromtimestamp(utc_timestamp))
70

    
71
epoch = from_timestamp(0)
72

    
73
def strtotime(str_, default=epoch):
74
    import dateutil.parser
75
    return dateutil.parser.parse(str_, default=default)
76

    
77
if date != None:
78
    str_ = date
79
    try: year = float(str_)
80
    except ValueError:
81
        try: date = strtotime(str_)
82
        except ImportError: return str_
83
        except ValueError as e: raise_invalid_value(e, str_)
84
    else: date = (datetime.date(int(year), 1, 1) +
85
        datetime.timedelta(round((year % 1.)*365)))
86
else:
87
    # Year is required
88
    if year == None:
89
        if month == None and day == None: return None # entire date is empty
90
        else: raise AssertionError(
91
            'null value in column "year" violates not-null constraint')
92
    
93
    # Convert month name to number
94
    if month != None and not month.isdigit(): # month is name
95
        month = str(strtotime(month).month)
96
    
97
    if month == None: month = 1
98
    if day == None: day = 1
99
    year, month, day = map(int, (year, month, day))
100
    
101
    for try_num in range(2):
102
        try:
103
            date = datetime.date(year, month, day)
104
            break
105
        except ValueError as e:
106
            if try_num > 0: raise # exception still raised after retry
107
            msg = e_msg(e)
108
            if msg == 'month must be in 1..12': # try swapping month and day
109
                month, day = day, month
110
            else: raise
111

    
112
return str(date)
113
$$;
114

    
115

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

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

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

    
128

    
129
ALTER FUNCTION py_functions."_dateRangeEnd"(value text) OWNER TO bien;
130

    
131
--
132
-- Name: _dateRangeEnd(timestamp with time zone); Type: FUNCTION; Schema: py_functions; Owner: bien
133
--
134

    
135
CREATE FUNCTION "_dateRangeEnd"(value timestamp with time zone) RETURNS timestamp with time zone
136
    LANGUAGE sql IMMUTABLE STRICT
137
    AS $_$
138
SELECT $1
139
$_$;
140

    
141

    
142
ALTER FUNCTION py_functions."_dateRangeEnd"(value timestamp with time zone) OWNER TO bien;
143

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

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

    
154

    
155
ALTER FUNCTION py_functions."_dateRangeStart"(value text) OWNER TO bien;
156

    
157
--
158
-- Name: _dateRangeStart(timestamp with time zone); Type: FUNCTION; Schema: py_functions; Owner: bien
159
--
160

    
161
CREATE FUNCTION "_dateRangeStart"(value timestamp with time zone) RETURNS timestamp with time zone
162
    LANGUAGE sql IMMUTABLE STRICT
163
    AS $_$
164
SELECT $1
165
$_$;
166

    
167

    
168
ALTER FUNCTION py_functions."_dateRangeStart"(value timestamp with time zone) OWNER TO bien;
169

    
170
--
171
-- Name: _namePart(text, text, text); Type: FUNCTION; Schema: py_functions; Owner: bien
172
--
173

    
174
CREATE FUNCTION "_namePart"(first text DEFAULT NULL::text, middle text DEFAULT NULL::text, last text DEFAULT NULL::text) RETURNS text
175
    LANGUAGE plpython3u IMMUTABLE
176
    AS $$
177
params = dict(first=first, middle=middle, last=last)
178

    
179
def none_if(val, *none_vals):
180
    for none_val in none_vals:
181
        if val == none_val: return None
182
    return val
183

    
184
_name_parts_slices_items = [
185
    ('first', slice(None, -1)),
186
    ('middle', slice(1, -1)),
187
    ('last', slice(-1, None)),
188
]
189
name_parts_slices = dict(_name_parts_slices_items)
190
name_parts = [name for name, slice_ in _name_parts_slices_items]
191

    
192
def _name(items):
193
    items = dict(items)
194
    parts = []
195
    for part in name_parts:
196
        if part in items: parts.append(items[part])
197
    return none_if(' '.join(parts), '')
198

    
199
out_items = []
200
for part, value in params.iteritems():
201
    if value == None: continue
202
    
203
    try: slice_ = name_parts_slices[part]
204
    except KeyError: pass # a non-value column
205
    else: out_items.append((part, ' '.join(value.split(' ')[slice_])))
206

    
207
return _name(out_items)
208
$$;
209

    
210

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

    
213
--
214
-- Name: parse_date_range(text); Type: FUNCTION; Schema: py_functions; Owner: bien
215
--
216

    
217
CREATE FUNCTION parse_date_range(str_ text) RETURNS text[]
218
    LANGUAGE plpython3u IMMUTABLE STRICT
219
    AS $$
220
import re
221

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

    
224
def could_be_year(str_): return str_.isdigit() and len(str_) == 4
225

    
226
def could_be_day(str_): return str_.isdigit() and len(str_) <= 2
227

    
228
range_sep='-'
229
part_sep=' '
230

    
231
default = (str_, str_)
232
# range_sep might be used as date part separator instead
233
if str_.find(part_sep) < 0: return default
234

    
235
start, sep, end = str_.partition(range_sep)
236
if sep == '': return default # not a range
237
start, end = (single_space(d).split(part_sep) for d in (start, end))
238

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

    
250
return [part_sep.join(d) for d in (start, end)]
251
$$;
252

    
253

    
254
ALTER FUNCTION py_functions.parse_date_range(str_ text) OWNER TO bien;
255

    
256
--
257
-- PostgreSQL database dump complete
258
--
259

    
(8-8/20)