37e0febec630e6edb3998f19ed96180ff5778317
[migration-tools.git] / sql / base / base.sql
1 --------------------------------------------------------------------------
2 -- An example of how to use:
3 -- 
4 -- DROP SCHEMA foo CASCADE; CREATE SCHEMA foo; 
5 -- \i base.sql
6 -- SELECT migration_tools.init('foo');
7 -- SELECT migration_tools.build('foo');
8 -- SELECT * FROM foo.fields_requiring_mapping;
9 -- \d foo.actor_usr
10 -- create some incoming ILS specific staging tables, like CREATE foo.legacy_items ( l_barcode TEXT, .. ) INHERITS foo.asset_copy;
11 -- Do some mapping, like UPDATE foo.legacy_items SET barcode = TRIM(BOTH ' ' FROM l_barcode);
12 -- Then, to move into production, do: select migration_tools.insert_base_into_production('foo')
13
14 CREATE SCHEMA migration_tools;
15
16 CREATE OR REPLACE FUNCTION migration_tools.production_tables (TEXT) RETURNS TEXT[] AS $$
17     DECLARE
18         migration_schema ALIAS FOR $1;
19         output  RECORD;
20     BEGIN
21         FOR output IN
22             EXECUTE 'SELECT string_to_array(value,'','') AS tables FROM ' || migration_schema || '.config WHERE key = ''production_tables'';'
23         LOOP
24             RETURN output.tables;
25         END LOOP;
26     END;
27 $$ LANGUAGE PLPGSQL STRICT STABLE;
28
29 CREATE OR REPLACE FUNCTION migration_tools.country_code (TEXT) RETURNS TEXT AS $$
30     DECLARE
31         migration_schema ALIAS FOR $1;
32         output TEXT;
33     BEGIN
34         FOR output IN
35             EXECUTE 'SELECT value FROM ' || migration_schema || '.config WHERE key = ''country_code'';'
36         LOOP
37             RETURN output;
38         END LOOP;
39     END;
40 $$ LANGUAGE PLPGSQL STRICT STABLE;
41
42
43 CREATE OR REPLACE FUNCTION migration_tools.log (TEXT,TEXT,INTEGER) RETURNS VOID AS $$
44     DECLARE
45         migration_schema ALIAS FOR $1;
46         sql ALIAS FOR $2;
47         nrows ALIAS FOR $3;
48     BEGIN
49         EXECUTE 'INSERT INTO ' || migration_schema || '.sql_log ( sql, row_count ) VALUES ( ' || quote_literal(sql) || ', ' || nrows || ' );';
50     END;
51 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
52
53 CREATE OR REPLACE FUNCTION migration_tools.exec (TEXT,TEXT) RETURNS VOID AS $$
54     DECLARE
55         migration_schema ALIAS FOR $1;
56         sql ALIAS FOR $2;
57         nrows INTEGER;
58     BEGIN
59         EXECUTE 'UPDATE ' || migration_schema || '.sql_current SET sql = ' || quote_literal(sql) || ';';
60         --RAISE INFO '%', sql;
61         EXECUTE sql;
62         GET DIAGNOSTICS nrows = ROW_COUNT;
63         PERFORM migration_tools.log(migration_schema,sql,nrows);
64     EXCEPTION
65         WHEN OTHERS THEN 
66             RAISE EXCEPTION '!!!!!!!!!!! state = %, msg = %, sql = %', SQLSTATE, SQLERRM, sql;
67     END;
68 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
69
70 CREATE OR REPLACE FUNCTION migration_tools.debug_exec (TEXT,TEXT) RETURNS VOID AS $$
71     DECLARE
72         migration_schema ALIAS FOR $1;
73         sql ALIAS FOR $2;
74         nrows INTEGER;
75     BEGIN
76         EXECUTE 'UPDATE ' || migration_schema || '.sql_current SET sql = ' || quote_literal(sql) || ';';
77         RAISE INFO 'debug_exec sql = %', sql;
78         EXECUTE sql;
79         GET DIAGNOSTICS nrows = ROW_COUNT;
80         PERFORM migration_tools.log(migration_schema,sql,nrows);
81     EXCEPTION
82         WHEN OTHERS THEN 
83             RAISE EXCEPTION '!!!!!!!!!!! state = %, msg = %, sql = %', SQLSTATE, SQLERRM, sql;
84     END;
85 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
86
87 CREATE OR REPLACE FUNCTION migration_tools.init (TEXT) RETURNS VOID AS $$
88     DECLARE
89         migration_schema ALIAS FOR $1;
90         sql TEXT;
91     BEGIN
92         EXECUTE 'DROP TABLE IF EXISTS ' || migration_schema || '.sql_current;';
93         EXECUTE 'CREATE TABLE ' || migration_schema || '.sql_current ( sql TEXT);';
94         EXECUTE 'INSERT INTO ' || migration_schema || '.sql_current ( sql ) VALUES ( '''' );';
95         BEGIN
96             SELECT 'CREATE TABLE ' || migration_schema || '.sql_log ( time TIMESTAMP NOT NULL DEFAULT NOW(), row_count INTEGER, sql TEXT );' INTO STRICT sql;
97             EXECUTE sql;
98         EXCEPTION
99             WHEN OTHERS THEN 
100                 RAISE INFO '!!!!!!!!!!! state = %, msg = %, sql = %', SQLSTATE, SQLERRM, sql;
101         END;
102         PERFORM migration_tools.exec( $1, 'DROP TABLE IF EXISTS ' || migration_schema || '.config;' );
103         PERFORM migration_tools.exec( $1, 'CREATE TABLE ' || migration_schema || '.config ( key TEXT UNIQUE, value TEXT);' );
104         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''production_tables'', ''asset.call_number,asset.copy_location,asset.copy,asset.stat_cat,asset.stat_cat_entry,asset.stat_cat_entry_copy_map,asset.copy_note,actor.usr,actor.card,actor.usr_address,actor.stat_cat,actor.stat_cat_entry,actor.stat_cat_entry_usr_map,actor.usr_note,action.circulation,action.hold_request,money.grocery,money.billing,money.cash_payment,money.forgive_payment'' );' );
105         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''country_code'', ''USA'' );' );
106         PERFORM migration_tools.exec( $1, 'DROP TABLE IF EXISTS ' || migration_schema || '.fields_requiring_mapping;' );
107         PERFORM migration_tools.exec( $1, 'CREATE TABLE ' || migration_schema || '.fields_requiring_mapping( table_schema TEXT, table_name TEXT, column_name TEXT, data_type TEXT);' );
108         PERFORM migration_tools.exec( $1, 'DROP TABLE IF EXISTS ' || migration_schema || '.base_profile_map;' );  
109         PERFORM migration_tools.exec( $1, 'CREATE TABLE ' || migration_schema || E'.base_profile_map ( 
110             id SERIAL,
111             perm_grp_id INTEGER,
112             transcribed_perm_group TEXT,
113             legacy_field1 TEXT,
114             legacy_value1 TEXT,
115             legacy_field2 TEXT,
116             legacy_value2 TEXT,
117             legacy_field3 TEXT,
118             legacy_value3 TEXT
119         );' );
120         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''base_profile_map'', ''base_profile_map'' );' );
121         BEGIN
122             PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''last_init'', now() );' );
123         EXCEPTION
124             WHEN OTHERS THEN PERFORM migration_tools.exec( $1, 'UPDATE ' || migration_schema || '.config SET value = now() WHERE key = ''last_init'';' );
125         END;
126     END;
127 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
128
129 CREATE OR REPLACE FUNCTION migration_tools.build (TEXT) RETURNS VOID AS $$
130     DECLARE
131         migration_schema ALIAS FOR $1;
132         production_tables TEXT[];
133     BEGIN
134         --RAISE INFO 'In migration_tools.build(%)', migration_schema;
135         SELECT migration_tools.production_tables(migration_schema) INTO STRICT production_tables;
136         PERFORM migration_tools.build_base_staging_tables(migration_schema,production_tables);
137         PERFORM migration_tools.exec( $1, 'CREATE UNIQUE INDEX ' || migration_schema || '_patron_barcode_key ON ' || migration_schema || '.actor_card ( barcode );' );
138         PERFORM migration_tools.exec( $1, 'CREATE UNIQUE INDEX ' || migration_schema || '_patron_usrname_key ON ' || migration_schema || '.actor_usr ( usrname );' );
139         PERFORM migration_tools.exec( $1, 'CREATE UNIQUE INDEX ' || migration_schema || '_copy_barcode_key ON ' || migration_schema || '.asset_copy ( barcode );' );
140         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_callnum_record_idx ON ' || migration_schema || '.asset_call_number ( record );' );
141         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_callnum_upper_label_id_lib_idx ON ' || migration_schema || '.asset_call_number ( UPPER(label),id,owning_lib );' );
142         PERFORM migration_tools.exec( $1, 'CREATE UNIQUE INDEX ' || migration_schema || '_callnum_label_once_per_lib ON ' || migration_schema || '.asset_call_number ( record,owning_lib,label );' );
143     END;
144 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
145
146 CREATE OR REPLACE FUNCTION migration_tools.build_base_staging_tables (TEXT,TEXT[]) RETURNS VOID AS $$
147     DECLARE
148         migration_schema ALIAS FOR $1;
149         production_tables ALIAS FOR $2;
150     BEGIN
151         --RAISE INFO 'In migration_tools.build_base_staging_tables(%,%)', migration_schema, production_tables;
152         FOR i IN array_lower(production_tables,1) .. array_upper(production_tables,1) LOOP
153             PERFORM migration_tools.build_specific_base_staging_table(migration_schema,production_tables[i]);
154         END LOOP;
155     END;
156 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
157
158 CREATE OR REPLACE FUNCTION migration_tools.build_specific_base_staging_table (TEXT,TEXT) RETURNS VOID AS $$
159     DECLARE
160         migration_schema ALIAS FOR $1;
161         production_table ALIAS FOR $2;
162         base_staging_table TEXT;
163         columns RECORD;
164     BEGIN
165         base_staging_table = REPLACE( production_table, '.', '_' );
166         --RAISE INFO 'In migration_tools.build_specific_base_staging_table(%,%) -> %', migration_schema, production_table, base_staging_table;
167         PERFORM migration_tools.exec( $1, 'CREATE TABLE ' || migration_schema || '.' || base_staging_table || ' ( LIKE ' || production_table || ' INCLUDING DEFAULTS EXCLUDING CONSTRAINTS );' );
168         PERFORM migration_tools.exec( $1, '
169             INSERT INTO ' || migration_schema || '.fields_requiring_mapping
170                 SELECT table_schema, table_name, column_name, data_type
171                 FROM information_schema.columns 
172                 WHERE table_schema = ''' || migration_schema || ''' AND table_name = ''' || base_staging_table || ''' AND is_nullable = ''NO'' AND column_default IS NULL;
173         ' );
174         FOR columns IN 
175             SELECT table_schema, table_name, column_name, data_type
176             FROM information_schema.columns 
177             WHERE table_schema = migration_schema AND table_name = base_staging_table AND is_nullable = 'NO' AND column_default IS NULL
178         LOOP
179             PERFORM migration_tools.exec( $1, 'ALTER TABLE ' || columns.table_schema || '.' || columns.table_name || ' ALTER COLUMN ' || columns.column_name || ' DROP NOT NULL;' );
180         END LOOP;
181     END;
182 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
183
184 CREATE OR REPLACE FUNCTION migration_tools.insert_base_into_production (TEXT) RETURNS VOID AS $$
185     DECLARE
186         migration_schema ALIAS FOR $1;
187         production_tables TEXT[];
188     BEGIN
189         --RAISE INFO 'In migration_tools.insert_into_production(%)', migration_schema;
190         SELECT migration_tools.production_tables(migration_schema) INTO STRICT production_tables;
191         FOR i IN array_lower(production_tables,1) .. array_upper(production_tables,1) LOOP
192             PERFORM migration_tools.insert_into_production(migration_schema,production_tables[i]);
193         END LOOP;
194     END;
195 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
196
197 CREATE OR REPLACE FUNCTION migration_tools.insert_into_production (TEXT,TEXT) RETURNS VOID AS $$
198     DECLARE
199         migration_schema ALIAS FOR $1;
200         production_table ALIAS FOR $2;
201         base_staging_table TEXT;
202         columns RECORD;
203     BEGIN
204         base_staging_table = REPLACE( production_table, '.', '_' );
205         --RAISE INFO 'In migration_tools.insert_into_production(%,%) -> %', migration_schema, production_table, base_staging_table;
206         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || production_table || ' SELECT * FROM ' || migration_schema || '.' || base_staging_table || ';' );
207     END;
208 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
209
210 CREATE OR REPLACE FUNCTION migration_tools.address_parse_out_citystatezip (TEXT) RETURNS TEXT[] AS $$
211     DECLARE
212         city_state_zip TEXT := $1;
213         city TEXT := '';
214         state TEXT := '';
215         zip TEXT := '';
216     BEGIN
217         zip := CASE WHEN city_state_zip ~ E'\\d\\d\\d\\d\\d' THEN REGEXP_REPLACE( city_state_zip, E'^.*(\\d\\d\\d\\d\\d-?\\d*).*$', E'\\1' ) ELSE '' END;
218         city_state_zip := REGEXP_REPLACE( city_state_zip, E'^(.*)\\d\\d\\d\\d\\d-?\\d*(.*)$', E'\\1\\2');
219         IF city_state_zip ~ ',' THEN
220             state := REGEXP_REPLACE( city_state_zip, E'^(.*),(.*)$', E'\\2');
221             city := REGEXP_REPLACE( city_state_zip, E'^(.*),(.*)$', E'\\1');
222         ELSE
223             IF city_state_zip ~ E'\\s+[A-Z][A-Z]\\s*' THEN
224                 state := REGEXP_REPLACE( city_state_zip, E'^.*,?\\s+([A-Z][A-Z])\\s*.*$', E'\\1' );
225                 city := REGEXP_REPLACE( city_state_zip, E'^(.*?),?\\s+[A-Z][A-Z](\\s*.*)$', E'\\1\\2' );
226             ELSE
227                 IF city_state_zip ~ E'^\\S+$'  THEN
228                     city := city_state_zip;
229                     state := 'N/A';
230                 ELSE
231                     state := REGEXP_REPLACE( city_state_zip, E'^(.*?),?\\s*(\\S+)\\s*$', E'\\2');
232                     city := REGEXP_REPLACE( city_state_zip, E'^(.*?),?\\s*(\\S+)\\s*$', E'\\1');
233                 END IF;
234             END IF;
235         END IF;
236         RETURN ARRAY[ TRIM(BOTH ' ' FROM city), TRIM(BOTH ' ' FROM state), TRIM(BOTH ' ' FROM zip) ];
237     END;
238 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
239
240 CREATE OR REPLACE FUNCTION migration_tools.rebarcode (o TEXT, t BIGINT) RETURNS TEXT AS $$
241     DECLARE
242         n TEXT := o;
243     BEGIN
244         IF o ~ E'^\\d+$' AND o !~ E'^0' AND length(o) < 19 THEN -- for reference, the max value for a bigint is 9223372036854775807.  May also want to consider the case where folks want to add prefixes to non-numeric barcodes
245             IF o::BIGINT < t THEN
246                 n = o::BIGINT + t;
247             END IF;
248         END IF;
249
250         RETURN n;
251     END;
252 $$ LANGUAGE PLPGSQL STRICT IMMUTABLE;
253
254 CREATE OR REPLACE FUNCTION migration_tools.base_profile_map (TEXT) RETURNS TEXT AS $$
255     DECLARE
256         migration_schema ALIAS FOR $1;
257         output TEXT;
258     BEGIN
259         FOR output IN
260             EXECUTE 'SELECT ''' || migration_schema || '.'' || value FROM ' || migration_schema || '.config WHERE key = ''base_profile_map'';'
261         LOOP
262             RETURN output;
263         END LOOP;
264     END;
265 $$ LANGUAGE PLPGSQL STRICT STABLE;
266
267 CREATE OR REPLACE FUNCTION migration_tools.map_base_patron_profile (TEXT,TEXT,TEXT) RETURNS VOID AS $$
268     DECLARE
269         migration_schema ALIAS FOR $1;
270         profile_map TEXT;
271         patron_table ALIAS FOR $2;
272         default_patron_profile ALIAS FOR $3;
273         sql TEXT;
274         sql_update TEXT;
275         sql_where1 TEXT := '';
276         sql_where2 TEXT := '';
277         sql_where3 TEXT := '';
278         output RECORD;
279     BEGIN
280         SELECT migration_tools.base_profile_map(migration_schema) INTO STRICT profile_map;
281         FOR output IN 
282             EXECUTE 'SELECT * FROM ' || profile_map || E' ORDER BY id;'
283         LOOP
284             sql_update := 'UPDATE ' || patron_table || ' AS u SET profile = perm_grp_id FROM ' || profile_map || ' AS m WHERE ';
285             sql_where1 := NULLIF(output.legacy_field1,'') || ' = ' || quote_literal( output.legacy_value1 ) || ' AND legacy_field1 = ' || quote_literal(output.legacy_field1) || ' AND legacy_value1 = ' || quote_literal(output.legacy_value1);
286             sql_where2 := NULLIF(output.legacy_field2,'') || ' = ' || quote_literal( output.legacy_value2 ) || ' AND legacy_field2 = ' || quote_literal(output.legacy_field2) || ' AND legacy_value2 = ' || quote_literal(output.legacy_value2);
287             sql_where3 := NULLIF(output.legacy_field3,'') || ' = ' || quote_literal( output.legacy_value3 ) || ' AND legacy_field3 = ' || quote_literal(output.legacy_field3) || ' AND legacy_value3 = ' || quote_literal(output.legacy_value3);
288             sql := sql_update || COALESCE(sql_where1,'') || CASE WHEN sql_where1 <> '' AND sql_where2<> ''  THEN ' AND ' ELSE '' END || COALESCE(sql_where2,'') || CASE WHEN sql_where2 <> '' AND sql_where3 <> '' THEN ' AND ' ELSE '' END || COALESCE(sql_where3,'') || ';';
289             --RAISE INFO 'sql = %', sql;
290             PERFORM migration_tools.exec( $1, sql );
291         END LOOP;
292         PERFORM migration_tools.exec( $1, 'UPDATE ' || patron_table || ' AS u SET profile = ' || quote_literal(default_patron_profile) || ' WHERE profile IS NULL;'  );
293         BEGIN
294             PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''last_base_patron_mapping_profile'', now() );' );
295         EXCEPTION
296             WHEN OTHERS THEN PERFORM migration_tools.exec( $1, 'UPDATE ' || migration_schema || '.config SET value = now() WHERE key = ''last_base_patron_mapping_profile'';' );
297         END;
298     END;
299 $$ LANGUAGE PLPGSQL STRICT STABLE;
300
301