d773fdbe0d91ede5783adc8349f2fdea35cc35d2
[migration-tools.git] / sql / base / base.sql
1 -- Copyright 2009-2012, Equinox Software, Inc.
2 --
3 -- This program is free software; you can redistribute it and/or
4 -- modify it under the terms of the GNU General Public License
5 -- as published by the Free Software Foundation; either version 2
6 -- of the License, or (at your option) any later version.
7 --
8 -- This program is distributed in the hope that it will be useful,
9 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
10 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 -- GNU General Public License for more details.
12 --
13 -- You should have received a copy of the GNU General Public License
14 -- along with this program; if not, write to the Free Software
15 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16
17 --------------------------------------------------------------------------
18 -- An example of how to use:
19 -- 
20 -- DROP SCHEMA foo CASCADE; CREATE SCHEMA foo; 
21 -- \i base.sql
22 -- SELECT migration_tools.init('foo');
23 -- SELECT migration_tools.build('foo');
24 -- SELECT * FROM foo.fields_requiring_mapping;
25 -- \d foo.actor_usr
26 -- create some incoming ILS specific staging tables, like CREATE foo.legacy_items ( l_barcode TEXT, .. ) INHERITS (foo.asset_copy);
27 -- Do some mapping, like UPDATE foo.legacy_items SET barcode = TRIM(BOTH ' ' FROM l_barcode);
28 -- Then, to move into production, do: select migration_tools.insert_base_into_production('foo')
29
30 CREATE SCHEMA migration_tools;
31
32 CREATE OR REPLACE FUNCTION migration_tools.production_tables (TEXT) RETURNS TEXT[] AS $$
33     DECLARE
34         migration_schema ALIAS FOR $1;
35         output  RECORD;
36     BEGIN
37         FOR output IN
38             EXECUTE 'SELECT string_to_array(value,'','') AS tables FROM ' || migration_schema || '.config WHERE key = ''production_tables'';'
39         LOOP
40             RETURN output.tables;
41         END LOOP;
42     END;
43 $$ LANGUAGE PLPGSQL STRICT STABLE;
44
45 CREATE OR REPLACE FUNCTION migration_tools.country_code (TEXT) RETURNS TEXT AS $$
46     DECLARE
47         migration_schema ALIAS FOR $1;
48         output TEXT;
49     BEGIN
50         FOR output IN
51             EXECUTE 'SELECT value FROM ' || migration_schema || '.config WHERE key = ''country_code'';'
52         LOOP
53             RETURN output;
54         END LOOP;
55     END;
56 $$ LANGUAGE PLPGSQL STRICT STABLE;
57
58
59 CREATE OR REPLACE FUNCTION migration_tools.log (TEXT,TEXT,INTEGER) RETURNS VOID AS $$
60     DECLARE
61         migration_schema ALIAS FOR $1;
62         sql ALIAS FOR $2;
63         nrows ALIAS FOR $3;
64     BEGIN
65         EXECUTE 'INSERT INTO ' || migration_schema || '.sql_log ( sql, row_count ) VALUES ( ' || quote_literal(sql) || ', ' || nrows || ' );';
66     END;
67 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
68
69 CREATE OR REPLACE FUNCTION migration_tools.exec (TEXT,TEXT) RETURNS VOID AS $$
70     DECLARE
71         migration_schema ALIAS FOR $1;
72         sql ALIAS FOR $2;
73         nrows INTEGER;
74     BEGIN
75         EXECUTE 'UPDATE ' || migration_schema || '.sql_current SET sql = ' || quote_literal(sql) || ';';
76         --RAISE INFO '%', sql;
77         EXECUTE sql;
78         GET DIAGNOSTICS nrows = ROW_COUNT;
79         PERFORM migration_tools.log(migration_schema,sql,nrows);
80     EXCEPTION
81         WHEN OTHERS THEN 
82             RAISE EXCEPTION '!!!!!!!!!!! state = %, msg = %, sql = %', SQLSTATE, SQLERRM, sql;
83     END;
84 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
85
86 CREATE OR REPLACE FUNCTION migration_tools.debug_exec (TEXT,TEXT) RETURNS VOID AS $$
87     DECLARE
88         migration_schema ALIAS FOR $1;
89         sql ALIAS FOR $2;
90         nrows INTEGER;
91     BEGIN
92         EXECUTE 'UPDATE ' || migration_schema || '.sql_current SET sql = ' || quote_literal(sql) || ';';
93         RAISE INFO 'debug_exec sql = %', sql;
94         EXECUTE sql;
95         GET DIAGNOSTICS nrows = ROW_COUNT;
96         PERFORM migration_tools.log(migration_schema,sql,nrows);
97     EXCEPTION
98         WHEN OTHERS THEN 
99             RAISE EXCEPTION '!!!!!!!!!!! state = %, msg = %, sql = %', SQLSTATE, SQLERRM, sql;
100     END;
101 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
102
103 CREATE OR REPLACE FUNCTION migration_tools.init (TEXT) RETURNS VOID AS $$
104     DECLARE
105         migration_schema ALIAS FOR $1;
106         sql TEXT;
107     BEGIN
108         EXECUTE 'DROP TABLE IF EXISTS ' || migration_schema || '.sql_current;';
109         EXECUTE 'CREATE TABLE ' || migration_schema || '.sql_current ( sql TEXT);';
110         EXECUTE 'INSERT INTO ' || migration_schema || '.sql_current ( sql ) VALUES ( '''' );';
111         BEGIN
112             SELECT 'CREATE TABLE ' || migration_schema || '.sql_log ( time TIMESTAMP NOT NULL DEFAULT NOW(), row_count INTEGER, sql TEXT );' INTO STRICT sql;
113             EXECUTE sql;
114         EXCEPTION
115             WHEN OTHERS THEN 
116                 RAISE INFO '!!!!!!!!!!! state = %, msg = %, sql = %', SQLSTATE, SQLERRM, sql;
117         END;
118         PERFORM migration_tools.exec( $1, 'DROP TABLE IF EXISTS ' || migration_schema || '.config;' );
119         PERFORM migration_tools.exec( $1, 'CREATE TABLE ' || migration_schema || '.config ( key TEXT UNIQUE, value TEXT);' );
120         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''production_tables'', ''asset.call_number,asset.call_number_prefix,asset.call_number_suffix,asset.copy_location,asset.copy,asset.copy_alert,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,actor.usr_standing_penalty,actor.usr_setting,action.circulation,action.hold_request,action.hold_notification,action.hold_request_note,action.hold_transit_copy,action.transit_copy,money.grocery,money.billing,money.cash_payment,money.forgive_payment,acq.provider,acq.provider_address,acq.provider_note,acq.provider_contact,acq.provider_contact_address,acq.fund,acq.fund_allocation,acq.fund_tag,acq.fund_tag_map,acq.funding_source,acq.funding_source_credit,acq.lineitem,acq.purchase_order,acq.po_item,acq.invoice,acq.invoice_item,acq.invoice_entry,acq.lineitem_detail,acq.fund_debit,acq.fund_transfer,acq.po_note,config.circ_matrix_matchpoint,config.circ_matrix_limit_set_map,config.hold_matrix_matchpoint,asset.copy_tag,asset.copy_tag_copy_map,config.copy_tag_type,serial.item,serial.item_note,serial.record_entry,biblio.record_entry'' );' );
121         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''country_code'', ''USA'' );' );
122         PERFORM migration_tools.exec( $1, 'DROP TABLE IF EXISTS ' || migration_schema || '.fields_requiring_mapping;' );
123         PERFORM migration_tools.exec( $1, 'CREATE TABLE ' || migration_schema || '.fields_requiring_mapping( table_schema TEXT, table_name TEXT, column_name TEXT, data_type TEXT);' );
124         PERFORM migration_tools.exec( $1, 'DROP TABLE IF EXISTS ' || migration_schema || '.base_profile_map;' );  
125         PERFORM migration_tools.exec( $1, 'CREATE TABLE ' || migration_schema || E'.base_profile_map ( 
126             id SERIAL,
127             perm_grp_id INTEGER,
128             transcribed_perm_group TEXT,
129             legacy_field1 TEXT,
130             legacy_value1 TEXT,
131             legacy_field2 TEXT,
132             legacy_value2 TEXT,
133             legacy_field3 TEXT,
134             legacy_value3 TEXT
135         );' );
136         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''base_profile_map'', ''base_profile_map'' );' );
137         PERFORM migration_tools.exec( $1, 'DROP TABLE IF EXISTS ' || migration_schema || '.base_item_dynamic_field_map;' );  
138         PERFORM migration_tools.exec( $1, 'CREATE TABLE ' || migration_schema || E'.base_item_dynamic_field_map ( 
139             id SERIAL,
140             evergreen_field TEXT,
141             evergreen_value TEXT,
142             evergreen_datatype TEXT,
143             legacy_field1 TEXT,
144             legacy_value1 TEXT,
145             legacy_field2 TEXT,
146             legacy_value2 TEXT,
147             legacy_field3 TEXT,
148             legacy_value3 TEXT
149         );' );
150         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_item_dynamic_lf1_idx ON ' || migration_schema || '.base_item_dynamic_field_map (legacy_field1,legacy_value1);' ); 
151         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_item_dynamic_lf2_idx ON ' || migration_schema || '.base_item_dynamic_field_map (legacy_field2,legacy_value2);' ); 
152         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_item_dynamic_lf3_idx ON ' || migration_schema || '.base_item_dynamic_field_map (legacy_field3,legacy_value3);' ); 
153         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''base_item_dynamic_field_map'', ''base_item_dynamic_field_map'' );' );
154         PERFORM migration_tools.exec( $1, 'DROP TABLE IF EXISTS ' || migration_schema || '.base_copy_location_map;' );  
155         PERFORM migration_tools.exec( $1, 'CREATE TABLE ' || migration_schema || E'.base_copy_location_map ( 
156             id SERIAL,
157             location INTEGER,
158             holdable BOOLEAN NOT NULL DEFAULT TRUE,
159             hold_verify BOOLEAN NOT NULL DEFAULT FALSE,
160             opac_visible BOOLEAN NOT NULL DEFAULT TRUE,
161             circulate BOOLEAN NOT NULL DEFAULT TRUE,
162             transcribed_location TEXT,
163             legacy_field1 TEXT,
164             legacy_value1 TEXT,
165             legacy_field2 TEXT,
166             legacy_value2 TEXT,
167             legacy_field3 TEXT,
168             legacy_value3 TEXT
169         );' );
170         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_base_copy_location_lf1_idx ON ' || migration_schema || '.base_copy_location_map (legacy_field1,legacy_value1);' ); 
171         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_base_copy_location_lf2_idx ON ' || migration_schema || '.base_copy_location_map (legacy_field2,legacy_value2);' ); 
172         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_base_copy_location_lf3_idx ON ' || migration_schema || '.base_copy_location_map (legacy_field3,legacy_value3);' ); 
173         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_base_copy_location_loc_idx ON ' || migration_schema || '.base_copy_location_map (transcribed_location);' ); 
174         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''base_copy_location_map'', ''base_copy_location_map'' );' );
175         PERFORM migration_tools.exec( $1, 'DROP TABLE IF EXISTS ' || migration_schema || '.base_circ_field_map;' );  
176         PERFORM migration_tools.exec( $1, 'CREATE TABLE ' || migration_schema || E'.base_circ_field_map ( 
177             id SERIAL,
178             circulate BOOLEAN,
179             loan_period TEXT,
180             max_renewals TEXT,
181             max_out TEXT,
182             fine_amount TEXT,
183             fine_interval TEXT,
184             max_fine TEXT,
185             item_field1 TEXT,
186             item_value1 TEXT,
187             item_field2 TEXT,
188             item_value2 TEXT,
189             patron_field1 TEXT,
190             patron_value1 TEXT,
191             patron_field2 TEXT,
192             patron_value2 TEXT
193         );' );
194         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_circ_dynamic_lf1_idx ON ' || migration_schema || '.base_circ_field_map (item_field1,item_value1);' ); 
195         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_circ_dynamic_lf2_idx ON ' || migration_schema || '.base_circ_field_map (item_field2,item_value2);' ); 
196         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_circ_dynamic_lf3_idx ON ' || migration_schema || '.base_circ_field_map (patron_field1,patron_value1);' ); 
197         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_circ_dynamic_lf4_idx ON ' || migration_schema || '.base_circ_field_map (patron_field2,patron_value2);' ); 
198         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''base_circ_field_map'', ''base_circ_field_map'' );' );
199
200         BEGIN
201             PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''last_init'', now() );' );
202         EXCEPTION
203             WHEN OTHERS THEN PERFORM migration_tools.exec( $1, 'UPDATE ' || migration_schema || '.config SET value = now() WHERE key = ''last_init'';' );
204         END;
205     END;
206 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
207
208 CREATE OR REPLACE FUNCTION migration_tools.build (TEXT) RETURNS VOID AS $$
209     DECLARE
210         migration_schema ALIAS FOR $1;
211         production_tables TEXT[];
212     BEGIN
213         --RAISE INFO 'In migration_tools.build(%)', migration_schema;
214         SELECT migration_tools.production_tables(migration_schema) INTO STRICT production_tables;
215         PERFORM migration_tools.build_base_staging_tables(migration_schema,production_tables);
216         PERFORM migration_tools.exec( $1, 'CREATE UNIQUE INDEX ' || migration_schema || '_patron_barcode_key ON ' || migration_schema || '.actor_card ( barcode );' );
217         PERFORM migration_tools.exec( $1, 'CREATE UNIQUE INDEX ' || migration_schema || '_patron_usrname_key ON ' || migration_schema || '.actor_usr ( usrname );' );
218         PERFORM migration_tools.exec( $1, 'CREATE UNIQUE INDEX ' || migration_schema || '_copy_barcode_key ON ' || migration_schema || '.asset_copy ( barcode );' );
219         PERFORM migration_tools.exec( $1, 'CREATE UNIQUE INDEX ' || migration_schema || '_copy_id_key ON ' || migration_schema || '.asset_copy ( id );' );
220         PERFORM migration_tools.exec( $1, 'CREATE INDEX ' || migration_schema || '_callnum_record_idx ON ' || migration_schema || '.asset_call_number ( record );' );
221         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 );' );
222         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,prefix,suffix );' );
223     END;
224 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
225
226 CREATE OR REPLACE FUNCTION migration_tools.build_base_staging_tables (TEXT,TEXT[]) RETURNS VOID AS $$
227     DECLARE
228         migration_schema ALIAS FOR $1;
229         production_tables ALIAS FOR $2;
230     BEGIN
231         --RAISE INFO 'In migration_tools.build_base_staging_tables(%,%)', migration_schema, production_tables;
232         FOR i IN array_lower(production_tables,1) .. array_upper(production_tables,1) LOOP
233             PERFORM migration_tools.build_specific_base_staging_table(migration_schema,production_tables[i]);
234         END LOOP;
235     END;
236 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
237
238 CREATE OR REPLACE FUNCTION migration_tools.build_specific_base_staging_table (TEXT,TEXT) RETURNS VOID AS $$
239     DECLARE
240         migration_schema ALIAS FOR $1;
241         production_table ALIAS FOR $2;
242         base_staging_table TEXT;
243         columns RECORD;
244     BEGIN
245         base_staging_table = REPLACE( production_table, '.', '_' );
246         --RAISE INFO 'In migration_tools.build_specific_base_staging_table(%,%) -> %', migration_schema, production_table, base_staging_table;
247         PERFORM migration_tools.exec( $1, 'CREATE UNLOGGED TABLE ' || migration_schema || '.' || base_staging_table || ' ( LIKE ' || production_table || ' INCLUDING DEFAULTS EXCLUDING CONSTRAINTS );' );
248         PERFORM migration_tools.exec( $1, '
249             INSERT INTO ' || migration_schema || '.fields_requiring_mapping
250                 SELECT table_schema, table_name, column_name, data_type
251                 FROM information_schema.columns 
252                 WHERE table_schema = ''' || migration_schema || ''' AND table_name = ''' || base_staging_table || ''' AND is_nullable = ''NO'' AND column_default IS NULL;
253         ' );
254         FOR columns IN 
255             SELECT table_schema, table_name, column_name, data_type
256             FROM information_schema.columns 
257             WHERE table_schema = migration_schema AND table_name = base_staging_table AND is_nullable = 'NO' AND column_default IS NULL
258         LOOP
259             PERFORM migration_tools.exec( $1, 'ALTER TABLE ' || columns.table_schema || '.' || columns.table_name || ' ALTER COLUMN ' || columns.column_name || ' DROP NOT NULL;' );
260         END LOOP;
261     END;
262 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
263
264 CREATE OR REPLACE FUNCTION migration_tools.create_linked_legacy_table_from (TEXT,TEXT,TEXT) RETURNS VOID AS $$
265     DECLARE
266         migration_schema ALIAS FOR $1;
267         parent_table ALIAS FOR $2;
268         source_table ALIAS FOR $3;
269         columns RECORD;
270         create_sql TEXT;
271         insert_sql TEXT;
272         column_list TEXT := '';
273         column_count INTEGER := 0;
274     BEGIN
275         create_sql := 'CREATE UNLOGGED TABLE ' || migration_schema || '.' || parent_table || '_legacy ( ';
276         FOR columns IN
277             SELECT table_schema, table_name, column_name, data_type
278             FROM information_schema.columns
279             WHERE table_schema = migration_schema AND table_name = source_table
280         LOOP
281             column_count := column_count + 1;
282             if column_count > 1 then
283                 create_sql := create_sql || ', ';
284                 column_list := column_list || ', ';
285             end if;
286             create_sql := create_sql || columns.column_name || ' ';
287             if columns.data_type = 'ARRAY' then
288                 create_sql := create_sql || 'TEXT[]';
289             else
290                 create_sql := create_sql || columns.data_type;
291             end if;
292             column_list := column_list || columns.column_name;
293         END LOOP;
294         create_sql := create_sql || ' ) INHERITS ( ' || migration_schema || '.' || parent_table || ' );';
295         --RAISE INFO 'create_sql = %', create_sql;
296         EXECUTE create_sql;
297         insert_sql := 'INSERT INTO ' || migration_schema || '.' || parent_table || '_legacy (' || column_list || ') SELECT ' || column_list || ' FROM ' || migration_schema || '.' || source_table || ';';
298         --RAISE INFO 'insert_sql = %', insert_sql;
299         EXECUTE insert_sql;
300     END;
301 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
302
303 CREATE OR REPLACE FUNCTION migration_tools.insert_base_into_production (TEXT) RETURNS VOID AS $$
304     DECLARE
305         migration_schema ALIAS FOR $1;
306         production_tables TEXT[];
307     BEGIN
308         --RAISE INFO 'In migration_tools.insert_into_production(%)', migration_schema;
309         SELECT migration_tools.production_tables(migration_schema) INTO STRICT production_tables;
310         FOR i IN array_lower(production_tables,1) .. array_upper(production_tables,1) LOOP
311             PERFORM migration_tools.insert_into_production(migration_schema,production_tables[i]);
312         END LOOP;
313     END;
314 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
315
316 CREATE OR REPLACE FUNCTION migration_tools.insert_into_production (TEXT,TEXT) RETURNS VOID AS $$
317     DECLARE
318         migration_schema ALIAS FOR $1;
319         production_table ALIAS FOR $2;
320         base_staging_table TEXT;
321         columns RECORD;
322     BEGIN
323         base_staging_table = REPLACE( production_table, '.', '_' );
324         --RAISE INFO 'In migration_tools.insert_into_production(%,%) -> %', migration_schema, production_table, base_staging_table;
325         PERFORM migration_tools.exec( $1, 'INSERT INTO ' || production_table || ' SELECT * FROM ' || migration_schema || '.' || base_staging_table || ';' );
326     END;
327 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
328
329 CREATE OR REPLACE FUNCTION migration_tools.name_parse_out_first_middle_last_comma_suffix (TEXT) RETURNS TEXT[] AS $$
330     DECLARE
331         full_name TEXT := $1;
332         before_comma TEXT;
333         family_name TEXT := '';
334         first_given_name TEXT := '';
335         second_given_name TEXT := '';
336         suffix TEXT := '';
337         prefix TEXT := '';
338     BEGIN
339         before_comma := BTRIM( REGEXP_REPLACE(full_name,E'^(.+),.+$',E'\\1') );
340         suffix := CASE WHEN full_name ~ ',' THEN BTRIM( REGEXP_REPLACE(full_name,E'^.+,(.+)$',E'\\1') ) ELSE '' END;
341
342         IF suffix = before_comma THEN
343             suffix := '';
344         END IF;
345
346         family_name := BTRIM( REGEXP_REPLACE(before_comma,E'^.+\\s(.+)$',E'\\1') );
347         first_given_name := BTRIM( REGEXP_REPLACE(before_comma,E'^(.+?)\\s.+$',E'\\1') );
348         second_given_name := BTRIM( CASE WHEN before_comma ~ '^.+\s.+\s.+$' THEN REGEXP_REPLACE(before_comma,E'^.+\\s(.+)\\s.+$',E'\\1') ELSE '' END );
349
350         RETURN ARRAY[ family_name, prefix, first_given_name, second_given_name, suffix ];
351     END;
352 $$ LANGUAGE PLPGSQL STRICT IMMUTABLE;
353
354 CREATE OR REPLACE FUNCTION migration_tools.name_parse_out_last_comma_prefix_first_middle_suffix (TEXT) RETURNS TEXT[] AS $$
355     DECLARE
356         full_name TEXT := $1;
357         temp TEXT;
358         family_name TEXT := '';
359         first_given_name TEXT := '';
360         second_given_name TEXT := '';
361         suffix TEXT := '';
362         prefix TEXT := '';
363     BEGIN
364         temp := full_name;
365         -- Use values, not structure, for prefix/suffix, unless we come up with a better idea
366         IF temp ilike '%MR.%' THEN
367             prefix := 'Mr.';
368             temp := REGEXP_REPLACE( temp, E'MR\.\\s*', '', 'i' );
369         END IF;
370         IF temp ilike '%MRS.%' THEN
371             prefix := 'Mrs.';
372             temp := REGEXP_REPLACE( temp, E'MRS\.\\s*', '', 'i' );
373         END IF;
374         IF temp ilike '%MS.%' THEN
375             prefix := 'Ms.';
376             temp := REGEXP_REPLACE( temp, E'MS\.\\s*', '', 'i' );
377         END IF;
378         IF temp ilike '%DR.%' THEN
379             prefix := 'Dr.';
380             temp := REGEXP_REPLACE( temp, E'DR\.\\s*', '', 'i' );
381         END IF;
382         IF temp ilike '%JR%' THEN
383             suffix := 'Jr.';
384             temp := REGEXP_REPLACE( temp, E'JR\.?\\s*', '', 'i' );
385         END IF;
386         IF temp ilike '%JR,%' THEN
387             suffix := 'Jr.';
388             temp := REGEXP_REPLACE( temp, E'JR,\\s*', ',', 'i' );
389         END IF;
390         IF temp ilike '%SR%' THEN
391             suffix := 'Sr.';
392             temp := REGEXP_REPLACE( temp, E'SR\.?\\s*', '', 'i' );
393         END IF;
394         IF temp ilike '%SR,%' THEN
395             suffix := 'Sr.';
396             temp := REGEXP_REPLACE( temp, E'SR,\\s*', ',', 'i' );
397         END IF;
398         IF temp ~ E'\\sII$' THEN
399             suffix := 'II';
400             temp := REGEXP_REPLACE( temp, E'II$', '', 'i' );
401         END IF;
402         IF temp ~ E'\\sIII$' THEN
403             suffix := 'III';
404             temp := REGEXP_REPLACE( temp, E'III$', '', 'i' );
405         END IF;
406         IF temp ~ E'\\sIV$' THEN
407             suffix := 'IV';
408             temp := REGEXP_REPLACE( temp, E'IV$', '', 'i' );
409         END IF;
410
411         family_name := BTRIM( REGEXP_REPLACE(temp,E'^([^,]*)\\s*,.*$',E'\\1') );
412         first_given_name := BTRIM( CASE WHEN temp ~ ',' THEN REGEXP_REPLACE(temp,E'^[^,]*\\s*,\\s*([^,\\s]*)\\s*.*$',E'\\1') ELSE 'N/A' END );
413         second_given_name := BTRIM( CASE WHEN temp ~ ',' THEN REGEXP_REPLACE(temp,E'^[^,]*\\s*,\\s*[^,\\s]*\\s*(.*)$',E'\\1') ELSE ''  END );
414
415         RETURN ARRAY[ family_name, prefix, first_given_name, second_given_name, suffix ];
416     END;
417 $$ LANGUAGE PLPGSQL STRICT IMMUTABLE;
418
419 CREATE OR REPLACE FUNCTION migration_tools.name_parse_out_last_first_middle_and_random_affix (TEXT) RETURNS TEXT[] AS $$
420     DECLARE
421         full_name TEXT := $1;
422         temp TEXT;
423         family_name TEXT := '';
424         first_given_name TEXT := '';
425         second_given_name TEXT := '';
426         suffix TEXT := '';
427         prefix TEXT := '';
428     BEGIN
429         temp := full_name;
430         -- Use values, not structure, for prefix/suffix, unless we come up with a better idea
431         IF temp ilike '%MR.%' THEN
432             prefix := 'Mr.';
433             temp := REGEXP_REPLACE( temp, E'MR\.\\s*', '', 'i' );
434         END IF;
435         IF temp ilike '%MRS.%' THEN
436             prefix := 'Mrs.';
437             temp := REGEXP_REPLACE( temp, E'MRS\.\\s*', '', 'i' );
438         END IF;
439         IF temp ilike '%MS.%' THEN
440             prefix := 'Ms.';
441             temp := REGEXP_REPLACE( temp, E'MS\.\\s*', '', 'i' );
442         END IF;
443         IF temp ilike '%DR.%' THEN
444             prefix := 'Dr.';
445             temp := REGEXP_REPLACE( temp, E'DR\.\\s*', '', 'i' );
446         END IF;
447         IF temp ilike '%JR.%' THEN
448             suffix := 'Jr.';
449             temp := REGEXP_REPLACE( temp, E'JR\.\\s*', '', 'i' );
450         END IF;
451         IF temp ilike '%JR,%' THEN
452             suffix := 'Jr.';
453             temp := REGEXP_REPLACE( temp, E'JR,\\s*', ',', 'i' );
454         END IF;
455         IF temp ilike '%SR.%' THEN
456             suffix := 'Sr.';
457             temp := REGEXP_REPLACE( temp, E'SR\.\\s*', '', 'i' );
458         END IF;
459         IF temp ilike '%SR,%' THEN
460             suffix := 'Sr.';
461             temp := REGEXP_REPLACE( temp, E'SR,\\s*', ',', 'i' );
462         END IF;
463         IF temp like '%III%' THEN
464             suffix := 'III';
465             temp := REGEXP_REPLACE( temp, E'III', '' );
466         END IF;
467         IF temp like '%II%' THEN
468             suffix := 'II';
469             temp := REGEXP_REPLACE( temp, E'II', '' );
470         END IF;
471         IF temp like '%IV%' THEN
472             suffix := 'IV';
473             temp := REGEXP_REPLACE( temp, E'IV', '' );
474         END IF;
475
476         temp := REGEXP_REPLACE( temp, '\(\)', '');
477         family_name := BTRIM( REGEXP_REPLACE(temp,E'^(\\S+).*$',E'\\1') );
478         family_name := REGEXP_REPLACE( family_name, ',', '' );
479         first_given_name := CASE WHEN temp ~ E'^\\S+$' THEN 'N/A' ELSE BTRIM( REGEXP_REPLACE(temp,E'^\\S+\\s+(\\S+).*$',E'\\1') ) END;
480         first_given_name := REGEXP_REPLACE( first_given_name, ',', '' );
481         second_given_name := CASE WHEN temp ~ E'^\\S+$' THEN '' ELSE BTRIM( REGEXP_REPLACE(temp,E'^\\S+\\s+\\S+\\s*(.*)$',E'\\1') ) END;
482         second_given_name := REGEXP_REPLACE( second_given_name, ',', '' );
483
484         RETURN ARRAY[ family_name, prefix, first_given_name, second_given_name, suffix ];
485     END;
486 $$ LANGUAGE PLPGSQL STRICT IMMUTABLE;
487
488 CREATE OR REPLACE FUNCTION migration_tools.name_parse_out_fuller_last_first_middle_and_random_affix (TEXT) RETURNS TEXT[] AS $$
489     DECLARE
490         full_name TEXT := $1;
491         temp TEXT;
492         family_name TEXT := '';
493         first_given_name TEXT := '';
494         second_given_name TEXT := '';
495         suffix TEXT := '';
496         prefix TEXT := '';
497     BEGIN
498         temp := BTRIM(full_name);
499         -- Use values, not structure, for prefix/suffix, unless we come up with a better idea
500         --IF temp ~ '^\S{2,}\.' THEN
501         --    prefix := REGEXP_REPLACE(temp, '^(\S{2,}\.).*$','\1');
502         --    temp := BTRIM(REGEXP_REPLACE(temp, '^\S{2,}\.(.*)$','\1'));
503         --END IF;
504         --IF temp ~ '\S{2,}\.$' THEN
505         --    suffix := REGEXP_REPLACE(temp, '^.*(\S{2,}\.)$','\1');
506         --    temp := REGEXP_REPLACE(temp, '^(.*)\S{2,}\.$','\1');
507         --END IF;
508         IF temp ilike '%MR.%' THEN
509             prefix := 'Mr.';
510             temp := BTRIM(REGEXP_REPLACE( temp, E'MR\.\\s*', '', 'i' ));
511         END IF;
512         IF temp ilike '%MRS.%' THEN
513             prefix := 'Mrs.';
514             temp := BTRIM(REGEXP_REPLACE( temp, E'MRS\.\\s*', '', 'i' ));
515         END IF;
516         IF temp ilike '%MS.%' THEN
517             prefix := 'Ms.';
518             temp := BTRIM(REGEXP_REPLACE( temp, E'MS\.\\s*', '', 'i' ));
519         END IF;
520         IF temp ilike '%DR.%' THEN
521             prefix := 'Dr.';
522             temp := BTRIM(REGEXP_REPLACE( temp, E'DR\.\\s*', '', 'i' ));
523         END IF;
524         IF temp ilike '%JR.%' THEN
525             suffix := 'Jr.';
526             temp := BTRIM(REGEXP_REPLACE( temp, E'JR\.\\s*', '', 'i' ));
527         END IF;
528         IF temp ilike '%JR,%' THEN
529             suffix := 'Jr.';
530             temp := BTRIM(REGEXP_REPLACE( temp, E'JR,\\s*', ',', 'i' ));
531         END IF;
532         IF temp ilike '%SR.%' THEN
533             suffix := 'Sr.';
534             temp := BTRIM(REGEXP_REPLACE( temp, E'SR\.\\s*', '', 'i' ));
535         END IF;
536         IF temp ilike '%SR,%' THEN
537             suffix := 'Sr.';
538             temp := BTRIM(REGEXP_REPLACE( temp, E'SR,\\s*', ',', 'i' ));
539         END IF;
540         IF temp like '%III%' THEN
541             suffix := 'III';
542             temp := BTRIM(REGEXP_REPLACE( temp, E'III', '' ));
543         END IF;
544         IF temp like '%II%' THEN
545             suffix := 'II';
546             temp := BTRIM(REGEXP_REPLACE( temp, E'II', '' ));
547         END IF;
548
549         IF temp ~ ',' THEN
550             family_name = BTRIM(REGEXP_REPLACE(temp,'^(.*?,).*$','\1'));
551             temp := BTRIM(REPLACE( temp, family_name, '' ));
552             family_name := REPLACE( family_name, ',', '' );
553             IF temp ~ ' ' THEN
554                 first_given_name := BTRIM( REGEXP_REPLACE(temp,'^(.+)\s(.+)$','\1') );
555                 second_given_name := BTRIM( REGEXP_REPLACE(temp,'^(.+)\s(.+)$','\2') );
556             ELSE
557                 first_given_name := temp;
558                 second_given_name := '';
559             END IF;
560         ELSE
561             IF temp ~ '^\S+\s+\S+\s+\S+$' THEN
562                 first_given_name := BTRIM( REGEXP_REPLACE(temp,'^(\S+)\s*(\S+)\s*(\S+)$','\1') );
563                 second_given_name := BTRIM( REGEXP_REPLACE(temp,'^(\S+)\s*(\S+)\s*(\S+)$','\2') );
564                 family_name := BTRIM( REGEXP_REPLACE(temp,'^(\S+)\s*(\S+)\s*(\S+)$','\3') );
565             ELSE
566                 first_given_name := BTRIM( REGEXP_REPLACE(temp,'^(\S+)\s*(\S+)$','\1') );
567                 second_given_name := temp;
568                 family_name := BTRIM( REGEXP_REPLACE(temp,'^(\S+)\s*(\S+)$','\2') );
569             END IF;
570         END IF;
571
572         RETURN ARRAY[ family_name, prefix, first_given_name, second_given_name, suffix ];
573     END;
574 $$ LANGUAGE PLPGSQL STRICT IMMUTABLE;
575
576 CREATE OR REPLACE FUNCTION migration_tools.name_parse_out_fuller_last_first_middle_and_random_affix2 (TEXT) RETURNS TEXT[] AS $$
577     DECLARE
578         full_name TEXT := $1;
579         temp TEXT;
580         family_name TEXT := '';
581         first_given_name TEXT := '';
582         second_given_name TEXT := '';
583         suffix TEXT := '';
584         prefix TEXT := '';
585     BEGIN
586         temp := BTRIM(full_name);
587         -- Use values, not structure, for prefix/suffix, unless we come up with a better idea
588         --IF temp ~ '^\S{2,}\.' THEN
589         --    prefix := REGEXP_REPLACE(temp, '^(\S{2,}\.).*$','\1');
590         --    temp := BTRIM(REGEXP_REPLACE(temp, '^\S{2,}\.(.*)$','\1'));
591         --END IF;
592         --IF temp ~ '\S{2,}\.$' THEN
593         --    suffix := REGEXP_REPLACE(temp, '^.*(\S{2,}\.)$','\1');
594         --    temp := REGEXP_REPLACE(temp, '^(.*)\S{2,}\.$','\1');
595         --END IF;
596         IF temp ilike '%MR.%' THEN
597             prefix := 'Mr.';
598             temp := BTRIM(REGEXP_REPLACE( temp, E'MR\.\\s*', '', 'i' ));
599         END IF;
600         IF temp ilike '%MRS.%' THEN
601             prefix := 'Mrs.';
602             temp := BTRIM(REGEXP_REPLACE( temp, E'MRS\.\\s*', '', 'i' ));
603         END IF;
604         IF temp ilike '%MS.%' THEN
605             prefix := 'Ms.';
606             temp := BTRIM(REGEXP_REPLACE( temp, E'MS\.\\s*', '', 'i' ));
607         END IF;
608         IF temp ilike '%DR.%' THEN
609             prefix := 'Dr.';
610             temp := BTRIM(REGEXP_REPLACE( temp, E'DR\.\\s*', '', 'i' ));
611         END IF;
612         IF temp ilike '%JR.%' THEN
613             suffix := 'Jr.';
614             temp := BTRIM(REGEXP_REPLACE( temp, E'JR\.\\s*', '', 'i' ));
615         END IF;
616         IF temp ilike '%JR,%' THEN
617             suffix := 'Jr.';
618             temp := BTRIM(REGEXP_REPLACE( temp, E'JR,\\s*', ',', 'i' ));
619         END IF;
620         IF temp ilike '%SR.%' THEN
621             suffix := 'Sr.';
622             temp := BTRIM(REGEXP_REPLACE( temp, E'SR\.\\s*', '', 'i' ));
623         END IF;
624         IF temp ilike '%SR,%' THEN
625             suffix := 'Sr.';
626             temp := BTRIM(REGEXP_REPLACE( temp, E'SR,\\s*', ',', 'i' ));
627         END IF;
628         IF temp like '%III%' THEN
629             suffix := 'III';
630             temp := BTRIM(REGEXP_REPLACE( temp, E'III', '' ));
631         END IF;
632         IF temp like '%II%' THEN
633             suffix := 'II';
634             temp := BTRIM(REGEXP_REPLACE( temp, E'II', '' ));
635         END IF;
636
637         IF temp ~ ',' THEN
638             family_name = BTRIM(REGEXP_REPLACE(temp,'^(.*?,).*$','\1'));
639             temp := BTRIM(REPLACE( temp, family_name, '' ));
640             family_name := REPLACE( family_name, ',', '' );
641             IF temp ~ ' ' THEN
642                 first_given_name := BTRIM( REGEXP_REPLACE(temp,'^(.+)\s(.+)$','\1') );
643                 second_given_name := BTRIM( REGEXP_REPLACE(temp,'^(.+)\s(.+)$','\2') );
644             ELSE
645                 first_given_name := temp;
646                 second_given_name := '';
647             END IF;
648         ELSE
649             IF temp ~ '^\S+\s+\S+\s+\S+$' THEN
650                 first_given_name := BTRIM( REGEXP_REPLACE(temp,'^(\S+)\s*(\S+)\s*(\S+)$','\1') );
651                 second_given_name := BTRIM( REGEXP_REPLACE(temp,'^(\S+)\s*(\S+)\s*(\S+)$','\2') );
652                 family_name := BTRIM( REGEXP_REPLACE(temp,'^(\S+)\s*(\S+)\s*(\S+)$','\3') );
653             ELSE
654                 first_given_name := BTRIM( REGEXP_REPLACE(temp,'^(\S+)\s*(\S+)$','\1') );
655                 second_given_name := temp;
656                 family_name := BTRIM( REGEXP_REPLACE(temp,'^(\S+)\s*(\S+)$','\2') );
657             END IF;
658         END IF;
659
660         family_name := BTRIM(REPLACE(REPLACE(family_name,',',''),'"',''));
661         first_given_name := BTRIM(REPLACE(REPLACE(first_given_name,',',''),'"',''));
662         second_given_name := BTRIM(REPLACE(REPLACE(second_given_name,',',''),'"',''));
663
664         RETURN ARRAY[ family_name, prefix, first_given_name, second_given_name, suffix ];
665     END;
666 $$ LANGUAGE PLPGSQL STRICT IMMUTABLE;
667
668 CREATE OR REPLACE FUNCTION migration_tools.address_parse_out_citystatezip (TEXT) RETURNS TEXT[] AS $$
669     DECLARE
670         city_state_zip TEXT := $1;
671         city TEXT := '';
672         state TEXT := '';
673         zip TEXT := '';
674     BEGIN
675         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;
676         city_state_zip := REGEXP_REPLACE( city_state_zip, E'^(.*)\\d\\d\\d\\d\\d-?\\d*(.*)$', E'\\1\\2');
677         IF city_state_zip ~ ',' THEN
678             state := REGEXP_REPLACE( city_state_zip, E'^(.*),(.*)$', E'\\2');
679             city := REGEXP_REPLACE( city_state_zip, E'^(.*),(.*)$', E'\\1');
680         ELSE
681             IF city_state_zip ~ E'\\s+[A-Z][A-Z]\\s*$' THEN
682                 state := REGEXP_REPLACE( city_state_zip, E'^.*,?\\s+([A-Z][A-Z])\\s*$', E'\\1' );
683                 city := REGEXP_REPLACE( city_state_zip, E'^(.*?),?\\s+[A-Z][A-Z](\\s*)$', E'\\1\\2' );
684             ELSE
685                 IF city_state_zip ~ E'^\\S+$'  THEN
686                     city := city_state_zip;
687                     state := 'N/A';
688                 ELSE
689                     state := REGEXP_REPLACE( city_state_zip, E'^(.*?),?\\s*(\\S+)\\s*$', E'\\2');
690                     city := REGEXP_REPLACE( city_state_zip, E'^(.*?),?\\s*(\\S+)\\s*$', E'\\1');
691                 END IF;
692             END IF;
693         END IF;
694         RETURN ARRAY[ TRIM(BOTH ' ' FROM city), TRIM(BOTH ' ' FROM state), TRIM(BOTH ' ' FROM zip) ];
695     END;
696 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
697
698 -- try to parse data like this: 100 MAIN ST$COVINGTON, GA 30016
699 CREATE OR REPLACE FUNCTION migration_tools.parse_out_address (TEXT) RETURNS TEXT[] AS $$
700     DECLARE
701         fullstring TEXT := $1;
702         address1 TEXT := '';
703         address2 TEXT := '';
704         scratch1 TEXT := '';
705         scratch2 TEXT := '';
706         city TEXT := '';
707         state TEXT := '';
708         zip TEXT := '';
709     BEGIN
710         zip := CASE
711             WHEN fullstring ~ E'\\d\\d\\d\\d\\d'
712             THEN REGEXP_REPLACE( fullstring, E'^.*(\\d\\d\\d\\d\\d-?\\d*).*$', E'\\1' )
713             ELSE ''
714         END;
715         fullstring := REGEXP_REPLACE( fullstring, E'^(.*)\\d\\d\\d\\d\\d-?\\d*(.*)$', E'\\1\\2');
716
717         IF fullstring ~ ',' THEN
718             state := REGEXP_REPLACE( fullstring, E'^(.*),(.*)$', E'\\2');
719             scratch1 := REGEXP_REPLACE( fullstring, E'^(.*),(.*)$', E'\\1');
720         ELSE
721             IF fullstring ~ E'\\s+[A-Z][A-Z]\\s*$' THEN
722                 state := REGEXP_REPLACE( fullstring, E'^.*,?\\s+([A-Z][A-Z])\\s*$', E'\\1' );
723                 scratch1 := REGEXP_REPLACE( fullstring, E'^(.*?),?\\s+[A-Z][A-Z](\\s*)$', E'\\1\\2' );
724             ELSE
725                 IF fullstring ~ E'^\\S+$'  THEN
726                     scratch1 := fullstring;
727                     state := 'N/A';
728                 ELSE
729                     state := REGEXP_REPLACE( fullstring, E'^(.*?),?\\s*(\\S+)\\s*$', E'\\2');
730                     scratch1 := REGEXP_REPLACE( fullstring, E'^(.*?),?\\s*(\\S+)\\s*$', E'\\1');
731                 END IF;
732             END IF;
733         END IF;
734
735         IF scratch1 ~ '[\$]' THEN
736             scratch2 := REGEXP_REPLACE( scratch1, E'^(.+)[\$](.+?)$', E'\\1');
737             city := REGEXP_REPLACE( scratch1, E'^(.+)[\$](.+?)$', E'\\2');
738         ELSE
739             IF scratch1 ~ '\s' THEN
740                 scratch2 := REGEXP_REPLACE( scratch1, E'^(.+)\\s+(.+?)$', E'\\1');
741                 city := REGEXP_REPLACE( scratch1, E'^(.+)\\s+(.+?)$', E'\\2');
742             ELSE
743                 scratch2 := 'N/A';
744                 city := scratch1;
745             END IF;
746         END IF;
747
748         IF scratch2 ~ '^\d' THEN
749             address1 := scratch2;
750             address2 := '';
751         ELSE
752             address1 := REGEXP_REPLACE( scratch2, E'^(.+?)(\\d.+)$', E'\\1');
753             address2 := REGEXP_REPLACE( scratch2, E'^(.+?)(\\d.+)$', E'\\2');
754         END IF;
755
756         RETURN ARRAY[
757              TRIM(BOTH ' ' FROM address1)
758             ,TRIM(BOTH ' ' FROM address2)
759             ,TRIM(BOTH ' ' FROM city)
760             ,TRIM(BOTH ' ' FROM state)
761             ,TRIM(BOTH ' ' FROM zip)
762         ];
763     END;
764 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
765
766 CREATE OR REPLACE FUNCTION migration_tools.parse_out_address2 (TEXT) RETURNS TEXT AS $$
767     my ($address) = @_;
768
769     use Geo::StreetAddress::US;
770
771     my $a = Geo::StreetAddress::US->parse_location($address);
772
773     return [
774          "$a->{number} $a->{prefix} $a->{street} $a->{type} $a->{suffix}"
775         ,"$a->{sec_unit_type} $a->{sec_unit_num}"
776         ,$a->{city}
777         ,$a->{state}
778         ,$a->{zip}
779     ];
780 $$ LANGUAGE PLPERLU STABLE;
781
782 DROP TABLE IF EXISTS migration_tools.usps_suffixes;
783 CREATE UNLOGGED TABLE migration_tools.usps_suffixes ( suffix_from TEXT, suffix_to TEXT );
784 INSERT INTO migration_tools.usps_suffixes VALUES
785     ('ALLEE','ALY'),
786     ('ALLEY','ALY'),
787     ('ALLY','ALY'),
788     ('ALY','ALY'),
789     ('ANEX','ANX'),
790     ('ANNEX','ANX'),
791     ('ANNX','ANX'),
792     ('ANX','ANX'),
793     ('ARCADE','ARC'),
794     ('ARC','ARC'),
795     ('AV','AVE'),
796     ('AVE','AVE'),
797     ('AVEN','AVE'),
798     ('AVENU','AVE'),
799     ('AVENUE','AVE'),
800     ('AVN','AVE'),
801     ('AVNUE','AVE'),
802     ('BAYOO','BYU'),
803     ('BAYOU','BYU'),
804     ('BCH','BCH'),
805     ('BEACH','BCH'),
806     ('BEND','BND'),
807     ('BLF','BLF'),
808     ('BLUF','BLF'),
809     ('BLUFF','BLF'),
810     ('BLUFFS','BLFS'),
811     ('BLVD','BLVD'),
812     ('BND','BND'),
813     ('BOT','BTM'),
814     ('BOTTM','BTM'),
815     ('BOTTOM','BTM'),
816     ('BOUL','BLVD'),
817     ('BOULEVARD','BLVD'),
818     ('BOULV','BLVD'),
819     ('BRANCH','BR'),
820     ('BR','BR'),
821     ('BRDGE','BRG'),
822     ('BRG','BRG'),
823     ('BRIDGE','BRG'),
824     ('BRK','BRK'),
825     ('BRNCH','BR'),
826     ('BROOK','BRK'),
827     ('BROOKS','BRKS'),
828     ('BTM','BTM'),
829     ('BURG','BG'),
830     ('BURGS','BGS'),
831     ('BYPA','BYP'),
832     ('BYPAS','BYP'),
833     ('BYPASS','BYP'),
834     ('BYP','BYP'),
835     ('BYPS','BYP'),
836     ('CAMP','CP'),
837     ('CANYN','CYN'),
838     ('CANYON','CYN'),
839     ('CAPE','CPE'),
840     ('CAUSEWAY','CSWY'),
841     ('CAUSWAY','CSWY'),
842     ('CEN','CTR'),
843     ('CENT','CTR'),
844     ('CENTER','CTR'),
845     ('CENTERS','CTRS'),
846     ('CENTR','CTR'),
847     ('CENTRE','CTR'),
848     ('CIRC','CIR'),
849     ('CIR','CIR'),
850     ('CIRCL','CIR'),
851     ('CIRCLE','CIR'),
852     ('CIRCLES','CIRS'),
853     ('CK','CRK'),
854     ('CLB','CLB'),
855     ('CLF','CLF'),
856     ('CLFS','CLFS'),
857     ('CLIFF','CLF'),
858     ('CLIFFS','CLFS'),
859     ('CLUB','CLB'),
860     ('CMP','CP'),
861     ('CNTER','CTR'),
862     ('CNTR','CTR'),
863     ('CNYN','CYN'),
864     ('COMMON','CMN'),
865     ('COR','COR'),
866     ('CORNER','COR'),
867     ('CORNERS','CORS'),
868     ('CORS','CORS'),
869     ('COURSE','CRSE'),
870     ('COURT','CT'),
871     ('COURTS','CTS'),
872     ('COVE','CV'),
873     ('COVES','CVS'),
874     ('CP','CP'),
875     ('CPE','CPE'),
876     ('CRCL','CIR'),
877     ('CRCLE','CIR'),
878     ('CR','CRK'),
879     ('CRECENT','CRES'),
880     ('CREEK','CRK'),
881     ('CRESCENT','CRES'),
882     ('CRES','CRES'),
883     ('CRESENT','CRES'),
884     ('CREST','CRST'),
885     ('CRK','CRK'),
886     ('CROSSING','XING'),
887     ('CROSSROAD','XRD'),
888     ('CRSCNT','CRES'),
889     ('CRSE','CRSE'),
890     ('CRSENT','CRES'),
891     ('CRSNT','CRES'),
892     ('CRSSING','XING'),
893     ('CRSSNG','XING'),
894     ('CRT','CT'),
895     ('CSWY','CSWY'),
896     ('CT','CT'),
897     ('CTR','CTR'),
898     ('CTS','CTS'),
899     ('CURVE','CURV'),
900     ('CV','CV'),
901     ('CYN','CYN'),
902     ('DALE','DL'),
903     ('DAM','DM'),
904     ('DIV','DV'),
905     ('DIVIDE','DV'),
906     ('DL','DL'),
907     ('DM','DM'),
908     ('DR','DR'),
909     ('DRIV','DR'),
910     ('DRIVE','DR'),
911     ('DRIVES','DRS'),
912     ('DRV','DR'),
913     ('DVD','DV'),
914     ('DV','DV'),
915     ('ESTATE','EST'),
916     ('ESTATES','ESTS'),
917     ('EST','EST'),
918     ('ESTS','ESTS'),
919     ('EXP','EXPY'),
920     ('EXPRESS','EXPY'),
921     ('EXPRESSWAY','EXPY'),
922     ('EXPR','EXPY'),
923     ('EXPW','EXPY'),
924     ('EXPY','EXPY'),
925     ('EXTENSION','EXT'),
926     ('EXTENSIONS','EXTS'),
927     ('EXT','EXT'),
928     ('EXTN','EXT'),
929     ('EXTNSN','EXT'),
930     ('EXTS','EXTS'),
931     ('FALL','FALL'),
932     ('FALLS','FLS'),
933     ('FERRY','FRY'),
934     ('FIELD','FLD'),
935     ('FIELDS','FLDS'),
936     ('FLAT','FLT'),
937     ('FLATS','FLTS'),
938     ('FLD','FLD'),
939     ('FLDS','FLDS'),
940     ('FLS','FLS'),
941     ('FLT','FLT'),
942     ('FLTS','FLTS'),
943     ('FORD','FRD'),
944     ('FORDS','FRDS'),
945     ('FOREST','FRST'),
946     ('FORESTS','FRST'),
947     ('FORGE','FRG'),
948     ('FORGES','FRGS'),
949     ('FORG','FRG'),
950     ('FORK','FRK'),
951     ('FORKS','FRKS'),
952     ('FORT','FT'),
953     ('FRD','FRD'),
954     ('FREEWAY','FWY'),
955     ('FREEWY','FWY'),
956     ('FRG','FRG'),
957     ('FRK','FRK'),
958     ('FRKS','FRKS'),
959     ('FRRY','FRY'),
960     ('FRST','FRST'),
961     ('FRT','FT'),
962     ('FRWAY','FWY'),
963     ('FRWY','FWY'),
964     ('FRY','FRY'),
965     ('FT','FT'),
966     ('FWY','FWY'),
967     ('GARDEN','GDN'),
968     ('GARDENS','GDNS'),
969     ('GARDN','GDN'),
970     ('GATEWAY','GTWY'),
971     ('GATEWY','GTWY'),
972     ('GATWAY','GTWY'),
973     ('GDN','GDN'),
974     ('GDNS','GDNS'),
975     ('GLEN','GLN'),
976     ('GLENS','GLNS'),
977     ('GLN','GLN'),
978     ('GRDEN','GDN'),
979     ('GRDN','GDN'),
980     ('GRDNS','GDNS'),
981     ('GREEN','GRN'),
982     ('GREENS','GRNS'),
983     ('GRN','GRN'),
984     ('GROVE','GRV'),
985     ('GROVES','GRVS'),
986     ('GROV','GRV'),
987     ('GRV','GRV'),
988     ('GTWAY','GTWY'),
989     ('GTWY','GTWY'),
990     ('HARB','HBR'),
991     ('HARBOR','HBR'),
992     ('HARBORS','HBRS'),
993     ('HARBR','HBR'),
994     ('HAVEN','HVN'),
995     ('HAVN','HVN'),
996     ('HBR','HBR'),
997     ('HEIGHT','HTS'),
998     ('HEIGHTS','HTS'),
999     ('HGTS','HTS'),
1000     ('HIGHWAY','HWY'),
1001     ('HIGHWY','HWY'),
1002     ('HILL','HL'),
1003     ('HILLS','HLS'),
1004     ('HIWAY','HWY'),
1005     ('HIWY','HWY'),
1006     ('HL','HL'),
1007     ('HLLW','HOLW'),
1008     ('HLS','HLS'),
1009     ('HOLLOW','HOLW'),
1010     ('HOLLOWS','HOLW'),
1011     ('HOLW','HOLW'),
1012     ('HOLWS','HOLW'),
1013     ('HRBOR','HBR'),
1014     ('HT','HTS'),
1015     ('HTS','HTS'),
1016     ('HVN','HVN'),
1017     ('HWAY','HWY'),
1018     ('HWY','HWY'),
1019     ('INLET','INLT'),
1020     ('INLT','INLT'),
1021     ('IS','IS'),
1022     ('ISLAND','IS'),
1023     ('ISLANDS','ISS'),
1024     ('ISLANDS','SLNDS'),
1025     ('ISLANDS','SS'),
1026     ('ISLE','ISLE'),
1027     ('ISLES','ISLE'),
1028     ('ISLND','IS'),
1029     ('I','SLNDS'),
1030     ('ISS','ISS'),
1031     ('JCTION','JCT'),
1032     ('JCT','JCT'),
1033     ('JCTN','JCT'),
1034     ('JCTNS','JCTS'),
1035     ('JCTS','JCTS'),
1036     ('JUNCTION','JCT'),
1037     ('JUNCTIONS','JCTS'),
1038     ('JUNCTN','JCT'),
1039     ('JUNCTON','JCT'),
1040     ('KEY','KY'),
1041     ('KEYS','KYS'),
1042     ('KNL','KNL'),
1043     ('KNLS','KNLS'),
1044     ('KNOL','KNL'),
1045     ('KNOLL','KNL'),
1046     ('KNOLLS','KNLS'),
1047     ('KY','KY'),
1048     ('KYS','KYS'),
1049     ('LAKE','LK'),
1050     ('LAKES','LKS'),
1051     ('LA','LN'),
1052     ('LANDING','LNDG'),
1053     ('LAND','LAND'),
1054     ('LANE','LN'),
1055     ('LANES','LN'),
1056     ('LCK','LCK'),
1057     ('LCKS','LCKS'),
1058     ('LDGE','LDG'),
1059     ('LDG','LDG'),
1060     ('LF','LF'),
1061     ('LGT','LGT'),
1062     ('LIGHT','LGT'),
1063     ('LIGHTS','LGTS'),
1064     ('LK','LK'),
1065     ('LKS','LKS'),
1066     ('LNDG','LNDG'),
1067     ('LNDNG','LNDG'),
1068     ('LN','LN'),
1069     ('LOAF','LF'),
1070     ('LOCK','LCK'),
1071     ('LOCKS','LCKS'),
1072     ('LODGE','LDG'),
1073     ('LODG','LDG'),
1074     ('LOOP','LOOP'),
1075     ('LOOPS','LOOP'),
1076     ('MALL','MALL'),
1077     ('MANOR','MNR'),
1078     ('MANORS','MNRS'),
1079     ('MDW','MDW'),
1080     ('MDWS','MDWS'),
1081     ('MEADOW','MDW'),
1082     ('MEADOWS','MDWS'),
1083     ('MEDOWS','MDWS'),
1084     ('MEWS','MEWS'),
1085     ('MILL','ML'),
1086     ('MILLS','MLS'),
1087     ('MISSION','MSN'),
1088     ('MISSN','MSN'),
1089     ('ML','ML'),
1090     ('MLS','MLS'),
1091     ('MNR','MNR'),
1092     ('MNRS','MNRS'),
1093     ('MNTAIN','MTN'),
1094     ('MNT','MT'),
1095     ('MNTN','MTN'),
1096     ('MNTNS','MTNS'),
1097     ('MOTORWAY','MTWY'),
1098     ('MOUNTAIN','MTN'),
1099     ('MOUNTAINS','MTNS'),
1100     ('MOUNTIN','MTN'),
1101     ('MOUNT','MT'),
1102     ('MSN','MSN'),
1103     ('MSSN','MSN'),
1104     ('MTIN','MTN'),
1105     ('MT','MT'),
1106     ('MTN','MTN'),
1107     ('NCK','NCK'),
1108     ('NECK','NCK'),
1109     ('ORCHARD','ORCH'),
1110     ('ORCH','ORCH'),
1111     ('ORCHRD','ORCH'),
1112     ('OVAL','OVAL'),
1113     ('OVERPASS','OPAS'),
1114     ('OVL','OVAL'),
1115     ('PARK','PARK'),
1116     ('PARKS','PARK'),
1117     ('PARKWAY','PKWY'),
1118     ('PARKWAYS','PKWY'),
1119     ('PARKWY','PKWY'),
1120     ('PASSAGE','PSGE'),
1121     ('PASS','PASS'),
1122     ('PATH','PATH'),
1123     ('PATHS','PATH'),
1124     ('PIKE','PIKE'),
1125     ('PIKES','PIKE'),
1126     ('PINE','PNE'),
1127     ('PINES','PNES'),
1128     ('PK','PARK'),
1129     ('PKWAY','PKWY'),
1130     ('PKWY','PKWY'),
1131     ('PKWYS','PKWY'),
1132     ('PKY','PKWY'),
1133     ('PLACE','PL'),
1134     ('PLAINES','PLNS'),
1135     ('PLAIN','PLN'),
1136     ('PLAINS','PLNS'),
1137     ('PLAZA','PLZ'),
1138     ('PLN','PLN'),
1139     ('PLNS','PLNS'),
1140     ('PL','PL'),
1141     ('PLZA','PLZ'),
1142     ('PLZ','PLZ'),
1143     ('PNES','PNES'),
1144     ('POINT','PT'),
1145     ('POINTS','PTS'),
1146     ('PORT','PRT'),
1147     ('PORTS','PRTS'),
1148     ('PRAIRIE','PR'),
1149     ('PRARIE','PR'),
1150     ('PRK','PARK'),
1151     ('PR','PR'),
1152     ('PRR','PR'),
1153     ('PRT','PRT'),
1154     ('PRTS','PRTS'),
1155     ('PT','PT'),
1156     ('PTS','PTS'),
1157     ('RADIAL','RADL'),
1158     ('RADIEL','RADL'),
1159     ('RADL','RADL'),
1160     ('RAD','RADL'),
1161     ('RAMP','RAMP'),
1162     ('RANCHES','RNCH'),
1163     ('RANCH','RNCH'),
1164     ('RAPID','RPD'),
1165     ('RAPIDS','RPDS'),
1166     ('RDGE','RDG'),
1167     ('RDG','RDG'),
1168     ('RDGS','RDGS'),
1169     ('RD','RD'),
1170     ('RDS','RDS'),
1171     ('REST','RST'),
1172     ('RIDGE','RDG'),
1173     ('RIDGES','RDGS'),
1174     ('RIVER','RIV'),
1175     ('RIV','RIV'),
1176     ('RIVR','RIV'),
1177     ('RNCH','RNCH'),
1178     ('RNCHS','RNCH'),
1179     ('ROAD','RD'),
1180     ('ROADS','RDS'),
1181     ('ROUTE','RTE'),
1182     ('ROW','ROW'),
1183     ('RPD','RPD'),
1184     ('RPDS','RPDS'),
1185     ('RST','RST'),
1186     ('RUE','RUE'),
1187     ('RUN','RUN'),
1188     ('RVR','RIV'),
1189     ('SHL','SHL'),
1190     ('SHLS','SHLS'),
1191     ('SHOAL','SHL'),
1192     ('SHOALS','SHLS'),
1193     ('SHOAR','SHR'),
1194     ('SHOARS','SHRS'),
1195     ('SHORE','SHR'),
1196     ('SHORES','SHRS'),
1197     ('SHR','SHR'),
1198     ('SHRS','SHRS'),
1199     ('SKYWAY','SKWY'),
1200     ('SMT','SMT'),
1201     ('SPG','SPG'),
1202     ('SPGS','SPGS'),
1203     ('SPNG','SPG'),
1204     ('SPNGS','SPGS'),
1205     ('SPRING','SPG'),
1206     ('SPRINGS','SPGS'),
1207     ('SPRNG','SPG'),
1208     ('SPRNGS','SPGS'),
1209     ('SPUR','SPUR'),
1210     ('SPURS','SPUR'),
1211     ('SQRE','SQ'),
1212     ('SQR','SQ'),
1213     ('SQRS','SQS'),
1214     ('SQ','SQ'),
1215     ('SQUARE','SQ'),
1216     ('SQUARES','SQS'),
1217     ('SQU','SQ'),
1218     ('STA','STA'),
1219     ('STATION','STA'),
1220     ('STATN','STA'),
1221     ('STN','STA'),
1222     ('STRA','STRA'),
1223     ('STRAVEN','STRA'),
1224     ('STRAVENUE','STRA'),
1225     ('STRAVE','STRA'),
1226     ('STRAVN','STRA'),
1227     ('STRAV','STRA'),
1228     ('STREAM','STRM'),
1229     ('STREETS','STS'),
1230     ('STREET','ST'),
1231     ('STREME','STRM'),
1232     ('STRM','STRM'),
1233     ('STR','ST'),
1234     ('STRT','ST'),
1235     ('STRVN','STRA'),
1236     ('STRVNUE','STRA'),
1237     ('ST','ST'),
1238     ('SUMIT','SMT'),
1239     ('SUMITT','SMT'),
1240     ('SUMMIT','SMT'),
1241     ('TERRACE','TER'),
1242     ('TERR','TER'),
1243     ('TER','TER'),
1244     ('THROUGHWAY','TRWY'),
1245     ('TPKE','TPKE'),
1246     ('TPK','TPKE'),
1247     ('TRACES','TRCE'),
1248     ('TRACE','TRCE'),
1249     ('TRACKS','TRAK'),
1250     ('TRACK','TRAK'),
1251     ('TRAFFICWAY','TRFY'),
1252     ('TRAILS','TRL'),
1253     ('TRAIL','TRL'),
1254     ('TRAK','TRAK'),
1255     ('TRCE','TRCE'),
1256     ('TRFY','TRFY'),
1257     ('TRKS','TRAK'),
1258     ('TRK','TRAK'),
1259     ('TRLS','TRL'),
1260     ('TRL','TRL'),
1261     ('TRNPK','TPKE'),
1262     ('TRPK','TPKE'),
1263     ('TR','TRL'),
1264     ('TUNEL','TUNL'),
1265     ('TUNLS','TUNL'),
1266     ('TUNL','TUNL'),
1267     ('TUNNELS','TUNL'),
1268     ('TUNNEL','TUNL'),
1269     ('TUNNL','TUNL'),
1270     ('TURNPIKE','TPKE'),
1271     ('TURNPK','TPKE'),
1272     ('UNDERPASS','UPAS'),
1273     ('UNIONS','UNS'),
1274     ('UNION','UN'),
1275     ('UN','UN'),
1276     ('VALLEYS','VLYS'),
1277     ('VALLEY','VLY'),
1278     ('VALLY','VLY'),
1279     ('VDCT','IA'),
1280     ('VIADCT','VIA'),
1281     ('VIADUCT','IA'),
1282     ('VIADUCT','VIA'),
1283     ('VIA','VIA'),
1284     ('VIEWS','VWS'),
1285     ('VIEW','VW'),
1286     ('VILLAGES','VLGS'),
1287     ('VILLAGE','VLG'),
1288     ('VILLAG','VLG'),
1289     ('VILLE','VL'),
1290     ('VILLG','VLG'),
1291     ('VILLIAGE','VLG'),
1292     ('VILL','VLG'),
1293     ('VISTA','VIS'),
1294     ('VIST','VIS'),
1295     ('VIS','VIS'),
1296     ('VLGS','VLGS'),
1297     ('VLG','VLG'),
1298     ('VLLY','VLY'),
1299     ('VL','VL'),
1300     ('VLYS','VLYS'),
1301     ('VLY','VLY'),
1302     ('VSTA','VIS'),
1303     ('VST','VIS'),
1304     ('VWS','VWS'),
1305     ('VW','VW'),
1306     ('WALKS','WALK'),
1307     ('WALK','WALK'),
1308     ('WALL','WALL'),
1309     ('WAYS','WAYS'),
1310     ('WAY','WAY'),
1311     ('WELLS','WLS'),
1312     ('WELL','WL'),
1313     ('WLS','WLS'),
1314     ('WY','WAY'),
1315     ('XING','XING');
1316
1317 -- this function should get a smaller range of inputs and benefit more from STABLE, hopefully speeding things up
1318 CREATE OR REPLACE FUNCTION migration_tools._normalize_address_suffix (TEXT) RETURNS TEXT AS $$
1319     DECLARE
1320         suffix TEXT := $1;
1321                 _r RECORD;
1322     BEGIN
1323         --RAISE INFO 'suffix = %', suffix;
1324                 FOR _r IN (SELECT * FROM migration_tools.usps_suffixes) LOOP
1325                         suffix := REGEXP_REPLACE( suffix, _r.suffix_from, _r.suffix_to, 'i');
1326                 END LOOP;
1327                 RETURN suffix;
1328     END;
1329 $$ LANGUAGE PLPGSQL STRICT STABLE;
1330
1331 CREATE OR REPLACE FUNCTION migration_tools.normalize_address_suffix (TEXT) RETURNS TEXT AS $$
1332     BEGIN
1333                 RETURN CASE
1334             WHEN $1 ~ '\s\S+$' THEN REGEXP_REPLACE( $1, '^(.*\s)(\S+)$', '\1' ) || migration_tools._normalize_address_suffix( REGEXP_REPLACE( $1, '^(.*\s)(\S+)$', '\2' ) )
1335             ELSE $1
1336         END;
1337     END;
1338 $$ LANGUAGE PLPGSQL STRICT STABLE;
1339
1340 CREATE OR REPLACE FUNCTION migration_tools.rebarcode (o TEXT, t BIGINT) RETURNS TEXT AS $$
1341     DECLARE
1342         n TEXT := o;
1343     BEGIN
1344         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
1345             IF o::BIGINT < t THEN
1346                 n = o::BIGINT + t;
1347             END IF;
1348         END IF;
1349
1350         RETURN n;
1351     END;
1352 $$ LANGUAGE PLPGSQL STRICT IMMUTABLE;
1353
1354 CREATE OR REPLACE FUNCTION migration_tools.base_profile_map (TEXT) RETURNS TEXT AS $$
1355     DECLARE
1356         migration_schema ALIAS FOR $1;
1357         output TEXT;
1358     BEGIN
1359         FOR output IN
1360             EXECUTE 'SELECT ''' || migration_schema || '.'' || value FROM ' || migration_schema || '.config WHERE key = ''base_profile_map'';'
1361         LOOP
1362             RETURN output;
1363         END LOOP;
1364     END;
1365 $$ LANGUAGE PLPGSQL STRICT STABLE;
1366
1367 CREATE OR REPLACE FUNCTION migration_tools.base_item_dynamic_field_map (TEXT) RETURNS TEXT AS $$
1368     DECLARE
1369         migration_schema ALIAS FOR $1;
1370         output TEXT;
1371     BEGIN
1372         FOR output IN
1373             EXECUTE 'SELECT ''' || migration_schema || '.'' || value FROM ' || migration_schema || '.config WHERE key = ''base_item_dynamic_field_map'';'
1374         LOOP
1375             RETURN output;
1376         END LOOP;
1377     END;
1378 $$ LANGUAGE PLPGSQL STRICT STABLE;
1379
1380 CREATE OR REPLACE FUNCTION migration_tools.base_copy_location_map (TEXT) RETURNS TEXT AS $$
1381     DECLARE
1382         migration_schema ALIAS FOR $1;
1383         output TEXT;
1384     BEGIN
1385         FOR output IN
1386             EXECUTE 'SELECT ''' || migration_schema || '.'' || value FROM ' || migration_schema || '.config WHERE key = ''base_copy_location_map'';'
1387         LOOP
1388             RETURN output;
1389         END LOOP;
1390     END;
1391 $$ LANGUAGE PLPGSQL STRICT STABLE;
1392
1393 CREATE OR REPLACE FUNCTION migration_tools.base_circ_field_map (TEXT) RETURNS TEXT AS $$
1394     DECLARE
1395         migration_schema ALIAS FOR $1;
1396         output TEXT;
1397     BEGIN
1398         FOR output IN
1399             EXECUTE 'SELECT ''' || migration_schema || '.'' || value FROM ' || migration_schema || '.config WHERE key = ''base_circ_field_map'';'
1400         LOOP
1401             RETURN output;
1402         END LOOP;
1403     END;
1404 $$ LANGUAGE PLPGSQL STRICT STABLE;
1405
1406 CREATE OR REPLACE FUNCTION migration_tools.map_base_patron_profile (TEXT,TEXT,INTEGER) RETURNS VOID AS $$
1407     DECLARE
1408         migration_schema ALIAS FOR $1;
1409         profile_map TEXT;
1410         patron_table ALIAS FOR $2;
1411         default_patron_profile ALIAS FOR $3;
1412         sql TEXT;
1413         sql_update TEXT;
1414         sql_where1 TEXT := '';
1415         sql_where2 TEXT := '';
1416         sql_where3 TEXT := '';
1417         output RECORD;
1418     BEGIN
1419         SELECT migration_tools.base_profile_map(migration_schema) INTO STRICT profile_map;
1420         FOR output IN 
1421             EXECUTE 'SELECT * FROM ' || profile_map || E' ORDER BY id;'
1422         LOOP
1423             sql_update := 'UPDATE ' || patron_table || ' AS u SET profile = perm_grp_id FROM ' || profile_map || ' AS m WHERE ';
1424             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);
1425             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);
1426             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);
1427             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,'') || ';';
1428             --RAISE INFO 'sql = %', sql;
1429             PERFORM migration_tools.exec( $1, sql );
1430         END LOOP;
1431         PERFORM migration_tools.exec( $1, 'UPDATE ' || patron_table || ' AS u SET profile = ' || quote_literal(default_patron_profile) || ' WHERE profile IS NULL;'  );
1432         BEGIN
1433             PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''last_base_patron_mapping_profile'', now() );' );
1434         EXCEPTION
1435             WHEN OTHERS THEN PERFORM migration_tools.exec( $1, 'UPDATE ' || migration_schema || '.config SET value = now() WHERE key = ''last_base_patron_mapping_profile'';' );
1436         END;
1437     END;
1438 $$ LANGUAGE PLPGSQL STRICT STABLE;
1439
1440 CREATE OR REPLACE FUNCTION migration_tools.map_base_item_table_dynamic (TEXT,TEXT) RETURNS VOID AS $$
1441     DECLARE
1442         migration_schema ALIAS FOR $1;
1443         field_map TEXT;
1444         item_table ALIAS FOR $2;
1445         sql TEXT;
1446         sql_update TEXT;
1447         sql_where1 TEXT := '';
1448         sql_where2 TEXT := '';
1449         sql_where3 TEXT := '';
1450         output RECORD;
1451     BEGIN
1452         SELECT migration_tools.base_item_dynamic_field_map(migration_schema) INTO STRICT field_map;
1453         FOR output IN 
1454             EXECUTE 'SELECT * FROM ' || field_map || E' ORDER BY id;'
1455         LOOP
1456             sql_update := 'UPDATE ' || item_table || ' AS i SET ' || output.evergreen_field || E' = ' || quote_literal(output.evergreen_value) || '::' || output.evergreen_datatype || E' FROM ' || field_map || ' AS m WHERE ';
1457             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);
1458             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);
1459             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);
1460             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,'') || ';';
1461             --RAISE INFO 'sql = %', sql;
1462             PERFORM migration_tools.exec( $1, sql );
1463         END LOOP;
1464         BEGIN
1465             PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''last_base_item_mapping_dynamic'', now() );' );
1466         EXCEPTION
1467             WHEN OTHERS THEN PERFORM migration_tools.exec( $1, 'UPDATE ' || migration_schema || '.config SET value = now() WHERE key = ''last_base_item_mapping_dynamic'';' );
1468         END;
1469     END;
1470 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
1471
1472 CREATE OR REPLACE FUNCTION migration_tools.map_base_item_table_locations (TEXT,TEXT) RETURNS VOID AS $$
1473     DECLARE
1474         migration_schema ALIAS FOR $1;
1475         base_copy_location_map TEXT;
1476         item_table ALIAS FOR $2;
1477         sql TEXT;
1478         sql_update TEXT;
1479         sql_where1 TEXT := '';
1480         sql_where2 TEXT := '';
1481         sql_where3 TEXT := '';
1482         output RECORD;
1483     BEGIN
1484         SELECT migration_tools.base_copy_location_map(migration_schema) INTO STRICT base_copy_location_map;
1485         FOR output IN 
1486             EXECUTE 'SELECT * FROM ' || base_copy_location_map || E' ORDER BY id;'
1487         LOOP
1488             sql_update := 'UPDATE ' || item_table || ' AS i SET location = m.location FROM ' || base_copy_location_map || ' AS m WHERE ';
1489             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);
1490             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);
1491             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);
1492             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,'') || ';';
1493             --RAISE INFO 'sql = %', sql;
1494             PERFORM migration_tools.exec( $1, sql );
1495         END LOOP;
1496         BEGIN
1497             PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''last_base_item_mapping_locations'', now() );' );
1498         EXCEPTION
1499             WHEN OTHERS THEN PERFORM migration_tools.exec( $1, 'UPDATE ' || migration_schema || '.config SET value = now() WHERE key = ''last_base_item_mapping_locations'';' );
1500         END;
1501     END;
1502 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
1503
1504 -- circulate       loan period     max renewals    max out fine amount     fine interval   max fine        item field 1    item value 1    item field 2    item value 2    patron field 1  patron value 1  patron field 2  patron value 2
1505 CREATE OR REPLACE FUNCTION migration_tools.map_base_circ_table_dynamic (TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
1506     DECLARE
1507         migration_schema ALIAS FOR $1;
1508         field_map TEXT;
1509         circ_table ALIAS FOR $2;
1510         item_table ALIAS FOR $3;
1511         patron_table ALIAS FOR $4;
1512         sql TEXT;
1513         sql_update TEXT;
1514         sql_where1 TEXT := '';
1515         sql_where2 TEXT := '';
1516         sql_where3 TEXT := '';
1517         sql_where4 TEXT := '';
1518         output RECORD;
1519     BEGIN
1520         SELECT migration_tools.base_circ_field_map(migration_schema) INTO STRICT field_map;
1521         FOR output IN 
1522             EXECUTE 'SELECT * FROM ' || field_map || E' ORDER BY id;'
1523         LOOP
1524             sql_update := 'UPDATE ' || circ_table || ' AS c SET duration = ' || quote_literal(output.loan_period) || '::INTERVAL, renewal_remaining = ' || quote_literal(output.max_renewals) || '::INTEGER, recuring_fine = ' || quote_literal(output.fine_amount) || '::NUMERIC(6,2), fine_interval = ' || quote_literal(output.fine_interval) || '::INTERVAL, max_fine = ' || quote_literal(output.max_fine) || '::NUMERIC(6,2) FROM ' || field_map || ' AS m, ' || item_table || ' AS i, ' || patron_table || ' AS u WHERE c.usr = u.id AND c.target_copy = i.id AND ';
1525             sql_where1 := NULLIF(output.item_field1,'') || ' = ' || quote_literal( output.item_value1 ) || ' AND item_field1 = ' || quote_literal(output.item_field1) || ' AND item_value1 = ' || quote_literal(output.item_value1);
1526             sql_where2 := NULLIF(output.item_field2,'') || ' = ' || quote_literal( output.item_value2 ) || ' AND item_field2 = ' || quote_literal(output.item_field2) || ' AND item_value2 = ' || quote_literal(output.item_value2);
1527             sql_where3 := NULLIF(output.patron_field1,'') || ' = ' || quote_literal( output.patron_value1 ) || ' AND patron_field1 = ' || quote_literal(output.patron_field1) || ' AND patron_value1 = ' || quote_literal(output.patron_value1);
1528             sql_where4 := NULLIF(output.patron_field2,'') || ' = ' || quote_literal( output.patron_value2 ) || ' AND patron_field2 = ' || quote_literal(output.patron_field2) || ' AND patron_value2 = ' || quote_literal(output.patron_value2);
1529             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,'') || CASE WHEN sql_where3 <> '' AND sql_where4 <> '' THEN ' AND ' ELSE '' END || COALESCE(sql_where4,'') || ';';
1530             --RAISE INFO 'sql = %', sql;
1531             PERFORM migration_tools.exec( $1, sql );
1532         END LOOP;
1533         BEGIN
1534             PERFORM migration_tools.exec( $1, 'INSERT INTO ' || migration_schema || '.config (key,value) VALUES ( ''last_base_circ_field_mapping'', now() );' );
1535         EXCEPTION
1536             WHEN OTHERS THEN PERFORM migration_tools.exec( $1, 'UPDATE ' || migration_schema || '.config SET value = now() WHERE key = ''last_base_circ_field_mapping'';' );
1537         END;
1538     END;
1539 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
1540
1541 -- expand_barcode
1542 --   $barcode      source barcode
1543 --   $prefix       prefix to add to barcode, NULL = add no prefix
1544 --   $maxlen       maximum length of barcode; default to 14 if left NULL
1545 --   $pad          padding string to apply to left of source barcode before adding
1546 --                 prefix and suffix; set to NULL or '' if no padding is desired
1547 --   $suffix       suffix to add to barcode, NULL = add no suffix
1548 --
1549 -- Returns a new string consisting of prefix concatenated with padded barcode and suffix.
1550 -- If new barcode would be longer than $maxlen, the original barcode is returned instead.
1551 --
1552 CREATE OR REPLACE FUNCTION migration_tools.expand_barcode (TEXT, TEXT, INTEGER, TEXT, TEXT) RETURNS TEXT AS $$
1553     my ($barcode, $prefix, $maxlen, $pad, $suffix) = @_;
1554
1555     # default case
1556     return unless defined $barcode;
1557
1558     $prefix     = '' unless defined $prefix;
1559     $maxlen ||= 14;
1560     $pad        = '0' unless defined $pad;
1561     $suffix     = '' unless defined $suffix;
1562
1563     # bail out if adding prefix and suffix would bring new barcode over max length
1564     return $barcode if (length($prefix) + length($barcode) + length($suffix)) > $maxlen;
1565
1566     my $new_barcode = $barcode;
1567     if ($pad ne '') {
1568         my $pad_length = $maxlen - length($prefix) - length($suffix);
1569         if (length($barcode) < $pad_length) {
1570             # assuming we always want padding on the left
1571             # also assuming that it is possible to have the pad string be longer than 1 character
1572             $new_barcode = substr($pad x ($pad_length - length($barcode)), 0, $pad_length - length($barcode)) . $new_barcode;
1573         }
1574     }
1575
1576     # bail out if adding prefix and suffix would bring new barcode over max length
1577     return $barcode if (length($prefix) + length($new_barcode) + length($suffix)) > $maxlen;
1578
1579     return "$prefix$new_barcode$suffix";
1580 $$ LANGUAGE PLPERLU STABLE;
1581
1582 -- remove previous version of this function
1583 DROP FUNCTION IF EXISTS migration_tools.attempt_cast(TEXT, TEXT, TEXT);
1584
1585 CREATE OR REPLACE FUNCTION migration_tools.attempt_cast (TEXT, TEXT) RETURNS TEXT AS $$
1586     DECLARE
1587         attempt_value ALIAS FOR $1;
1588         datatype ALIAS FOR $2;
1589     BEGIN
1590         EXECUTE 'SELECT ' || quote_literal(attempt_value) || '::' || datatype || ' AS a;';
1591         RETURN attempt_value;
1592     EXCEPTION
1593         WHEN OTHERS THEN RETURN NULL;
1594     END;
1595 $$ LANGUAGE PLPGSQL STRICT STABLE;
1596
1597 CREATE OR REPLACE FUNCTION migration_tools.attempt_date (TEXT,TEXT) RETURNS DATE AS $$
1598     DECLARE
1599         attempt_value ALIAS FOR $1;
1600         fail_value ALIAS FOR $2;
1601         output DATE;
1602     BEGIN
1603         FOR output IN
1604             EXECUTE 'SELECT ' || quote_literal(REGEXP_REPLACE(attempt_value,'^(\d\d)(\d\d)(\d\d)$','\1-\2-\3')) || '::date AS a;'
1605         LOOP
1606             RETURN output;
1607         END LOOP;
1608     EXCEPTION
1609         WHEN OTHERS THEN
1610             FOR output IN
1611                 EXECUTE 'SELECT ' || quote_literal(fail_value) || '::date AS a;'
1612             LOOP
1613                 RETURN output;
1614             END LOOP;
1615     END;
1616 $$ LANGUAGE PLPGSQL STRICT STABLE;
1617
1618 CREATE OR REPLACE FUNCTION migration_tools.attempt_timestamptz (TEXT,TEXT) RETURNS TIMESTAMPTZ AS $$
1619     DECLARE
1620         attempt_value ALIAS FOR $1;
1621         fail_value ALIAS FOR $2;
1622         output TIMESTAMPTZ;
1623     BEGIN
1624         FOR output IN
1625             EXECUTE 'SELECT ' || quote_literal(attempt_value) || '::TIMESTAMPTZ AS a;'
1626         LOOP
1627             RETURN output;
1628         END LOOP;
1629     EXCEPTION
1630         WHEN OTHERS THEN
1631             FOR output IN
1632                 EXECUTE 'SELECT ' || quote_literal(fail_value) || '::TIMESTAMPTZ AS a;'
1633             LOOP
1634                 RETURN output;
1635             END LOOP;
1636     END;
1637 $$ LANGUAGE PLPGSQL STRICT STABLE;
1638
1639 CREATE OR REPLACE FUNCTION migration_tools.attempt_hz_date (TEXT,TEXT) RETURNS DATE AS $$
1640     DECLARE
1641         attempt_value ALIAS FOR $1;
1642         fail_value ALIAS FOR $2;
1643         output DATE;
1644     BEGIN
1645         FOR output IN
1646             EXECUTE E'SELECT (\'1970-01-01\'::date + \'' || attempt_value || E' days\'::interval)::date AS a;'
1647         LOOP
1648             RETURN output;
1649         END LOOP;
1650     EXCEPTION
1651         WHEN OTHERS THEN
1652             FOR output IN
1653                 EXECUTE 'SELECT ' || quote_literal(fail_value) || '::date AS a;'
1654             LOOP
1655                 RETURN output;
1656             END LOOP;
1657     END;
1658 $$ LANGUAGE PLPGSQL STRICT STABLE;
1659
1660 CREATE OR REPLACE FUNCTION migration_tools.attempt_sierra_timestamp (TEXT,TEXT) RETURNS TIMESTAMP AS $$
1661     DECLARE
1662         attempt_value ALIAS FOR $1;
1663         fail_value ALIAS FOR $2;
1664         output TIMESTAMP;
1665     BEGIN
1666             output := REGEXP_REPLACE(attempt_value,E'^(..)(..)(..)(..)(..)$',E'20\\1-\\2-\\3 \\4:\\5')::TIMESTAMP;
1667             RETURN output;
1668     EXCEPTION
1669         WHEN OTHERS THEN
1670             FOR output IN
1671                 EXECUTE 'SELECT ' || quote_literal(fail_value) || '::TIMESTAMP AS a;'
1672             LOOP
1673                 RETURN output;
1674             END LOOP;
1675     END;
1676 $$ LANGUAGE PLPGSQL STRICT STABLE;
1677
1678 CREATE OR REPLACE FUNCTION migration_tools.attempt_money (TEXT,TEXT) RETURNS NUMERIC(8,2) AS $$
1679     DECLARE
1680         attempt_value ALIAS FOR $1;
1681         fail_value ALIAS FOR $2;
1682         output NUMERIC(8,2);
1683     BEGIN
1684         FOR output IN
1685             EXECUTE 'SELECT ' || quote_literal(REPLACE(REPLACE(attempt_value,'$',''),',','')) || '::NUMERIC(8,2) AS a;'
1686         LOOP
1687             RETURN output;
1688         END LOOP;
1689     EXCEPTION
1690         WHEN OTHERS THEN
1691             FOR output IN
1692                 EXECUTE 'SELECT ' || quote_literal(fail_value) || '::NUMERIC(8,2) AS a;'
1693             LOOP
1694                 RETURN output;
1695             END LOOP;
1696     END;
1697 $$ LANGUAGE PLPGSQL STRICT STABLE;
1698
1699 CREATE OR REPLACE FUNCTION migration_tools.attempt_money6 (TEXT,TEXT) RETURNS NUMERIC(6,2) AS $$
1700     DECLARE
1701         attempt_value ALIAS FOR $1;
1702         fail_value ALIAS FOR $2;
1703         output NUMERIC(6,2);
1704     BEGIN
1705         FOR output IN
1706             EXECUTE 'SELECT ' || quote_literal(REPLACE(REPLACE(attempt_value,'$',''),',','')) || '::NUMERIC(6,2) AS a;'
1707         LOOP
1708             RETURN output;
1709         END LOOP;
1710     EXCEPTION
1711         WHEN OTHERS THEN
1712             FOR output IN
1713                 EXECUTE 'SELECT ' || quote_literal(fail_value) || '::NUMERIC(6,2) AS a;'
1714             LOOP
1715                 RETURN output;
1716             END LOOP;
1717     END;
1718 $$ LANGUAGE PLPGSQL STRICT STABLE;
1719
1720 CREATE OR REPLACE FUNCTION migration_tools.attempt_money_from_pennies (TEXT,TEXT) RETURNS NUMERIC(8,2) AS $$
1721     DECLARE
1722         attempt_value ALIAS FOR $1;
1723         fail_value ALIAS FOR $2;
1724         output NUMERIC(8,2);
1725     BEGIN
1726         IF length(regexp_replace(attempt_value,'^0+','')) > 10 THEN
1727             RAISE EXCEPTION 'too many digits';
1728         END IF;
1729         FOR output IN
1730             EXECUTE 'SELECT ' || quote_literal((left(lpad(regexp_replace(attempt_value,'^0+',''),10,'0'),-2) || '.' || right(lpad(regexp_replace(attempt_value,'^0+',''),10,'0'),2))::numeric(8,2)) || '::NUMERIC(8,2) AS a;'
1731         LOOP
1732             RETURN output;
1733         END LOOP;
1734     EXCEPTION
1735         WHEN OTHERS THEN
1736             FOR output IN
1737                 EXECUTE 'SELECT ' || quote_literal(fail_value) || '::NUMERIC(8,2) AS a;'
1738             LOOP
1739                 RETURN output;
1740             END LOOP;
1741     END;
1742 $$ LANGUAGE PLPGSQL STRICT STABLE;
1743
1744 CREATE OR REPLACE FUNCTION migration_tools.attempt_money_from_pennies6 (TEXT,TEXT) RETURNS NUMERIC(6,2) AS $$
1745     DECLARE
1746         attempt_value ALIAS FOR $1;
1747         fail_value ALIAS FOR $2;
1748         output NUMERIC(6,2);
1749     BEGIN
1750         IF length(regexp_replace(attempt_value,'^0+','')) > 8 THEN
1751             RAISE EXCEPTION 'too many digits';
1752         END IF;
1753         FOR output IN
1754             EXECUTE 'SELECT ' || quote_literal((left(lpad(regexp_replace(attempt_value,'^0+',''),8,'0'),-2) || '.' || right(lpad(regexp_replace(attempt_value,'^0+',''),8,'0'),2))::numeric(6,2)) || '::NUMERIC(6,2) AS a;'
1755         LOOP
1756             RETURN output;
1757         END LOOP;
1758     EXCEPTION
1759         WHEN OTHERS THEN
1760             FOR output IN
1761                 EXECUTE 'SELECT ' || quote_literal(fail_value) || '::NUMERIC(6,2) AS a;'
1762             LOOP
1763                 RETURN output;
1764             END LOOP;
1765     END;
1766 $$ LANGUAGE PLPGSQL STRICT STABLE;
1767
1768 -- add_codabar_checkdigit
1769 --   $barcode      source barcode
1770 --
1771 -- If the source string is 13 or 14 characters long and contains only digits, adds or replaces the 14
1772 -- character with a checkdigit computed according to the usual algorithm for library barcodes
1773 -- using the Codabar symbology - see <http://www.makebarcode.com/specs/codabar.html>.  If the
1774 -- input string does not meet those requirements, it is returned unchanged.
1775 --
1776 CREATE OR REPLACE FUNCTION migration_tools.add_codabar_checkdigit (TEXT) RETURNS TEXT AS $$
1777     my $barcode = shift;
1778
1779     return $barcode if $barcode !~ /^\d{13,14}$/;
1780     $barcode = substr($barcode, 0, 13); # ignore 14th digit
1781     my @digits = split //, $barcode;
1782     my $total = 0;
1783     $total += $digits[$_] foreach (1, 3, 5, 7, 9, 11);
1784     $total += (2 * $digits[$_] >= 10) ? (2 * $digits[$_] - 9) : (2 * $digits[$_]) foreach (0, 2, 4, 6, 8, 10, 12);
1785     my $remainder = $total % 10;
1786     my $checkdigit = ($remainder == 0) ? $remainder : 10 - $remainder;
1787     return $barcode . $checkdigit; 
1788 $$ LANGUAGE PLPERLU STRICT STABLE;
1789
1790 -- add_code39mod43_checkdigit
1791 --   $barcode      source barcode
1792 --
1793 -- If the source string is 13 or 14 characters long and contains only valid
1794 -- Code 39 mod 43 characters, adds or replaces the 14th
1795 -- character with a checkdigit computed according to the usual algorithm for library barcodes
1796 -- using the Code 39 mod 43 symbology - see <http://en.wikipedia.org/wiki/Code_39#Code_39_mod_43>.  If the
1797 -- input string does not meet those requirements, it is returned unchanged.
1798 --
1799 CREATE OR REPLACE FUNCTION migration_tools.add_code39mod43_checkdigit (TEXT) RETURNS TEXT AS $$
1800     my $barcode = shift;
1801
1802     return $barcode if $barcode !~ /^[0-9A-Z. $\/+%-]{13,14}$/;
1803     $barcode = substr($barcode, 0, 13); # ignore 14th character
1804
1805     my @valid_chars = split //, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%';
1806     my %nums = map { $valid_chars[$_] => $_ } (0..42);
1807
1808     my $total = 0;
1809     $total += $nums{$_} foreach split(//, $barcode);
1810     my $remainder = $total % 43;
1811     my $checkdigit = $valid_chars[$remainder];
1812     return $barcode . $checkdigit;
1813 $$ LANGUAGE PLPERLU STRICT STABLE;
1814
1815 -- add_mod16_checkdigit
1816 --   $barcode      source barcode
1817 --
1818 -- https://www.activebarcode.com/codes/checkdigit/modulo16.html
1819
1820 CREATE OR REPLACE FUNCTION migration_tools.add_mod16_checkdigit (TEXT) RETURNS TEXT AS $$
1821     my $barcode = shift;
1822
1823     my @digits = split //, $barcode;
1824     my $total = 0;
1825     foreach $digit (@digits) {
1826         if ($digit =~ /[0-9]/) { $total += $digit;
1827         } elsif ($digit eq '-') { $total += 10;
1828         } elsif ($digit eq '$') { $total += 11;
1829         } elsif ($digit eq ':') { $total += 12;
1830         } elsif ($digit eq '/') { $total += 13;
1831         } elsif ($digit eq '.') { $total += 14;
1832         } elsif ($digit eq '+') { $total += 15;
1833         } elsif ($digit eq 'A') { $total += 16;
1834         } elsif ($digit eq 'B') { $total += 17;
1835         } elsif ($digit eq 'C') { $total += 18;
1836         } elsif ($digit eq 'D') { $total += 19;
1837         } else { die "invalid digit <$digit>";
1838         }
1839     }
1840     my $remainder = $total % 16;
1841     my $difference = 16 - $remainder;
1842     my $checkdigit;
1843     if ($difference < 10) { $checkdigit = $difference;
1844     } elsif ($difference == 10) { $checkdigit = '-';
1845     } elsif ($difference == 11) { $checkdigit = '$';
1846     } elsif ($difference == 12) { $checkdigit = ':';
1847     } elsif ($difference == 13) { $checkdigit = '/';
1848     } elsif ($difference == 14) { $checkdigit = '.';
1849     } elsif ($difference == 15) { $checkdigit = '+';
1850     } else { die "error calculating checkdigit";
1851     }
1852
1853     return $barcode . $checkdigit;
1854 $$ LANGUAGE PLPERLU STRICT STABLE;
1855
1856 CREATE OR REPLACE FUNCTION migration_tools.attempt_phone (TEXT,TEXT) RETURNS TEXT AS $$
1857   DECLARE
1858     phone TEXT := $1;
1859     areacode TEXT := $2;
1860     temp TEXT := '';
1861     output TEXT := '';
1862     n_digits INTEGER := 0;
1863   BEGIN
1864     temp := phone;
1865     temp := REGEXP_REPLACE(temp, '^1*[^0-9]*(?=[0-9])', '');
1866     temp := REGEXP_REPLACE(temp, '[^0-9]*([0-9]{3})[^0-9]*([0-9]{3})[^0-9]*([0-9]{4})', E'\\1-\\2-\\3');
1867     n_digits := LENGTH(REGEXP_REPLACE(REGEXP_REPLACE(temp, '(.*)?[a-zA-Z].*', E'\\1') , '[^0-9]', '', 'g'));
1868     IF n_digits = 7 AND areacode <> '' THEN
1869       temp := REGEXP_REPLACE(temp, '[^0-9]*([0-9]{3})[^0-9]*([0-9]{4})', E'\\1-\\2');
1870       output := (areacode || '-' || temp);
1871     ELSE
1872       output := temp;
1873     END IF;
1874     RETURN output;
1875   END;
1876
1877 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
1878
1879 CREATE OR REPLACE FUNCTION migration_tools.set_leader (TEXT, INT, TEXT) RETURNS TEXT AS $$
1880   my ($marcxml, $pos, $value) = @_;
1881
1882   use MARC::Record;
1883   use MARC::File::XML;
1884
1885   my $xml = $marcxml;
1886   eval {
1887     my $marc = MARC::Record->new_from_xml($marcxml, 'UTF-8');
1888     my $leader = $marc->leader();
1889     substr($leader, $pos, 1) = $value;
1890     $marc->leader($leader);
1891     $xml = $marc->as_xml_record;
1892     $xml =~ s/^<\?.+?\?>$//mo;
1893     $xml =~ s/\n//sgo;
1894     $xml =~ s/>\s+</></sgo;
1895   };
1896   return $xml;
1897 $$ LANGUAGE PLPERLU STABLE;
1898
1899 CREATE OR REPLACE FUNCTION migration_tools.set_008 (TEXT, INT, TEXT) RETURNS TEXT AS $$
1900   my ($marcxml, $pos, $value) = @_;
1901
1902   use MARC::Record;
1903   use MARC::File::XML;
1904
1905   my $xml = $marcxml;
1906   eval {
1907     my $marc = MARC::Record->new_from_xml($marcxml, 'UTF-8');
1908     my $f008 = $marc->field('008');
1909
1910     if ($f008) {
1911        my $field = $f008->data();
1912        substr($field, $pos, 1) = $value;
1913        $f008->update($field);
1914        $xml = $marc->as_xml_record;
1915        $xml =~ s/^<\?.+?\?>$//mo;
1916        $xml =~ s/\n//sgo;
1917        $xml =~ s/>\s+</></sgo;
1918     }
1919   };
1920   return $xml;
1921 $$ LANGUAGE PLPERLU STABLE;
1922
1923
1924 CREATE OR REPLACE FUNCTION migration_tools.is_staff_profile (INT) RETURNS BOOLEAN AS $$
1925   DECLARE
1926     profile ALIAS FOR $1;
1927   BEGIN
1928     RETURN CASE WHEN 'Staff' IN (select (permission.grp_ancestors(profile)).name) THEN TRUE ELSE FALSE END;
1929   END;
1930 $$ LANGUAGE PLPGSQL STRICT STABLE;
1931
1932
1933 CREATE OR REPLACE FUNCTION migration_tools.is_blank (TEXT) RETURNS BOOLEAN AS $$
1934   BEGIN
1935     RETURN CASE WHEN $1 = '' THEN TRUE ELSE FALSE END;
1936   END;
1937 $$ LANGUAGE PLPGSQL STRICT STABLE;
1938
1939
1940 CREATE OR REPLACE FUNCTION migration_tools.insert_tags (TEXT, TEXT) RETURNS TEXT AS $$
1941
1942   my ($marcxml, $tags) = @_;
1943
1944   use MARC::Record;
1945   use MARC::File::XML;
1946
1947   my $xml = $marcxml;
1948
1949   eval {
1950     my $marc = MARC::Record->new_from_xml($marcxml, 'UTF-8');
1951     my $to_insert = MARC::Record->new_from_xml("<record>$tags</record>", 'UTF-8');
1952
1953     my @incumbents = ();
1954
1955     foreach my $field ( $marc->fields() ) {
1956       push @incumbents, $field->as_formatted();
1957     }
1958
1959     foreach $field ( $to_insert->fields() ) {
1960       if (!grep {$_ eq $field->as_formatted()} @incumbents) {
1961         $marc->insert_fields_ordered( ($field) );
1962       }
1963     }
1964
1965     $xml = $marc->as_xml_record;
1966     $xml =~ s/^<\?.+?\?>$//mo;
1967     $xml =~ s/\n//sgo;
1968     $xml =~ s/>\s+</></sgo;
1969   };
1970
1971   return $xml;
1972
1973 $$ LANGUAGE PLPERLU STABLE;
1974
1975 CREATE OR REPLACE FUNCTION migration_tools.apply_circ_matrix( tablename TEXT ) RETURNS VOID AS $$
1976
1977 -- Usage:
1978 --
1979 --   First make sure the circ matrix is loaded and the circulations
1980 --   have been staged to the extent possible (but at the very least
1981 --   circ_lib, target_copy, usr, and *_renewal).  User profiles and
1982 --   circ modifiers must also be in place.
1983 --
1984 --   SELECT migration_tools.apply_circ_matrix('m_pioneer.action_circulation');
1985 --
1986
1987 DECLARE
1988   circ_lib             INT;
1989   target_copy          INT;
1990   usr                  INT;
1991   is_renewal           BOOLEAN;
1992   this_duration_rule   INT;
1993   this_fine_rule       INT;
1994   this_max_fine_rule   INT;
1995   rcd                  config.rule_circ_duration%ROWTYPE;
1996   rrf                  config.rule_recurring_fine%ROWTYPE;
1997   rmf                  config.rule_max_fine%ROWTYPE;
1998   circ                 INT;
1999   n                    INT := 0;
2000   n_circs              INT;
2001   
2002 BEGIN
2003
2004   EXECUTE 'SELECT COUNT(*) FROM ' || tablename || ';' INTO n_circs;
2005
2006   FOR circ IN EXECUTE ('SELECT id FROM ' || tablename) LOOP
2007
2008     -- Fetch the correct rules for this circulation
2009     EXECUTE ('
2010       SELECT
2011         circ_lib,
2012         target_copy,
2013         usr,
2014         CASE
2015           WHEN phone_renewal OR desk_renewal OR opac_renewal THEN TRUE
2016           ELSE FALSE
2017         END
2018       FROM ' || tablename || ' WHERE id = ' || circ || ';')
2019       INTO circ_lib, target_copy, usr, is_renewal ;
2020     SELECT
2021       INTO this_duration_rule,
2022            this_fine_rule,
2023            this_max_fine_rule
2024       duration_rule,
2025       recurring_fine_rule,
2026       max_fine_rule
2027       FROM action.item_user_circ_test(
2028         circ_lib,
2029         target_copy,
2030         usr,
2031         is_renewal
2032         );
2033     SELECT INTO rcd * FROM config.rule_circ_duration
2034       WHERE id = this_duration_rule;
2035     SELECT INTO rrf * FROM config.rule_recurring_fine
2036       WHERE id = this_fine_rule;
2037     SELECT INTO rmf * FROM config.rule_max_fine
2038       WHERE id = this_max_fine_rule;
2039
2040     -- Apply the rules to this circulation
2041     EXECUTE ('UPDATE ' || tablename || ' c
2042     SET
2043       duration_rule = rcd.name,
2044       recurring_fine_rule = rrf.name,
2045       max_fine_rule = rmf.name,
2046       duration = rcd.normal,
2047       recurring_fine = rrf.normal,
2048       max_fine =
2049         CASE rmf.is_percent
2050           WHEN TRUE THEN (rmf.amount / 100.0) * ac.price
2051           ELSE rmf.amount
2052         END,
2053       renewal_remaining = rcd.max_renewals
2054     FROM
2055       config.rule_circ_duration rcd,
2056       config.rule_recurring_fine rrf,
2057       config.rule_max_fine rmf,
2058                         asset.copy ac
2059     WHERE
2060       rcd.id = ' || this_duration_rule || ' AND
2061       rrf.id = ' || this_fine_rule || ' AND
2062       rmf.id = ' || this_max_fine_rule || ' AND
2063                         ac.id = c.target_copy AND
2064       c.id = ' || circ || ';');
2065
2066     -- Keep track of where we are in the process
2067     n := n + 1;
2068     IF (n % 100 = 0) THEN
2069       RAISE INFO '%', n || ' of ' || n_circs
2070         || ' (' || (100*n/n_circs) || '%) circs updated.';
2071     END IF;
2072
2073   END LOOP;
2074
2075   RETURN;
2076 END;
2077
2078 $$ LANGUAGE plpgsql;
2079
2080 CREATE OR REPLACE FUNCTION migration_tools.apply_circ_matrix_before_20( tablename TEXT ) RETURNS VOID AS $$
2081
2082 -- Usage:
2083 --
2084 --   First make sure the circ matrix is loaded and the circulations
2085 --   have been staged to the extent possible (but at the very least
2086 --   circ_lib, target_copy, usr, and *_renewal).  User profiles and
2087 --   circ modifiers must also be in place.
2088 --
2089 --   SELECT migration_tools.apply_circ_matrix('m_pioneer.action_circulation');
2090 --
2091
2092 DECLARE
2093   circ_lib             INT;
2094   target_copy          INT;
2095   usr                  INT;
2096   is_renewal           BOOLEAN;
2097   this_duration_rule   INT;
2098   this_fine_rule       INT;
2099   this_max_fine_rule   INT;
2100   rcd                  config.rule_circ_duration%ROWTYPE;
2101   rrf                  config.rule_recurring_fine%ROWTYPE;
2102   rmf                  config.rule_max_fine%ROWTYPE;
2103   circ                 INT;
2104   n                    INT := 0;
2105   n_circs              INT;
2106   
2107 BEGIN
2108
2109   EXECUTE 'SELECT COUNT(*) FROM ' || tablename || ';' INTO n_circs;
2110
2111   FOR circ IN EXECUTE ('SELECT id FROM ' || tablename) LOOP
2112
2113     -- Fetch the correct rules for this circulation
2114     EXECUTE ('
2115       SELECT
2116         circ_lib,
2117         target_copy,
2118         usr,
2119         CASE
2120           WHEN phone_renewal OR desk_renewal OR opac_renewal THEN TRUE
2121           ELSE FALSE
2122         END
2123       FROM ' || tablename || ' WHERE id = ' || circ || ';')
2124       INTO circ_lib, target_copy, usr, is_renewal ;
2125     SELECT
2126       INTO this_duration_rule,
2127            this_fine_rule,
2128            this_max_fine_rule
2129       duration_rule,
2130       recuring_fine_rule,
2131       max_fine_rule
2132       FROM action.find_circ_matrix_matchpoint(
2133         circ_lib,
2134         target_copy,
2135         usr,
2136         is_renewal
2137         );
2138     SELECT INTO rcd * FROM config.rule_circ_duration
2139       WHERE id = this_duration_rule;
2140     SELECT INTO rrf * FROM config.rule_recurring_fine
2141       WHERE id = this_fine_rule;
2142     SELECT INTO rmf * FROM config.rule_max_fine
2143       WHERE id = this_max_fine_rule;
2144
2145     -- Apply the rules to this circulation
2146     EXECUTE ('UPDATE ' || tablename || ' c
2147     SET
2148       duration_rule = rcd.name,
2149       recuring_fine_rule = rrf.name,
2150       max_fine_rule = rmf.name,
2151       duration = rcd.normal,
2152       recuring_fine = rrf.normal,
2153       max_fine =
2154         CASE rmf.is_percent
2155           WHEN TRUE THEN (rmf.amount / 100.0) * ac.price
2156           ELSE rmf.amount
2157         END,
2158       renewal_remaining = rcd.max_renewals
2159     FROM
2160       config.rule_circ_duration rcd,
2161       config.rule_recuring_fine rrf,
2162       config.rule_max_fine rmf,
2163                         asset.copy ac
2164     WHERE
2165       rcd.id = ' || this_duration_rule || ' AND
2166       rrf.id = ' || this_fine_rule || ' AND
2167       rmf.id = ' || this_max_fine_rule || ' AND
2168                         ac.id = c.target_copy AND
2169       c.id = ' || circ || ';');
2170
2171     -- Keep track of where we are in the process
2172     n := n + 1;
2173     IF (n % 100 = 0) THEN
2174       RAISE INFO '%', n || ' of ' || n_circs
2175         || ' (' || (100*n/n_circs) || '%) circs updated.';
2176     END IF;
2177
2178   END LOOP;
2179
2180   RETURN;
2181 END;
2182
2183 $$ LANGUAGE plpgsql;
2184
2185 CREATE OR REPLACE FUNCTION migration_tools.apply_circ_matrix_after_20( tablename TEXT ) RETURNS VOID AS $$
2186
2187 -- Usage:
2188 --
2189 --   First make sure the circ matrix is loaded and the circulations
2190 --   have been staged to the extent possible (but at the very least
2191 --   circ_lib, target_copy, usr, and *_renewal).  User profiles and
2192 --   circ modifiers must also be in place.
2193 --
2194 --   SELECT migration_tools.apply_circ_matrix('m_pioneer.action_circulation');
2195 --
2196
2197 DECLARE
2198   circ_lib             INT;
2199   target_copy          INT;
2200   usr                  INT;
2201   is_renewal           BOOLEAN;
2202   this_duration_rule   INT;
2203   this_fine_rule       INT;
2204   this_max_fine_rule   INT;
2205   rcd                  config.rule_circ_duration%ROWTYPE;
2206   rrf                  config.rule_recurring_fine%ROWTYPE;
2207   rmf                  config.rule_max_fine%ROWTYPE;
2208   circ                 INT;
2209   n                    INT := 0;
2210   n_circs              INT;
2211   
2212 BEGIN
2213
2214   EXECUTE 'SELECT COUNT(*) FROM ' || tablename || ';' INTO n_circs;
2215
2216   FOR circ IN EXECUTE ('SELECT id FROM ' || tablename) LOOP
2217
2218     -- Fetch the correct rules for this circulation
2219     EXECUTE ('
2220       SELECT
2221         circ_lib,
2222         target_copy,
2223         usr,
2224         CASE
2225           WHEN phone_renewal OR desk_renewal OR opac_renewal THEN TRUE
2226           ELSE FALSE
2227         END
2228       FROM ' || tablename || ' WHERE id = ' || circ || ';')
2229       INTO circ_lib, target_copy, usr, is_renewal ;
2230     SELECT
2231       INTO this_duration_rule,
2232            this_fine_rule,
2233            this_max_fine_rule
2234       (matchpoint).duration_rule,
2235       (matchpoint).recurring_fine_rule,
2236       (matchpoint).max_fine_rule
2237       FROM action.find_circ_matrix_matchpoint(
2238         circ_lib,
2239         target_copy,
2240         usr,
2241         is_renewal
2242         );
2243     SELECT INTO rcd * FROM config.rule_circ_duration
2244       WHERE id = this_duration_rule;
2245     SELECT INTO rrf * FROM config.rule_recurring_fine
2246       WHERE id = this_fine_rule;
2247     SELECT INTO rmf * FROM config.rule_max_fine
2248       WHERE id = this_max_fine_rule;
2249
2250     -- Apply the rules to this circulation
2251     EXECUTE ('UPDATE ' || tablename || ' c
2252     SET
2253       duration_rule = rcd.name,
2254       recurring_fine_rule = rrf.name,
2255       max_fine_rule = rmf.name,
2256       duration = rcd.normal,
2257       recurring_fine = rrf.normal,
2258       max_fine =
2259         CASE rmf.is_percent
2260           WHEN TRUE THEN (rmf.amount / 100.0) * ac.price
2261           ELSE rmf.amount
2262         END,
2263       renewal_remaining = rcd.max_renewals,
2264       grace_period = rrf.grace_period
2265     FROM
2266       config.rule_circ_duration rcd,
2267       config.rule_recurring_fine rrf,
2268       config.rule_max_fine rmf,
2269                         asset.copy ac
2270     WHERE
2271       rcd.id = ' || this_duration_rule || ' AND
2272       rrf.id = ' || this_fine_rule || ' AND
2273       rmf.id = ' || this_max_fine_rule || ' AND
2274                         ac.id = c.target_copy AND
2275       c.id = ' || circ || ';');
2276
2277     -- Keep track of where we are in the process
2278     n := n + 1;
2279     IF (n % 100 = 0) THEN
2280       RAISE INFO '%', n || ' of ' || n_circs
2281         || ' (' || (100*n/n_circs) || '%) circs updated.';
2282     END IF;
2283
2284   END LOOP;
2285
2286   RETURN;
2287 END;
2288
2289 $$ LANGUAGE plpgsql;
2290
2291 -- TODO: make another version of the procedure below that can work with specified copy staging tables
2292 -- The following should track the logic of OpenILS::Application::AppUtils::get_copy_price
2293 CREATE OR REPLACE FUNCTION migration_tools.get_copy_price( item BIGINT ) RETURNS NUMERIC AS $$
2294 DECLARE
2295     context_lib             INT;
2296     charge_lost_on_zero     BOOLEAN;
2297     min_price               NUMERIC;
2298     max_price               NUMERIC;
2299     default_price           NUMERIC;
2300     working_price           NUMERIC;
2301
2302 BEGIN
2303
2304     SELECT INTO context_lib CASE WHEN call_number = -1 THEN circ_lib ELSE owning_lib END
2305         FROM asset.copy ac, asset.call_number acn WHERE ac.call_number = acn.id AND ac.id = item;
2306
2307     SELECT INTO charge_lost_on_zero value
2308         FROM actor.org_unit_ancestor_setting('circ.charge_lost_on_zero',context_lib);
2309
2310     SELECT INTO min_price value
2311         FROM actor.org_unit_ancestor_setting('circ.min_item_price',context_lib);
2312
2313     SELECT INTO max_price value
2314         FROM actor.org_unit_ancestor_setting('circ.max_item_price',context_lib);
2315
2316     SELECT INTO default_price value
2317         FROM actor.org_unit_ancestor_setting('cat.default_item_price',context_lib);
2318
2319     SELECT INTO working_price price FROM asset.copy WHERE id = item;
2320
2321     IF (working_price IS NULL OR (working_price = 0 AND charge_lost_on_zero)) THEN
2322         working_price := default_price;
2323     END IF;
2324
2325     IF (max_price IS NOT NULL AND working_price > max_price) THEN
2326         working_price := max_price;
2327     END IF;
2328
2329     IF (min_price IS NOT NULL AND working_price < min_price) THEN
2330         IF (working_price <> 0 OR charge_lost_on_zero IS NULL OR charge_lost_on_zero) THEN
2331             working_price := min_price;
2332         END IF;
2333     END IF;
2334
2335     RETURN working_price;
2336
2337 END;
2338
2339 $$ LANGUAGE plpgsql;
2340
2341 CREATE OR REPLACE FUNCTION migration_tools.apply_circ_matrix_to_specific_circ( tablename TEXT, circ BIGINT ) RETURNS VOID AS $$
2342
2343 -- Usage:
2344 --
2345 --   First make sure the circ matrix is loaded and the circulations
2346 --   have been staged to the extent possible (but at the very least
2347 --   circ_lib, target_copy, usr, and *_renewal).  User profiles and
2348 --   circ modifiers must also be in place.
2349 --
2350 --   SELECT migration_tools.apply_circ_matrix_to_specific_circ('m_nwrl.action_circulation', 18391960);
2351 --
2352
2353 DECLARE
2354   circ_lib             INT;
2355   target_copy          INT;
2356   usr                  INT;
2357   is_renewal           BOOLEAN;
2358   this_duration_rule   INT;
2359   this_fine_rule       INT;
2360   this_max_fine_rule   INT;
2361   rcd                  config.rule_circ_duration%ROWTYPE;
2362   rrf                  config.rule_recurring_fine%ROWTYPE;
2363   rmf                  config.rule_max_fine%ROWTYPE;
2364   n                    INT := 0;
2365   n_circs              INT := 1;
2366   
2367 BEGIN
2368
2369   --EXECUTE 'SELECT COUNT(*) FROM ' || tablename || ';' INTO n_circs;
2370
2371   --FOR circ IN EXECUTE ('SELECT id FROM ' || tablename) LOOP
2372
2373     -- Fetch the correct rules for this circulation
2374     EXECUTE ('
2375       SELECT
2376         circ_lib,
2377         target_copy,
2378         usr,
2379         CASE
2380           WHEN phone_renewal OR desk_renewal OR opac_renewal THEN TRUE
2381           ELSE FALSE
2382         END
2383       FROM ' || tablename || ' WHERE id = ' || circ || ';')
2384       INTO circ_lib, target_copy, usr, is_renewal ;
2385     SELECT
2386       INTO this_duration_rule,
2387            this_fine_rule,
2388            this_max_fine_rule
2389       (matchpoint).duration_rule,
2390       (matchpoint).recurring_fine_rule,
2391       (matchpoint).max_fine_rule
2392       FROM action.find_circ_matrix_matchpoint(
2393         circ_lib,
2394         target_copy,
2395         usr,
2396         is_renewal
2397         );
2398     SELECT INTO rcd * FROM config.rule_circ_duration
2399       WHERE id = this_duration_rule;
2400     SELECT INTO rrf * FROM config.rule_recurring_fine
2401       WHERE id = this_fine_rule;
2402     SELECT INTO rmf * FROM config.rule_max_fine
2403       WHERE id = this_max_fine_rule;
2404
2405     -- Apply the rules to this circulation
2406     EXECUTE ('UPDATE ' || tablename || ' c
2407     SET
2408       duration_rule = rcd.name,
2409       recurring_fine_rule = rrf.name,
2410       max_fine_rule = rmf.name,
2411       duration = rcd.normal,
2412       recurring_fine = rrf.normal,
2413       max_fine =
2414         CASE rmf.is_percent
2415           WHEN TRUE THEN (rmf.amount / 100.0) * migration_tools.get_copy_price(ac.id)
2416           ELSE rmf.amount
2417         END,
2418       renewal_remaining = rcd.max_renewals,
2419       grace_period = rrf.grace_period
2420     FROM
2421       config.rule_circ_duration rcd,
2422       config.rule_recurring_fine rrf,
2423       config.rule_max_fine rmf,
2424                         asset.copy ac
2425     WHERE
2426       rcd.id = ' || this_duration_rule || ' AND
2427       rrf.id = ' || this_fine_rule || ' AND
2428       rmf.id = ' || this_max_fine_rule || ' AND
2429                         ac.id = c.target_copy AND
2430       c.id = ' || circ || ';');
2431
2432     -- Keep track of where we are in the process
2433     n := n + 1;
2434     IF (n % 100 = 0) THEN
2435       RAISE INFO '%', n || ' of ' || n_circs
2436         || ' (' || (100*n/n_circs) || '%) circs updated.';
2437     END IF;
2438
2439   --END LOOP;
2440
2441   RETURN;
2442 END;
2443
2444 $$ LANGUAGE plpgsql;
2445
2446
2447
2448
2449 CREATE OR REPLACE FUNCTION migration_tools.stage_not_applicable_asset_stat_cats( schemaname TEXT ) RETURNS VOID AS $$
2450
2451 -- USAGE: Make sure the stat_cat and stat_cat_entry tables are populated, including exactly one 'Not Applicable' entry per stat cat.
2452 --        Then SELECT migration_tools.stage_not_applicable_asset_stat_cats('m_foo');
2453
2454 -- TODO: Make a variant that will go directly to production tables -- which would be useful for retrofixing the absence of N/A cats.
2455 -- TODO: Add a similar tool for actor stat cats, which behave differently.
2456
2457 DECLARE
2458         c                    TEXT := schemaname || '.asset_copy_legacy';
2459         sc                                                                       TEXT := schemaname || '.asset_stat_cat';
2460         sce                                                                      TEXT := schemaname || '.asset_stat_cat_entry';
2461         scecm                                                            TEXT := schemaname || '.asset_stat_cat_entry_copy_map';
2462         stat_cat                                                 INT;
2463   stat_cat_entry       INT;
2464   
2465 BEGIN
2466
2467   FOR stat_cat IN EXECUTE ('SELECT id FROM ' || sc) LOOP
2468
2469                 EXECUTE ('SELECT id FROM ' || sce || ' WHERE stat_cat = ' || stat_cat || E' AND value = \'Not Applicable\';') INTO stat_cat_entry;
2470
2471                 EXECUTE ('INSERT INTO ' || scecm || ' (owning_copy, stat_cat, stat_cat_entry)
2472                                                         SELECT c.id, ' || stat_cat || ', ' || stat_cat_entry || ' FROM ' || c || ' c WHERE c.id NOT IN
2473                                                         (SELECT owning_copy FROM ' || scecm || ' WHERE stat_cat = ' || stat_cat || ');');
2474
2475   END LOOP;
2476
2477   RETURN;
2478 END;
2479
2480 $$ LANGUAGE plpgsql;
2481
2482 CREATE OR REPLACE FUNCTION migration_tools.assign_standing_penalties ( ) RETURNS VOID AS $$
2483
2484 -- USAGE: Once circulation data has been loaded, and group penalty thresholds have been set up, run this.
2485 --        This will assign standing penalties as needed.
2486
2487 DECLARE
2488   org_unit  INT;
2489   usr       INT;
2490
2491 BEGIN
2492
2493   FOR org_unit IN EXECUTE ('SELECT DISTINCT org_unit FROM permission.grp_penalty_threshold;') LOOP
2494
2495     FOR usr IN EXECUTE ('SELECT id FROM actor.usr WHERE NOT deleted;') LOOP
2496   
2497       EXECUTE('SELECT actor.calculate_system_penalties(' || usr || ', ' || org_unit || ');');
2498
2499     END LOOP;
2500
2501   END LOOP;
2502
2503   RETURN;
2504
2505 END;
2506
2507 $$ LANGUAGE plpgsql;
2508
2509
2510 CREATE OR REPLACE FUNCTION migration_tools.insert_metarecords_for_pristine_database () RETURNS VOID AS $$
2511
2512 BEGIN
2513   INSERT INTO metabib.metarecord (fingerprint, master_record)
2514     SELECT  DISTINCT ON (b.fingerprint) b.fingerprint, b.id
2515       FROM  biblio.record_entry b
2516       WHERE NOT b.deleted
2517         AND b.id IN (SELECT r.id FROM biblio.record_entry r LEFT JOIN metabib.metarecord_source_map k ON (k.source = r.id) WHERE k.id IS NULL AND r.fingerprint IS NOT NULL)
2518         AND NOT EXISTS ( SELECT 1 FROM metabib.metarecord WHERE fingerprint = b.fingerprint )
2519       ORDER BY b.fingerprint, b.quality DESC;
2520   INSERT INTO metabib.metarecord_source_map (metarecord, source)
2521     SELECT  m.id, r.id
2522       FROM  biblio.record_entry r
2523       JOIN  metabib.metarecord m USING (fingerprint)
2524      WHERE  NOT r.deleted;
2525 END;
2526   
2527 $$ LANGUAGE plpgsql;
2528
2529
2530 CREATE OR REPLACE FUNCTION migration_tools.insert_metarecords_for_incumbent_database () RETURNS VOID AS $$
2531
2532 BEGIN
2533   INSERT INTO metabib.metarecord (fingerprint, master_record)
2534     SELECT  DISTINCT ON (b.fingerprint) b.fingerprint, b.id
2535       FROM  biblio.record_entry b
2536       WHERE NOT b.deleted
2537         AND b.id IN (SELECT r.id FROM biblio.record_entry r LEFT JOIN metabib.metarecord_source_map k ON (k.source = r.id) WHERE k.id IS NULL AND r.fingerprint IS NOT NULL)
2538         AND NOT EXISTS ( SELECT 1 FROM metabib.metarecord WHERE fingerprint = b.fingerprint )
2539       ORDER BY b.fingerprint, b.quality DESC;
2540   INSERT INTO metabib.metarecord_source_map (metarecord, source)
2541     SELECT  m.id, r.id
2542       FROM  biblio.record_entry r
2543         JOIN metabib.metarecord m USING (fingerprint)
2544       WHERE NOT r.deleted
2545         AND r.id IN (SELECT b.id FROM biblio.record_entry b LEFT JOIN metabib.metarecord_source_map k ON (k.source = b.id) WHERE k.id IS NULL);
2546 END;
2547     
2548 $$ LANGUAGE plpgsql;
2549
2550
2551 CREATE OR REPLACE FUNCTION migration_tools.create_cards( schemaname TEXT ) RETURNS VOID AS $$
2552
2553 -- USAGE: Make sure the patrons are staged in schemaname.actor_usr_legacy and have 'usrname' assigned.
2554 --        Then SELECT migration_tools.create_cards('m_foo');
2555
2556 DECLARE
2557         u                    TEXT := schemaname || '.actor_usr_legacy';
2558         c                    TEXT := schemaname || '.actor_card';
2559   
2560 BEGIN
2561
2562         EXECUTE ('DELETE FROM ' || c || ';');
2563         EXECUTE ('INSERT INTO ' || c || ' (usr, barcode) SELECT id, usrname FROM ' || u || ';');
2564         EXECUTE ('UPDATE ' || u || ' u SET card = c.id FROM ' || c || ' c WHERE c.usr = u.id;');
2565
2566   RETURN;
2567
2568 END;
2569
2570 $$ LANGUAGE plpgsql;
2571
2572
2573 CREATE OR REPLACE FUNCTION migration_tools.insert_856_9_conditional (TEXT, TEXT) RETURNS TEXT AS $$
2574
2575   ## USAGE: UPDATE biblio.record_entry SET marc = migration_tools.insert_856_9(marc, 'ABC') WHERE [...];
2576
2577   my ($marcxml, $shortname) = @_;
2578
2579   use MARC::Record;
2580   use MARC::File::XML;
2581
2582   my $xml = $marcxml;
2583
2584   eval {
2585     my $marc = MARC::Record->new_from_xml($marcxml, 'UTF-8');
2586
2587     foreach my $field ( $marc->field('856') ) {
2588       if ( scalar(grep( /(contentreserve|netlibrary|overdrive)\.com/i, $field->subfield('u'))) > 0 &&
2589            ! ( $field->as_string('9') =~ m/$shortname/ ) ) {
2590         $field->add_subfields( '9' => $shortname );
2591                                 $field->update( ind2 => '0');
2592       }
2593     }
2594
2595     $xml = $marc->as_xml_record;
2596     $xml =~ s/^<\?.+?\?>$//mo;
2597     $xml =~ s/\n//sgo;
2598     $xml =~ s/>\s+</></sgo;
2599   };
2600
2601   return $xml;
2602
2603 $$ LANGUAGE PLPERLU STABLE;
2604
2605 CREATE OR REPLACE FUNCTION migration_tools.insert_856_9 (TEXT, TEXT) RETURNS TEXT AS $$
2606
2607   ## USAGE: UPDATE biblio.record_entry SET marc = migration_tools.insert_856_9(marc, 'ABC') WHERE [...];
2608
2609   my ($marcxml, $shortname) = @_;
2610
2611   use MARC::Record;
2612   use MARC::File::XML;
2613
2614   my $xml = $marcxml;
2615
2616   eval {
2617     my $marc = MARC::Record->new_from_xml($marcxml, 'UTF-8');
2618
2619     foreach my $field ( $marc->field('856') ) {
2620       if ( ! $field->as_string('9') ) {
2621         $field->add_subfields( '9' => $shortname );
2622       }
2623     }
2624
2625     $xml = $marc->as_xml_record;
2626     $xml =~ s/^<\?.+?\?>$//mo;
2627     $xml =~ s/\n//sgo;
2628     $xml =~ s/>\s+</></sgo;
2629   };
2630
2631   return $xml;
2632
2633 $$ LANGUAGE PLPERLU STABLE;
2634
2635
2636 CREATE OR REPLACE FUNCTION migration_tools.change_call_number(copy_id BIGINT, new_label TEXT, cn_class BIGINT) RETURNS VOID AS $$
2637
2638 DECLARE
2639   old_volume   BIGINT;
2640   new_volume   BIGINT;
2641   bib          BIGINT;
2642   owner        INTEGER;
2643   old_label    TEXT;
2644   remainder    BIGINT;
2645
2646 BEGIN
2647
2648   -- Bail out if asked to change the label to ##URI##
2649   IF new_label = '##URI##' THEN
2650     RETURN;
2651   END IF;
2652
2653   -- Gather information
2654   SELECT call_number INTO old_volume FROM asset.copy WHERE id = copy_id;
2655   SELECT record INTO bib FROM asset.call_number WHERE id = old_volume;
2656   SELECT owning_lib, label INTO owner, old_label FROM asset.call_number WHERE id = old_volume;
2657
2658   -- Bail out if the label already is ##URI##
2659   IF old_label = '##URI##' THEN
2660     RETURN;
2661   END IF;
2662
2663   -- Bail out if the call number label is already correct
2664   IF new_volume = old_volume THEN
2665     RETURN;
2666   END IF;
2667
2668   -- Check whether we already have a destination volume available
2669   SELECT id INTO new_volume FROM asset.call_number 
2670     WHERE 
2671       record = bib AND
2672       owning_lib = owner AND
2673       label = new_label AND
2674       NOT deleted;
2675
2676   -- Create destination volume if needed
2677   IF NOT FOUND THEN
2678     INSERT INTO asset.call_number (creator, editor, record, owning_lib, label, label_class) 
2679       VALUES (1, 1, bib, owner, new_label, cn_class);
2680     SELECT id INTO new_volume FROM asset.call_number
2681       WHERE 
2682         record = bib AND
2683         owning_lib = owner AND
2684         label = new_label AND
2685         NOT deleted;
2686   END IF;
2687
2688   -- Move copy to destination
2689   UPDATE asset.copy SET call_number = new_volume WHERE id = copy_id;
2690
2691   -- Delete source volume if it is now empty
2692   SELECT id INTO remainder FROM asset.copy WHERE call_number = old_volume AND NOT deleted;
2693   IF NOT FOUND THEN
2694     DELETE FROM asset.call_number WHERE id = old_volume;
2695   END IF;
2696
2697 END;
2698
2699 $$ LANGUAGE plpgsql;
2700
2701 CREATE OR REPLACE FUNCTION migration_tools.zip_to_city_state_county (TEXT) RETURNS TEXT[] AS $$
2702
2703         my $input = $_[0];
2704         my %zipdata;
2705
2706         open (FH, '<', '/openils/var/data/zips.txt') or return ('No File Found', 'No File Found', 'No File Found');
2707
2708         while (<FH>) {
2709                 chomp;
2710                 my ($junk, $state, $city, $zip, $foo, $bar, $county, $baz, $morejunk) = split(/\|/);
2711                 $zipdata{$zip} = [$city, $state, $county];
2712         }
2713
2714         if (defined $zipdata{$input}) {
2715                 my ($city, $state, $county) = @{$zipdata{$input}};
2716                 return [$city, $state, $county];
2717         } elsif (defined $zipdata{substr $input, 0, 5}) {
2718                 my ($city, $state, $county) = @{$zipdata{substr $input, 0, 5}};
2719                 return [$city, $state, $county];
2720         } else {
2721                 return ['ZIP not found', 'ZIP not found', 'ZIP not found'];
2722         }
2723   
2724 $$ LANGUAGE PLPERLU STABLE;
2725
2726 CREATE OR REPLACE FUNCTION migration_tools.check_ou_depth ( ) RETURNS VOID AS $$
2727
2728 DECLARE
2729   ou  INT;
2730         org_unit_depth INT;
2731         ou_parent INT;
2732         parent_depth INT;
2733   errors_found BOOLEAN;
2734         ou_shortname TEXT;
2735         parent_shortname TEXT;
2736         ou_type_name TEXT;
2737         parent_type TEXT;
2738         type_id INT;
2739         type_depth INT;
2740         type_parent INT;
2741         type_parent_depth INT;
2742         proper_parent TEXT;
2743
2744 BEGIN
2745
2746         errors_found := FALSE;
2747
2748 -- Checking actor.org_unit_type
2749
2750         FOR type_id IN EXECUTE ('SELECT id FROM actor.org_unit_type ORDER BY id;') LOOP
2751
2752                 SELECT depth FROM actor.org_unit_type WHERE id = type_id INTO type_depth;
2753                 SELECT parent FROM actor.org_unit_type WHERE id = type_id INTO type_parent;
2754
2755                 IF type_parent IS NOT NULL THEN
2756
2757                         SELECT depth FROM actor.org_unit_type WHERE id = type_parent INTO type_parent_depth;
2758
2759                         IF type_depth - type_parent_depth <> 1 THEN
2760                                 SELECT name FROM actor.org_unit_type WHERE id = type_id INTO ou_type_name;
2761                                 SELECT name FROM actor.org_unit_type WHERE id = type_parent INTO parent_type;
2762                                 RAISE INFO 'The % org unit type has a depth of %, but its parent org unit type, %, has a depth of %.',
2763                                         ou_type_name, type_depth, parent_type, type_parent_depth;
2764                                 errors_found := TRUE;
2765
2766                         END IF;
2767
2768                 END IF;
2769
2770         END LOOP;
2771
2772 -- Checking actor.org_unit
2773
2774   FOR ou IN EXECUTE ('SELECT id FROM actor.org_unit ORDER BY shortname;') LOOP
2775
2776                 SELECT parent_ou FROM actor.org_unit WHERE id = ou INTO ou_parent;
2777                 SELECT t.depth FROM actor.org_unit_type t, actor.org_unit o WHERE o.ou_type = t.id and o.id = ou INTO org_unit_depth;
2778                 SELECT t.depth FROM actor.org_unit_type t, actor.org_unit o WHERE o.ou_type = t.id and o.id = ou_parent INTO parent_depth;
2779                 SELECT shortname FROM actor.org_unit WHERE id = ou INTO ou_shortname;
2780                 SELECT shortname FROM actor.org_unit WHERE id = ou_parent INTO parent_shortname;
2781                 SELECT t.name FROM actor.org_unit_type t, actor.org_unit o WHERE o.ou_type = t.id and o.id = ou INTO ou_type_name;
2782                 SELECT t.name FROM actor.org_unit_type t, actor.org_unit o WHERE o.ou_type = t.id and o.id = ou_parent INTO parent_type;
2783
2784                 IF ou_parent IS NOT NULL THEN
2785
2786                         IF      (org_unit_depth - parent_depth <> 1) OR (
2787                                 (SELECT parent FROM actor.org_unit_type WHERE name = ou_type_name) <> (SELECT id FROM actor.org_unit_type WHERE name = parent_type)
2788                         ) THEN
2789                                 RAISE INFO '% (org unit %) is a % (depth %) but its parent, % (org unit %), is a % (depth %).', 
2790                                         ou_shortname, ou, ou_type_name, org_unit_depth, parent_shortname, ou_parent, parent_type, parent_depth;
2791                                 errors_found := TRUE;
2792                         END IF;
2793
2794                 END IF;
2795
2796   END LOOP;
2797
2798         IF NOT errors_found THEN
2799                 RAISE INFO 'No errors found.';
2800         END IF;
2801
2802   RETURN;
2803
2804 END;
2805
2806 $$ LANGUAGE plpgsql;
2807
2808
2809 CREATE OR REPLACE FUNCTION migration_tools.refresh_opac_visible_copies ( ) RETURNS VOID AS $$
2810
2811 BEGIN   
2812
2813         DELETE FROM asset.opac_visible_copies;
2814
2815         INSERT INTO asset.opac_visible_copies (id, circ_lib, record)
2816                 SELECT DISTINCT
2817                         cp.id, cp.circ_lib, cn.record
2818                 FROM
2819                         asset.copy cp
2820                         JOIN asset.call_number cn ON (cn.id = cp.call_number)
2821                         JOIN actor.org_unit a ON (cp.circ_lib = a.id)
2822                         JOIN asset.copy_location cl ON (cp.location = cl.id)
2823                         JOIN config.copy_status cs ON (cp.status = cs.id)
2824                         JOIN biblio.record_entry b ON (cn.record = b.id)
2825                 WHERE 
2826                         NOT cp.deleted AND
2827                         NOT cn.deleted AND
2828                         NOT b.deleted AND
2829                         cs.opac_visible AND
2830                         cl.opac_visible AND
2831                         cp.opac_visible AND
2832                         a.opac_visible AND
2833                         cp.id NOT IN (SELECT id FROM asset.opac_visible_copies);
2834
2835 END;
2836
2837 $$ LANGUAGE plpgsql;
2838
2839
2840 CREATE OR REPLACE FUNCTION migration_tools.change_owning_lib(copy_id BIGINT, new_owning_lib INTEGER) RETURNS VOID AS $$
2841
2842 DECLARE
2843   old_volume     BIGINT;
2844   new_volume     BIGINT;
2845   bib            BIGINT;
2846   old_owning_lib INTEGER;
2847         old_label      TEXT;
2848   remainder      BIGINT;
2849
2850 BEGIN
2851
2852   -- Gather information
2853   SELECT call_number INTO old_volume FROM asset.copy WHERE id = copy_id;
2854   SELECT record INTO bib FROM asset.call_number WHERE id = old_volume;
2855   SELECT owning_lib, label INTO old_owning_lib, old_label FROM asset.call_number WHERE id = old_volume;
2856
2857         -- Bail out if the new_owning_lib is not the ID of an org_unit
2858         IF new_owning_lib NOT IN (SELECT id FROM actor.org_unit) THEN
2859                 RAISE WARNING 
2860                         '% is not a valid actor.org_unit ID; no change made.', 
2861                                 new_owning_lib;
2862                 RETURN;
2863         END IF;
2864
2865   -- Bail out discreetly if the owning_lib is already correct
2866   IF new_owning_lib = old_owning_lib THEN
2867     RETURN;
2868   END IF;
2869
2870   -- Check whether we already have a destination volume available
2871   SELECT id INTO new_volume FROM asset.call_number 
2872     WHERE 
2873       record = bib AND
2874       owning_lib = new_owning_lib AND
2875       label = old_label AND
2876       NOT deleted;
2877
2878   -- Create destination volume if needed
2879   IF NOT FOUND THEN
2880     INSERT INTO asset.call_number (creator, editor, record, owning_lib, label) 
2881       VALUES (1, 1, bib, new_owning_lib, old_label);
2882     SELECT id INTO new_volume FROM asset.call_number
2883       WHERE 
2884         record = bib AND
2885         owning_lib = new_owning_lib AND
2886         label = old_label AND
2887         NOT deleted;
2888   END IF;
2889
2890   -- Move copy to destination
2891   UPDATE asset.copy SET call_number = new_volume WHERE id = copy_id;
2892
2893   -- Delete source volume if it is now empty
2894   SELECT id INTO remainder FROM asset.copy WHERE call_number = old_volume AND NOT deleted;
2895   IF NOT FOUND THEN
2896     DELETE FROM asset.call_number WHERE id = old_volume;
2897   END IF;
2898
2899 END;
2900
2901 $$ LANGUAGE plpgsql;
2902
2903
2904 CREATE OR REPLACE FUNCTION migration_tools.change_owning_lib(copy_id BIGINT, new_owner TEXT) RETURNS VOID AS $$
2905
2906 -- You can use shortnames with this function, which looks up the org unit ID and passes it to change_owning_lib(BIGINT,INTEGER).
2907
2908 DECLARE
2909         new_owning_lib  INTEGER;
2910
2911 BEGIN
2912
2913         -- Parse the new_owner as an org unit ID or shortname
2914         IF new_owner IN (SELECT shortname FROM actor.org_unit) THEN
2915                 SELECT id INTO new_owning_lib FROM actor.org_unit WHERE shortname = new_owner;
2916                 PERFORM migration_tools.change_owning_lib(copy_id, new_owning_lib);
2917         ELSIF new_owner ~ E'^[0-9]+$' THEN
2918                 IF new_owner::INTEGER IN (SELECT id FROM actor.org_unit) THEN
2919                         RAISE INFO 
2920                                 '%',
2921                                 E'You don\'t need to put the actor.org_unit ID in quotes; '
2922                                         || E'if you put it in quotes, I\'m going to try to parse it as a shortname first.';
2923                         new_owning_lib := new_owner::INTEGER;
2924                 PERFORM migration_tools.change_owning_lib(copy_id, new_owning_lib);
2925                 END IF;
2926         ELSE
2927                 RAISE WARNING 
2928                         '% is not a valid actor.org_unit shortname or ID; no change made.', 
2929                         new_owning_lib;
2930                 RETURN;
2931         END IF;
2932
2933 END;
2934
2935 $$ LANGUAGE plpgsql;
2936
2937 CREATE OR REPLACE FUNCTION migration_tools.marc_parses( TEXT ) RETURNS BOOLEAN AS $func$
2938
2939 use MARC::Record;
2940 use MARC::File::XML (BinaryEncoding => 'UTF-8');
2941 use MARC::Charset;
2942
2943 MARC::Charset->assume_unicode(1);
2944
2945 my $xml = shift;
2946
2947 eval {
2948     my $r = MARC::Record->new_from_xml( $xml );
2949     my $output_xml = $r->as_xml_record();
2950 };
2951 if ($@) {
2952     return 0;
2953 } else {
2954     return 1;
2955 }
2956
2957 $func$ LANGUAGE PLPERLU;
2958 COMMENT ON FUNCTION migration_tools.marc_parses(TEXT) IS 'Return boolean indicating if MARCXML string is parseable by MARC::File::XML';
2959
2960 CREATE OR REPLACE FUNCTION migration_tools.simple_export_library_config(dir TEXT, orgs INT[]) RETURNS VOID AS $FUNC$
2961 BEGIN
2962    EXECUTE $$COPY (SELECT * FROM actor.hours_of_operation WHERE id IN ($$ ||
2963            ARRAY_TO_STRING(orgs, ',') || $$)$$ ||
2964            $$) TO '$$ ||  dir || $$/actor_hours_of_operation'$$;
2965    EXECUTE $$COPY (SELECT org_unit, close_start, close_end, reason FROM actor.org_unit_closed WHERE org_unit IN ($$ ||
2966            ARRAY_TO_STRING(orgs, ',') || $$)$$ ||
2967            $$) TO '$$ ||  dir || $$/actor_org_unit_closed'$$;
2968    EXECUTE $$COPY (SELECT org_unit, name, value FROM actor.org_unit_setting WHERE org_unit IN ($$ ||
2969            ARRAY_TO_STRING(orgs, ',') || $$)$$ ||
2970            $$) TO '$$ ||  dir || $$/actor_org_unit_setting'$$;
2971    EXECUTE $$COPY (SELECT name, owning_lib, holdable, hold_verify, opac_visible, circulate FROM asset.copy_location WHERE owning_lib IN ($$ ||
2972            ARRAY_TO_STRING(orgs, ',') || $$)$$ ||
2973            $$) TO '$$ ||  dir || $$/asset_copy_location'$$;
2974    EXECUTE $$COPY (SELECT grp, org_unit, penalty, threshold FROM permission.grp_penalty_threshold WHERE org_unit IN ($$ ||
2975            ARRAY_TO_STRING(orgs, ',') || $$)$$ ||
2976            $$) TO '$$ ||  dir || $$/permission_grp_penalty_threshold'$$;
2977    EXECUTE $$COPY (SELECT owning_lib, label, label_sortkey FROM asset.call_number_prefix WHERE owning_lib IN ($$ ||
2978            ARRAY_TO_STRING(orgs, ',') || $$)$$ ||
2979            $$) TO '$$ ||  dir || $$/asset_call_number_prefix'$$;
2980    EXECUTE $$COPY (SELECT owning_lib, label, label_sortkey FROM asset.call_number_suffix WHERE owning_lib IN ($$ ||
2981            ARRAY_TO_STRING(orgs, ',') || $$)$$ ||
2982            $$) TO '$$ ||  dir || $$/asset_call_number_suffix'$$;
2983    EXECUTE $$COPY config.rule_circ_duration TO '$$ ||  dir || $$/config_rule_circ_duration'$$;
2984    EXECUTE $$COPY config.rule_age_hold_protect TO '$$ ||  dir || $$/config_rule_age_hold_protect'$$;
2985    EXECUTE $$COPY config.rule_max_fine TO '$$ ||  dir || $$/config_rule_max_fine'$$;
2986    EXECUTE $$COPY config.rule_recurring_fine TO '$$ ||  dir || $$/config_rule_recurring_fine'$$;
2987    EXECUTE $$COPY permission.grp_tree TO '$$ ||  dir || $$/permission_grp_tree'$$;
2988 END;
2989 $FUNC$ LANGUAGE PLPGSQL;
2990
2991 CREATE OR REPLACE FUNCTION migration_tools.simple_import_library_config(dir TEXT) RETURNS VOID AS $FUNC$
2992 BEGIN
2993    EXECUTE $$COPY actor.hours_of_operation FROM '$$ ||  dir || $$/actor_hours_of_operation'$$;
2994    EXECUTE $$COPY actor.org_unit_closed (org_unit, close_start, close_end, reason) FROM '$$ ||  dir || $$/actor_org_unit_closed'$$;
2995    EXECUTE $$COPY actor.org_unit_setting (org_unit, name, value) FROM '$$ ||  dir || $$/actor_org_unit_setting'$$;
2996    EXECUTE $$COPY asset.copy_location (name, owning_lib, holdable, hold_verify, opac_visible, circulate) FROM '$$ ||  dir || $$/asset_copy_location'$$;
2997    EXECUTE $$COPY permission.grp_penalty_threshold (grp, org_unit, penalty, threshold) FROM '$$ ||  dir || $$/permission_grp_penalty_threshold'$$;
2998    EXECUTE $$COPY asset.call_number_prefix (owning_lib, label, label_sortkey) FROM '$$ ||  dir || $$/asset_call_number_prefix'$$;
2999    EXECUTE $$COPY asset.call_number_suffix (owning_lib, label, label_sortkey) FROM '$$ ||  dir || $$/asset_call_number_suffix'$$;
3000
3001    -- import any new circ rules
3002    PERFORM migration_tools.simple_import_new_rows_by_value(dir, 'config', 'rule_circ_duration', 'id', 'name');
3003    PERFORM migration_tools.simple_import_new_rows_by_value(dir, 'config', 'rule_age_hold_protect', 'id', 'name');
3004    PERFORM migration_tools.simple_import_new_rows_by_value(dir, 'config', 'rule_max_fine', 'id', 'name');
3005    PERFORM migration_tools.simple_import_new_rows_by_value(dir, 'config', 'rule_recurring_fine', 'id', 'name');
3006
3007    -- and permission groups
3008    PERFORM migration_tools.simple_import_new_rows_by_value(dir, 'permission', 'grp_tree', 'id', 'name');
3009
3010 END;
3011 $FUNC$ LANGUAGE PLPGSQL;
3012
3013
3014 CREATE OR REPLACE FUNCTION migration_tools.simple_import_new_rows_by_value(dir TEXT, schemaname TEXT, tablename TEXT, idcol TEXT, matchcol TEXT) RETURNS VOID AS $FUNC$
3015 DECLARE
3016     name TEXT;
3017     loopq TEXT;
3018     existsq TEXT;
3019     ct INTEGER;
3020     cols TEXT[];
3021     copyst TEXT;
3022 BEGIN
3023     EXECUTE $$DROP TABLE IF EXISTS tmp_$$ || tablename;
3024     EXECUTE $$CREATE TEMPORARY TABLE tmp_$$ || tablename || $$ AS SELECT * FROM $$ || schemaname || '.' || tablename || $$ LIMIT 0$$;
3025     EXECUTE $$COPY tmp_$$ || tablename || $$ FROM '$$ ||  dir || '/' || schemaname || '_' || tablename || $$'$$;
3026     loopq := 'SELECT ' || matchcol || ' FROM tmp_' || tablename || ' ORDER BY ' || idcol;
3027     existsq := 'SELECT COUNT(*) FROM ' || schemaname || '.' || tablename || ' WHERE ' || matchcol || ' = $1';
3028     SELECT ARRAY_AGG(column_name::TEXT) INTO cols FROM information_schema.columns WHERE table_schema = schemaname AND table_name = tablename AND column_name <> idcol;
3029     FOR name IN EXECUTE loopq LOOP
3030        EXECUTE existsq INTO ct USING name;
3031        IF ct = 0 THEN
3032            RAISE NOTICE 'inserting %.% row for %', schemaname, tablename, name;
3033            copyst := 'INSERT INTO ' || schemaname || '.' || tablename || ' (' || ARRAY_TO_STRING(cols, ',') || ') SELECT ' || ARRAY_TO_STRING(cols, ',') || 
3034                      ' FROM tmp_' || tablename || ' WHERE ' || matchcol || ' = $1';
3035            EXECUTE copyst USING name;
3036        END IF;
3037     END LOOP;
3038 END;
3039 $FUNC$ LANGUAGE PLPGSQL;
3040
3041 CREATE OR REPLACE FUNCTION migration_tools.split_rows_on_column_with_delimiter(schemaname TEXT, tablename TEXT, matchcol TEXT, delimiter TEXT) RETURNS VOID AS $FUNC$
3042 DECLARE
3043     id BIGINT;
3044     loopq TEXT;
3045     cols TEXT[];
3046     splitst TEXT;
3047 BEGIN
3048     loopq := 'SELECT id FROM ' || schemaname || '.' || tablename || ' WHERE ' || matchcol || ' ~ $1 ORDER BY id';
3049     SELECT ARRAY_AGG(column_name::TEXT) INTO cols FROM information_schema.columns WHERE table_schema = schemaname AND table_name = tablename AND column_name <> 'id' AND column_name <> matchcol;
3050     FOR id IN EXECUTE loopq USING delimiter LOOP
3051        RAISE NOTICE 'splitting row from %.% with id = %', schemaname, tablename, id;
3052        splitst := 'INSERT INTO ' || schemaname || '.' || tablename || ' (' || ARRAY_TO_STRING(cols, ',') || ', ' || matchcol || ') SELECT ' || ARRAY_TO_STRING(cols, ',') || ', s.token ' ||
3053                  ' FROM ' || schemaname || '.' || tablename || ' t, UNNEST(STRING_TO_ARRAY(t.' || matchcol || ', $2)) s(token) WHERE id = $1';
3054        EXECUTE splitst USING id, delimiter;
3055     END LOOP;
3056 END;
3057 $FUNC$ LANGUAGE PLPGSQL;
3058
3059 CREATE OR REPLACE FUNCTION migration_tools.merge_marc_fields( TEXT, TEXT, TEXT[] ) RETURNS TEXT AS $func$
3060
3061 use strict;
3062 use warnings;
3063
3064 use MARC::Record;
3065 use MARC::File::XML (BinaryEncoding => 'UTF-8');
3066 use MARC::Charset;
3067
3068 MARC::Charset->assume_unicode(1);
3069
3070 my $target_xml = shift;
3071 my $source_xml = shift;
3072 my $tags = shift;
3073
3074 my $target;
3075 my $source;
3076
3077 eval { $target = MARC::Record->new_from_xml( $target_xml ); };
3078 if ($@) {
3079     return;
3080 }
3081 eval { $source = MARC::Record->new_from_xml( $source_xml ); };
3082 if ($@) {
3083     return;
3084 }
3085
3086 my $source_id = $source->subfield('901', 'c');
3087 $source_id = $source->subfield('903', 'a') unless $source_id;
3088 my $target_id = $target->subfield('901', 'c');
3089 $target_id = $target->subfield('903', 'a') unless $target_id;
3090
3091 my %existing_fields;
3092 foreach my $tag (@$tags) {
3093     my %existing_fields = map { $_->as_formatted() => 1 } $target->field($tag);
3094     my @to_add = grep { not exists $existing_fields{$_->as_formatted()} } $source->field($tag);
3095     $target->insert_fields_ordered(map { $_->clone() } @to_add);
3096     if (@to_add) {
3097         elog(NOTICE, "Merged $tag tag(s) from $source_id to $target_id");
3098     }
3099 }
3100
3101 my $xml = $target->as_xml_record;
3102 $xml =~ s/^<\?.+?\?>$//mo;
3103 $xml =~ s/\n//sgo;
3104 $xml =~ s/>\s+</></sgo;
3105
3106 return $xml;
3107
3108 $func$ LANGUAGE PLPERLU;
3109 COMMENT ON FUNCTION migration_tools.merge_marc_fields( TEXT, TEXT, TEXT[] ) IS 'Given two MARCXML strings and an array of tags, returns MARCXML representing the merge of the specified fields from the second MARCXML record into the first.';
3110
3111 CREATE OR REPLACE FUNCTION migration_tools.make_stub_bib (text[], text[]) RETURNS TEXT AS $func$
3112
3113 use strict;
3114 use warnings;
3115
3116 use MARC::Record;
3117 use MARC::File::XML (BinaryEncoding => 'UTF-8');
3118 use Text::CSV;
3119
3120 my $in_tags = shift;
3121 my $in_values = shift;
3122
3123 # hack-and-slash parsing of array-passed-as-string;
3124 # this can go away once everybody is running Postgres 9.1+
3125 my $csv = Text::CSV->new({binary => 1});
3126 $in_tags =~ s/^{//;
3127 $in_tags =~ s/}$//;
3128 my $status = $csv->parse($in_tags);
3129 my $tags = [ $csv->fields() ];
3130 $in_values =~ s/^{//;
3131 $in_values =~ s/}$//;
3132 $status = $csv->parse($in_values);
3133 my $values = [ $csv->fields() ];
3134
3135 my $marc = MARC::Record->new();
3136
3137 $marc->leader('00000nam a22000007  4500');
3138 $marc->append_fields(MARC::Field->new('008', '000000s                       000   eng d'));
3139
3140 foreach my $i (0..$#$tags) {
3141     my ($tag, $sf);
3142     if ($tags->[$i] =~ /^(\d{3})([0-9a-z])$/) {
3143         $tag = $1;
3144         $sf = $2;
3145         $marc->append_fields(MARC::Field->new($tag, ' ', ' ', $sf => $values->[$i])) if $values->[$i] !~ /^\s*$/ and $values->[$i] ne 'NULL';
3146     } elsif ($tags->[$i] =~ /^(\d{3})$/) {
3147         $tag = $1;
3148         $marc->append_fields(MARC::Field->new($tag, $values->[$i])) if $values->[$i] !~ /^\s*$/ and $values->[$i] ne 'NULL';
3149     }
3150 }
3151
3152 my $xml = $marc->as_xml_record;
3153 $xml =~ s/^<\?.+?\?>$//mo;
3154 $xml =~ s/\n//sgo;
3155 $xml =~ s/>\s+</></sgo;
3156
3157 return $xml;
3158
3159 $func$ LANGUAGE PLPERLU;
3160 COMMENT ON FUNCTION migration_tools.make_stub_bib (text[], text[]) IS $$Simple function to create a stub MARCXML bib from a set of columns.
3161 The first argument is an array of tag/subfield specifiers, e.g., ARRAY['001', '245a', '500a'].
3162 The second argument is an array of text containing the values to plug into each field.  
3163 If the value for a given field is NULL or the empty string, it is not inserted.
3164 $$;
3165
3166 CREATE OR REPLACE FUNCTION migration_tools.set_indicator (TEXT, TEXT, INTEGER, CHAR(1)) RETURNS TEXT AS $func$
3167
3168 my ($marcxml, $tag, $pos, $value) = @_;
3169
3170 use MARC::Record;
3171 use MARC::File::XML (BinaryEncoding => 'UTF-8');
3172 use MARC::Charset;
3173 use strict;
3174
3175 MARC::Charset->assume_unicode(1);
3176
3177 elog(ERROR, 'indicator position must be either 1 or 2') unless $pos =~ /^[12]$/;
3178 elog(ERROR, 'MARC tag must be numeric') unless $tag =~ /^\d{3}$/;
3179 elog(ERROR, 'MARC tag must not be control field') if $tag =~ /^00/;
3180 elog(ERROR, 'Value must be exactly one character') unless $value =~ /^.$/;
3181
3182 my $xml = $marcxml;
3183 eval {
3184     my $marc = MARC::Record->new_from_xml($marcxml, 'UTF-8');
3185
3186     foreach my $field ($marc->field($tag)) {
3187         $field->update("ind$pos" => $value);
3188     }
3189     $xml = $marc->as_xml_record;
3190     $xml =~ s/^<\?.+?\?>$//mo;
3191     $xml =~ s/\n//sgo;
3192     $xml =~ s/>\s+</></sgo;
3193 };
3194 return $xml;
3195
3196 $func$ LANGUAGE PLPERLU;
3197
3198 COMMENT ON FUNCTION migration_tools.set_indicator(TEXT, TEXT, INTEGER, CHAR(1)) IS $$Set indicator value of a specified MARC field.
3199 The first argument is a MARCXML string.
3200 The second argument is a MARC tag.
3201 The third argument is the indicator position, either 1 or 2.
3202 The fourth argument is the character to set the indicator value to.
3203 All occurences of the specified field will be changed.
3204 The function returns the revised MARCXML string.$$;
3205
3206 CREATE OR REPLACE FUNCTION migration_tools.create_staff_user(
3207     username TEXT,
3208     password TEXT,
3209     org TEXT,
3210     perm_group TEXT,
3211     first_name TEXT DEFAULT '',
3212     last_name TEXT DEFAULT ''
3213 ) RETURNS VOID AS $func$
3214 BEGIN
3215     RAISE NOTICE '%', org ;
3216     INSERT INTO actor.usr (usrname, passwd, ident_type, first_given_name, family_name, home_ou, profile)
3217     SELECT username, password, 1, first_name, last_name, aou.id, pgt.id
3218     FROM   actor.org_unit aou, permission.grp_tree pgt
3219     WHERE  aou.shortname = org
3220     AND    pgt.name = perm_group;
3221 END
3222 $func$
3223 LANGUAGE PLPGSQL;
3224
3225 -- example: SELECT * FROM migration_tools.duplicate_template(5,'{3,4}');
3226 CREATE OR REPLACE FUNCTION migration_tools.duplicate_template (INTEGER, INTEGER[]) RETURNS VOID AS $$
3227     DECLARE
3228         target_event_def ALIAS FOR $1;
3229         orgs ALIAS FOR $2;
3230     BEGIN
3231         DROP TABLE IF EXISTS new_atevdefs;
3232         CREATE TEMP TABLE new_atevdefs (atevdef INTEGER);
3233         FOR i IN array_lower(orgs,1) .. array_upper(orgs,1) LOOP
3234             INSERT INTO action_trigger.event_definition (
3235                 active
3236                 ,owner
3237                 ,name
3238                 ,hook
3239                 ,validator
3240                 ,reactor
3241                 ,cleanup_success
3242                 ,cleanup_failure
3243                 ,delay
3244                 ,max_delay
3245                 ,usr_field
3246                 ,opt_in_setting
3247                 ,delay_field
3248                 ,group_field
3249                 ,template
3250                 ,granularity
3251                 ,repeat_delay
3252             ) SELECT
3253                 'f'
3254                 ,orgs[i]
3255                 ,name || ' (clone of '||target_event_def||')'
3256                 ,hook
3257                 ,validator
3258                 ,reactor
3259                 ,cleanup_success
3260                 ,cleanup_failure
3261                 ,delay
3262                 ,max_delay
3263                 ,usr_field
3264                 ,opt_in_setting
3265                 ,delay_field
3266                 ,group_field
3267                 ,template
3268                 ,granularity
3269                 ,repeat_delay
3270             FROM
3271                 action_trigger.event_definition
3272             WHERE
3273                 id = target_event_def
3274             ;
3275             RAISE INFO 'created atevdef with id = %', currval('action_trigger.event_definition_id_seq');
3276             INSERT INTO new_atevdefs SELECT currval('action_trigger.event_definition_id_seq');
3277             INSERT INTO action_trigger.environment (
3278                 event_def
3279                 ,path
3280                 ,collector
3281                 ,label
3282             ) SELECT
3283                 currval('action_trigger.event_definition_id_seq')
3284                 ,path
3285                 ,collector
3286                 ,label
3287             FROM
3288                 action_trigger.environment
3289             WHERE
3290                 event_def = target_event_def
3291             ;
3292             INSERT INTO action_trigger.event_params (
3293                 event_def
3294                 ,param
3295                 ,value
3296             ) SELECT
3297                 currval('action_trigger.event_definition_id_seq')
3298                 ,param
3299                 ,value
3300             FROM
3301                 action_trigger.event_params
3302             WHERE
3303                 event_def = target_event_def
3304             ;
3305         END LOOP;
3306         RAISE INFO '-- UPDATE action_trigger.event_definition SET active = CASE WHEN id = % THEN FALSE ELSE TRUE END WHERE id in (%,%);', target_event_def, target_event_def, (SELECT array_to_string(array_agg(atevdef),',') from new_atevdefs);
3307     END;
3308 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3309
3310 -- example: SELECT * FROM migration_tools.duplicate_template_but_change_delay(5,'{3,4}','00:30:00'::INTERVAL);
3311 CREATE OR REPLACE FUNCTION migration_tools.duplicate_template_but_change_delay (INTEGER, INTEGER[], INTERVAL) RETURNS VOID AS $$
3312     DECLARE
3313         target_event_def ALIAS FOR $1;
3314         orgs ALIAS FOR $2;
3315         new_interval ALIAS FOR $3;
3316     BEGIN
3317         DROP TABLE IF EXISTS new_atevdefs;
3318         CREATE TEMP TABLE new_atevdefs (atevdef INTEGER);
3319         FOR i IN array_lower(orgs,1) .. array_upper(orgs,1) LOOP
3320             INSERT INTO action_trigger.event_definition (
3321                 active
3322                 ,owner
3323                 ,name
3324                 ,hook
3325                 ,validator
3326                 ,reactor
3327                 ,cleanup_success
3328                 ,cleanup_failure
3329                 ,delay
3330                 ,max_delay
3331                 ,usr_field
3332                 ,opt_in_setting
3333                 ,delay_field
3334                 ,group_field
3335                 ,template
3336                 ,granularity
3337                 ,repeat_delay
3338             ) SELECT
3339                 'f'
3340                 ,orgs[i]
3341                 ,name || ' (clone of '||target_event_def||')'
3342                 ,hook
3343                 ,validator
3344                 ,reactor
3345                 ,cleanup_success
3346                 ,cleanup_failure
3347                 ,new_interval
3348                 ,max_delay
3349                 ,usr_field
3350                 ,opt_in_setting
3351                 ,delay_field
3352                 ,group_field
3353                 ,template
3354                 ,granularity
3355                 ,repeat_delay
3356             FROM
3357                 action_trigger.event_definition
3358             WHERE
3359                 id = target_event_def
3360             ;
3361             RAISE INFO 'created atevdef with id = %', currval('action_trigger.event_definition_id_seq');
3362             INSERT INTO new_atevdefs SELECT currval('action_trigger.event_definition_id_seq');
3363             INSERT INTO action_trigger.environment (
3364                 event_def
3365                 ,path
3366                 ,collector
3367                 ,label
3368             ) SELECT
3369                 currval('action_trigger.event_definition_id_seq')
3370                 ,path
3371                 ,collector
3372                 ,label
3373             FROM
3374                 action_trigger.environment
3375             WHERE
3376                 event_def = target_event_def
3377             ;
3378             INSERT INTO action_trigger.event_params (
3379                 event_def
3380                 ,param
3381                 ,value
3382             ) SELECT
3383                 currval('action_trigger.event_definition_id_seq')
3384                 ,param
3385                 ,value
3386             FROM
3387                 action_trigger.event_params
3388             WHERE
3389                 event_def = target_event_def
3390             ;
3391         END LOOP;
3392         RAISE INFO '-- UPDATE action_trigger.event_definition SET active = CASE WHEN id = % THEN FALSE ELSE TRUE END WHERE id in (%,%);', target_event_def, target_event_def, (SELECT array_to_string(array_agg(atevdef),',') from new_atevdefs);
3393     END;
3394 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3395
3396 -- example: SELECT * FROM migration_tools.duplicate_templates(3,'{5,6}');
3397 CREATE OR REPLACE FUNCTION migration_tools.duplicate_templates (INTEGER, INTEGER[]) RETURNS VOID AS $$
3398     DECLARE
3399         org ALIAS FOR $1;
3400         target_event_defs ALIAS FOR $2;
3401     BEGIN
3402         DROP TABLE IF EXISTS new_atevdefs;
3403         CREATE TEMP TABLE new_atevdefs (atevdef INTEGER);
3404         FOR i IN array_lower(target_event_defs,1) .. array_upper(target_event_defs,1) LOOP
3405             INSERT INTO action_trigger.event_definition (
3406                 active
3407                 ,owner
3408                 ,name
3409                 ,hook
3410                 ,validator
3411                 ,reactor
3412                 ,cleanup_success
3413                 ,cleanup_failure
3414                 ,delay
3415                 ,max_delay
3416                 ,usr_field
3417                 ,opt_in_setting
3418                 ,delay_field
3419                 ,group_field
3420                 ,template
3421                 ,granularity
3422                 ,repeat_delay
3423             ) SELECT
3424                 'f'
3425                 ,org
3426                 ,name || ' (clone of '||target_event_defs[i]||')'
3427                 ,hook
3428                 ,validator
3429                 ,reactor
3430                 ,cleanup_success
3431                 ,cleanup_failure
3432                 ,delay
3433                 ,max_delay
3434                 ,usr_field
3435                 ,opt_in_setting
3436                 ,delay_field
3437                 ,group_field
3438                 ,template
3439                 ,granularity
3440                 ,repeat_delay
3441             FROM
3442                 action_trigger.event_definition
3443             WHERE
3444                 id = target_event_defs[i]
3445             ;
3446             RAISE INFO 'created atevdef with id = %', currval('action_trigger.event_definition_id_seq');
3447             INSERT INTO new_atevdefs SELECT currval('action_trigger.event_definition_id_seq');
3448             INSERT INTO action_trigger.environment (
3449                 event_def
3450                 ,path
3451                 ,collector
3452                 ,label
3453             ) SELECT
3454                 currval('action_trigger.event_definition_id_seq')
3455                 ,path
3456                 ,collector
3457                 ,label
3458             FROM
3459                 action_trigger.environment
3460             WHERE
3461                 event_def = target_event_defs[i]
3462             ;
3463             INSERT INTO action_trigger.event_params (
3464                 event_def
3465                 ,param
3466                 ,value
3467             ) SELECT
3468                 currval('action_trigger.event_definition_id_seq')
3469                 ,param
3470                 ,value
3471             FROM
3472                 action_trigger.event_params
3473             WHERE
3474                 event_def = target_event_defs[i]
3475             ;
3476         END LOOP;
3477         RAISE INFO '-- UPDATE action_trigger.event_definition SET active = TRUE WHERE id in (%);', (SELECT array_to_string(array_agg(atevdef),',') from new_atevdefs);
3478     END;
3479 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3480
3481 CREATE OR REPLACE FUNCTION migration_tools.reset_event (BIGINT) RETURNS VOID AS $$
3482     UPDATE
3483         action_trigger.event
3484     SET
3485          start_time = NULL
3486         ,update_time = NULL
3487         ,complete_time = NULL
3488         ,update_process = NULL
3489         ,state = 'pending'
3490         ,template_output = NULL
3491         ,error_output = NULL
3492         ,async_output = NULL
3493     WHERE
3494         id = $1;
3495 $$ LANGUAGE SQL;
3496
3497 CREATE OR REPLACE FUNCTION migration_tools.get_marc_leader (TEXT) RETURNS TEXT AS $$
3498     my ($marcxml) = @_;
3499
3500     use MARC::Record;
3501     use MARC::File::XML;
3502     use MARC::Field;
3503
3504     my $field;
3505     eval {
3506         my $marc = MARC::Record->new_from_xml($marcxml, 'UTF-8');
3507         $field = $marc->leader();
3508     };
3509     return $field;
3510 $$ LANGUAGE PLPERLU STABLE;
3511
3512 CREATE OR REPLACE FUNCTION migration_tools.get_marc_tag (TEXT, TEXT, TEXT, TEXT) RETURNS TEXT AS $$
3513     my ($marcxml, $tag, $subfield, $delimiter) = @_;
3514
3515     use MARC::Record;
3516     use MARC::File::XML;
3517     use MARC::Field;
3518
3519     my $field;
3520     eval {
3521         my $marc = MARC::Record->new_from_xml($marcxml, 'UTF-8');
3522         $field = $marc->field($tag);
3523     };
3524     return $field->as_string($subfield,$delimiter);
3525 $$ LANGUAGE PLPERLU STABLE;
3526
3527 CREATE OR REPLACE FUNCTION migration_tools.get_marc_tags (TEXT, TEXT, TEXT, TEXT) RETURNS TEXT[] AS $$
3528     my ($marcxml, $tag, $subfield, $delimiter) = @_;
3529
3530     use MARC::Record;
3531     use MARC::File::XML;
3532     use MARC::Field;
3533
3534     my @fields;
3535     eval {
3536         my $marc = MARC::Record->new_from_xml($marcxml, 'UTF-8');
3537         @fields = $marc->field($tag);
3538     };
3539     my @texts;
3540     foreach my $field (@fields) {
3541         push @texts, $field->as_string($subfield,$delimiter);
3542     }
3543     return \@texts;
3544 $$ LANGUAGE PLPERLU STABLE;
3545
3546 CREATE OR REPLACE FUNCTION migration_tools.find_hold_matrix_matchpoint (INTEGER) RETURNS INTEGER AS $$
3547     SELECT action.find_hold_matrix_matchpoint(
3548         (SELECT pickup_lib FROM action.hold_request WHERE id = $1),
3549         (SELECT request_lib FROM action.hold_request WHERE id = $1),
3550         (SELECT current_copy FROM action.hold_request WHERE id = $1),
3551         (SELECT usr FROM action.hold_request WHERE id = $1),
3552         (SELECT requestor FROM action.hold_request WHERE id = $1)
3553     );
3554 $$ LANGUAGE SQL;
3555
3556 CREATE OR REPLACE FUNCTION migration_tools.find_hold_matrix_matchpoint2 (INTEGER) RETURNS SETOF action.matrix_test_result AS $$
3557     SELECT action.hold_request_permit_test(
3558         (SELECT pickup_lib FROM action.hold_request WHERE id = $1),
3559         (SELECT request_lib FROM action.hold_request WHERE id = $1),
3560         (SELECT current_copy FROM action.hold_request WHERE id = $1),
3561         (SELECT usr FROM action.hold_request WHERE id = $1),
3562         (SELECT requestor FROM action.hold_request WHERE id = $1)
3563     );
3564 $$ LANGUAGE SQL;
3565
3566 CREATE OR REPLACE FUNCTION migration_tools.find_circ_matrix_matchpoint (INTEGER) RETURNS SETOF action.found_circ_matrix_matchpoint AS $$
3567     SELECT action.find_circ_matrix_matchpoint(
3568         (SELECT circ_lib FROM action.circulation WHERE id = $1),
3569         (SELECT target_copy FROM action.circulation WHERE id = $1),
3570         (SELECT usr FROM action.circulation WHERE id = $1),
3571         (SELECT COALESCE(
3572                 NULLIF(phone_renewal,false),
3573                 NULLIF(desk_renewal,false),
3574                 NULLIF(opac_renewal,false),
3575                 false
3576             ) FROM action.circulation WHERE id = $1
3577         )
3578     );
3579 $$ LANGUAGE SQL;
3580
3581 CREATE OR REPLACE FUNCTION migration_tools.assert (BOOLEAN) RETURNS VOID AS $$
3582     DECLARE
3583         test ALIAS FOR $1;
3584     BEGIN
3585         IF NOT test THEN
3586             RAISE EXCEPTION 'assertion';
3587         END IF;
3588     END;
3589 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3590
3591 CREATE OR REPLACE FUNCTION migration_tools.assert (BOOLEAN,TEXT) RETURNS VOID AS $$
3592     DECLARE
3593         test ALIAS FOR $1;
3594         msg ALIAS FOR $2;
3595     BEGIN
3596         IF NOT test THEN
3597             RAISE EXCEPTION '%', msg;
3598         END IF;
3599     END;
3600 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3601
3602 CREATE OR REPLACE FUNCTION migration_tools.assert (BOOLEAN,TEXT,TEXT) RETURNS TEXT AS $$
3603     DECLARE
3604         test ALIAS FOR $1;
3605         fail_msg ALIAS FOR $2;
3606         success_msg ALIAS FOR $3;
3607     BEGIN
3608         IF NOT test THEN
3609             RAISE EXCEPTION '%', fail_msg;
3610         END IF;
3611         RETURN success_msg;
3612     END;
3613 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3614
3615 -- push bib sequence and return starting value for reserved range
3616 CREATE OR REPLACE FUNCTION migration_tools.push_bib_sequence(INTEGER) RETURNS BIGINT AS $$
3617     DECLARE
3618         bib_count ALIAS FOR $1;
3619         output BIGINT;
3620     BEGIN
3621         PERFORM setval('biblio.record_entry_id_seq',(SELECT MAX(id) FROM biblio.record_entry) + bib_count + 2000);
3622         FOR output IN
3623             SELECT CEIL(MAX(id)/1000)*1000+1000 FROM biblio.record_entry WHERE id < (SELECT last_value FROM biblio.record_entry_id_seq)
3624         LOOP
3625             RETURN output;
3626         END LOOP;
3627     END;
3628 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3629
3630 -- set a new salted password
3631
3632 CREATE OR REPLACE FUNCTION migration_tools.set_salted_passwd(INTEGER,TEXT) RETURNS BOOLEAN AS $$
3633     DECLARE
3634         usr_id              ALIAS FOR $1;
3635         plain_passwd        ALIAS FOR $2;
3636         plain_salt          TEXT;
3637         md5_passwd          TEXT;
3638     BEGIN
3639
3640         SELECT actor.create_salt('main') INTO plain_salt;
3641
3642         SELECT MD5(plain_passwd) INTO md5_passwd;
3643         
3644         PERFORM actor.set_passwd(usr_id, 'main', MD5(plain_salt || md5_passwd), plain_salt);
3645
3646         RETURN TRUE;
3647
3648     END;
3649 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3650
3651
3652 -- convenience functions for handling copy_location maps
3653
3654 CREATE OR REPLACE FUNCTION migration_tools.handle_shelf (TEXT,TEXT,TEXT,INTEGER) RETURNS VOID AS $$
3655     DECLARE
3656         table_schema ALIAS FOR $1;
3657         table_name ALIAS FOR $2;
3658         org_shortname ALIAS FOR $3;
3659         org_range ALIAS FOR $4;
3660         proceed BOOLEAN;
3661         org INTEGER;
3662         -- if x_org is on the mapping table, it'll take precedence over the passed org_shortname param
3663         -- though we'll still use the passed org for the full path traversal when needed
3664         x_org_found BOOLEAN;
3665         x_org INTEGER;
3666         org_list INTEGER[];
3667         o INTEGER;
3668     BEGIN
3669         EXECUTE 'SELECT EXISTS (
3670             SELECT 1
3671             FROM information_schema.columns
3672             WHERE table_schema = $1
3673             AND table_name = $2
3674             and column_name = ''desired_shelf''
3675         )' INTO proceed USING table_schema, table_name;
3676         IF NOT proceed THEN
3677             RAISE EXCEPTION 'Missing column desired_shelf';
3678         END IF;
3679
3680         EXECUTE 'SELECT EXISTS (
3681             SELECT 1
3682             FROM information_schema.columns
3683             WHERE table_schema = $1
3684             AND table_name = $2
3685             and column_name = ''x_org''
3686         )' INTO x_org_found USING table_schema, table_name;
3687
3688         SELECT id INTO org FROM actor.org_unit WHERE shortname = org_shortname;
3689         IF org IS NULL THEN
3690             RAISE EXCEPTION 'Cannot find org by shortname';
3691         END IF;
3692
3693         SELECT INTO org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( org );
3694
3695         EXECUTE 'ALTER TABLE '
3696             || quote_ident(table_name)
3697             || ' DROP COLUMN IF EXISTS x_shelf';
3698         EXECUTE 'ALTER TABLE '
3699             || quote_ident(table_name)
3700             || ' ADD COLUMN x_shelf INTEGER';
3701
3702         IF x_org_found THEN
3703             EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3704                 || ' SET x_shelf = b.id FROM asset_copy_location b'
3705                 || ' WHERE BTRIM(UPPER(a.desired_shelf)) = BTRIM(UPPER(b.name))'
3706                 || ' AND b.owning_lib = x_org'
3707                 || ' AND NOT b.deleted';
3708             EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3709                 || ' SET x_shelf = b.id FROM asset.copy_location b'
3710                 || ' WHERE BTRIM(UPPER(a.desired_shelf)) = BTRIM(UPPER(b.name))'
3711                 || ' AND b.owning_lib = x_org'
3712                 || ' AND x_shelf IS NULL'
3713                 || ' AND NOT b.deleted';
3714         ELSE
3715             EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3716                 || ' SET x_shelf = b.id FROM asset_copy_location b'
3717                 || ' WHERE BTRIM(UPPER(a.desired_shelf)) = BTRIM(UPPER(b.name))'
3718                 || ' AND b.owning_lib = $1'
3719                 || ' AND NOT b.deleted'
3720             USING org;
3721             EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3722                 || ' SET x_shelf = b.id FROM asset_copy_location b'
3723                 || ' WHERE BTRIM(UPPER(a.desired_shelf)) = BTRIM(UPPER(b.name))'
3724                 || ' AND b.owning_lib = $1'
3725                 || ' AND x_shelf IS NULL'
3726                 || ' AND NOT b.deleted'
3727             USING org;
3728         END IF;
3729
3730         FOREACH o IN ARRAY org_list LOOP
3731             EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3732                 || ' SET x_shelf = b.id FROM asset.copy_location b'
3733                 || ' WHERE BTRIM(UPPER(a.desired_shelf)) = BTRIM(UPPER(b.name))'
3734                 || ' AND b.owning_lib = $1 AND x_shelf IS NULL'
3735                 || ' AND NOT b.deleted'
3736             USING o;
3737         END LOOP;
3738
3739         EXECUTE 'SELECT migration_tools.assert(
3740             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE desired_shelf <> '''' AND x_shelf IS NULL),
3741             ''Cannot find a desired location'',
3742             ''Found all desired locations''
3743         );';
3744
3745     END;
3746 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3747
3748 -- convenience functions for handling circmod maps
3749
3750 CREATE OR REPLACE FUNCTION migration_tools.handle_circmod (TEXT,TEXT) RETURNS VOID AS $$
3751     DECLARE
3752         table_schema ALIAS FOR $1;
3753         table_name ALIAS FOR $2;
3754         proceed BOOLEAN;
3755     BEGIN
3756         EXECUTE 'SELECT EXISTS (
3757             SELECT 1
3758             FROM information_schema.columns
3759             WHERE table_schema = $1
3760             AND table_name = $2
3761             and column_name = ''desired_circmod''
3762         )' INTO proceed USING table_schema, table_name;
3763         IF NOT proceed THEN
3764             RAISE EXCEPTION 'Missing column desired_circmod'; 
3765         END IF;
3766
3767         EXECUTE 'ALTER TABLE '
3768             || quote_ident(table_name)
3769             || ' DROP COLUMN IF EXISTS x_circmod';
3770         EXECUTE 'ALTER TABLE '
3771             || quote_ident(table_name)
3772             || ' ADD COLUMN x_circmod TEXT';
3773
3774         EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3775             || ' SET x_circmod = code FROM config.circ_modifier b'
3776             || ' WHERE BTRIM(UPPER(a.desired_circmod)) = BTRIM(UPPER(b.code))';
3777
3778         EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3779             || ' SET x_circmod = code FROM config.circ_modifier b'
3780             || ' WHERE BTRIM(UPPER(a.desired_circmod)) = BTRIM(UPPER(b.name))'
3781             || ' AND x_circmod IS NULL';
3782
3783         EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3784             || ' SET x_circmod = code FROM config.circ_modifier b'
3785             || ' WHERE BTRIM(UPPER(a.desired_circmod)) = BTRIM(UPPER(b.description))'
3786             || ' AND x_circmod IS NULL';
3787
3788         EXECUTE 'SELECT migration_tools.assert(
3789             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE desired_circmod <> '''' AND x_circmod IS NULL),
3790             ''Cannot find a desired circulation modifier'',
3791             ''Found all desired circulation modifiers''
3792         );';
3793
3794     END;
3795 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3796
3797 -- convenience functions for handling item status maps
3798
3799 CREATE OR REPLACE FUNCTION migration_tools.handle_status (TEXT,TEXT) RETURNS VOID AS $$
3800     DECLARE
3801         table_schema ALIAS FOR $1;
3802         table_name ALIAS FOR $2;
3803         proceed BOOLEAN;
3804     BEGIN
3805         EXECUTE 'SELECT EXISTS (
3806             SELECT 1
3807             FROM information_schema.columns
3808             WHERE table_schema = $1
3809             AND table_name = $2
3810             and column_name = ''desired_status''
3811         )' INTO proceed USING table_schema, table_name;
3812         IF NOT proceed THEN
3813             RAISE EXCEPTION 'Missing column desired_status'; 
3814         END IF;
3815
3816         EXECUTE 'ALTER TABLE '
3817             || quote_ident(table_name)
3818             || ' DROP COLUMN IF EXISTS x_status';
3819         EXECUTE 'ALTER TABLE '
3820             || quote_ident(table_name)
3821             || ' ADD COLUMN x_status INTEGER';
3822
3823         EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3824             || ' SET x_status = id FROM config.copy_status b'
3825             || ' WHERE BTRIM(UPPER(a.desired_status)) = BTRIM(UPPER(b.name))';
3826
3827         EXECUTE 'SELECT migration_tools.assert(
3828             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE desired_status <> '''' AND x_status IS NULL),
3829             ''Cannot find a desired copy status'',
3830             ''Found all desired copy statuses''
3831         );';
3832
3833     END;
3834 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3835
3836 -- convenience functions for handling org maps
3837
3838 CREATE OR REPLACE FUNCTION migration_tools.handle_org (TEXT,TEXT) RETURNS VOID AS $$
3839     DECLARE
3840         table_schema ALIAS FOR $1;
3841         table_name ALIAS FOR $2;
3842         proceed BOOLEAN;
3843     BEGIN
3844         EXECUTE 'SELECT EXISTS (
3845             SELECT 1
3846             FROM information_schema.columns
3847             WHERE table_schema = $1
3848             AND table_name = $2
3849             and column_name = ''desired_org''
3850         )' INTO proceed USING table_schema, table_name;
3851         IF NOT proceed THEN
3852             RAISE EXCEPTION 'Missing column desired_org'; 
3853         END IF;
3854
3855         EXECUTE 'ALTER TABLE '
3856             || quote_ident(table_name)
3857             || ' DROP COLUMN IF EXISTS x_org';
3858         EXECUTE 'ALTER TABLE '
3859             || quote_ident(table_name)
3860             || ' ADD COLUMN x_org INTEGER';
3861
3862         EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3863             || ' SET x_org = b.id FROM actor.org_unit b'
3864             || ' WHERE BTRIM(a.desired_org) = BTRIM(b.shortname)';
3865
3866         EXECUTE 'SELECT migration_tools.assert(
3867             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE desired_org <> '''' AND x_org IS NULL),
3868             ''Cannot find a desired org unit'',
3869             ''Found all desired org units''
3870         );';
3871
3872     END;
3873 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3874
3875 -- convenience function for handling desired_not_migrate
3876
3877 CREATE OR REPLACE FUNCTION migration_tools.handle_not_migrate (TEXT,TEXT) RETURNS VOID AS $$
3878     DECLARE
3879         table_schema ALIAS FOR $1;
3880         table_name ALIAS FOR $2;
3881         proceed BOOLEAN;
3882     BEGIN
3883         EXECUTE 'SELECT EXISTS (
3884             SELECT 1
3885             FROM information_schema.columns
3886             WHERE table_schema = $1
3887             AND table_name = $2
3888             and column_name = ''desired_not_migrate''
3889         )' INTO proceed USING table_schema, table_name;
3890         IF NOT proceed THEN
3891             RAISE EXCEPTION 'Missing column desired_not_migrate'; 
3892         END IF;
3893
3894         EXECUTE 'ALTER TABLE '
3895             || quote_ident(table_name)
3896             || ' DROP COLUMN IF EXISTS x_migrate';
3897         EXECUTE 'ALTER TABLE '
3898             || quote_ident(table_name)
3899             || ' ADD COLUMN x_migrate BOOLEAN';
3900
3901         EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3902             || ' SET x_migrate = CASE'
3903             || ' WHEN BTRIM(desired_not_migrate) = ''TRUE'' THEN FALSE'
3904             || ' WHEN BTRIM(desired_not_migrate) = ''DNM'' THEN FALSE'
3905             || ' WHEN BTRIM(desired_not_migrate) = ''Do Not Migrate'' THEN FALSE'
3906             || ' WHEN BTRIM(desired_not_migrate) = ''FALSE'' THEN TRUE'
3907             || ' WHEN BTRIM(desired_not_migrate) = ''Migrate'' THEN TRUE'
3908             || ' WHEN BTRIM(desired_not_migrate) = '''' THEN TRUE'
3909             || ' END';
3910
3911         EXECUTE 'SELECT migration_tools.assert(
3912             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE x_migrate IS NULL),
3913             ''Not all desired_not_migrate values understood'',
3914             ''All desired_not_migrate values understood''
3915         );';
3916
3917     END;
3918 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3919
3920 -- convenience function for handling desired_not_migrate
3921
3922 CREATE OR REPLACE FUNCTION migration_tools.handle_barred_or_blocked (TEXT,TEXT) RETURNS VOID AS $$
3923     DECLARE
3924         table_schema ALIAS FOR $1;
3925         table_name ALIAS FOR $2;
3926         proceed BOOLEAN;
3927     BEGIN
3928         EXECUTE 'SELECT EXISTS (
3929             SELECT 1
3930             FROM information_schema.columns
3931             WHERE table_schema = $1
3932             AND table_name = $2
3933             and column_name = ''desired_barred_or_blocked''
3934         )' INTO proceed USING table_schema, table_name;
3935         IF NOT proceed THEN
3936             RAISE EXCEPTION 'Missing column desired_barred_or_blocked'; 
3937         END IF;
3938
3939         EXECUTE 'ALTER TABLE '
3940             || quote_ident(table_name)
3941             || ' DROP COLUMN IF EXISTS x_barred';
3942         EXECUTE 'ALTER TABLE '
3943             || quote_ident(table_name)
3944             || ' ADD COLUMN x_barred BOOLEAN';
3945
3946         EXECUTE 'ALTER TABLE '
3947             || quote_ident(table_name)
3948             || ' DROP COLUMN IF EXISTS x_blocked';
3949         EXECUTE 'ALTER TABLE '
3950             || quote_ident(table_name)
3951             || ' ADD COLUMN x_blocked BOOLEAN';
3952
3953         EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3954             || ' SET x_barred = CASE'
3955             || ' WHEN BTRIM(desired_barred_or_blocked) = ''Barred'' THEN TRUE'
3956             || ' WHEN BTRIM(desired_barred_or_blocked) = ''Blocked'' THEN FALSE'
3957             || ' WHEN BTRIM(desired_barred_or_blocked) = ''Neither'' THEN FALSE'
3958             || ' WHEN BTRIM(desired_barred_or_blocked) = '''' THEN FALSE'
3959             || ' END';
3960
3961         EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
3962             || ' SET x_blocked = CASE'
3963             || ' WHEN BTRIM(desired_barred_or_blocked) = ''Blocked'' THEN TRUE'
3964             || ' WHEN BTRIM(desired_barred_or_blocked) = ''Barred'' THEN FALSE'
3965             || ' WHEN BTRIM(desired_barred_or_blocked) = ''Neither'' THEN FALSE'
3966             || ' WHEN BTRIM(desired_barred_or_blocked) = '''' THEN FALSE'
3967             || ' END';
3968
3969         EXECUTE 'SELECT migration_tools.assert(
3970             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE x_barred IS NULL or x_blocked IS NULL),
3971             ''Not all desired_barred_or_blocked values understood'',
3972             ''All desired_barred_or_blocked values understood''
3973         );';
3974
3975     END;
3976 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
3977
3978 -- convenience function for handling desired_profile
3979
3980 CREATE OR REPLACE FUNCTION migration_tools.handle_profile (TEXT,TEXT) RETURNS VOID AS $$
3981     DECLARE
3982         table_schema ALIAS FOR $1;
3983         table_name ALIAS FOR $2;
3984         proceed BOOLEAN;
3985     BEGIN
3986         EXECUTE 'SELECT EXISTS (
3987             SELECT 1
3988             FROM information_schema.columns
3989             WHERE table_schema = $1
3990             AND table_name = $2
3991             and column_name = ''desired_profile''
3992         )' INTO proceed USING table_schema, table_name;
3993         IF NOT proceed THEN
3994             RAISE EXCEPTION 'Missing column desired_profile'; 
3995         END IF;
3996
3997         EXECUTE 'ALTER TABLE '
3998             || quote_ident(table_name)
3999             || ' DROP COLUMN IF EXISTS x_profile';
4000         EXECUTE 'ALTER TABLE '
4001             || quote_ident(table_name)
4002             || ' ADD COLUMN x_profile INTEGER';
4003
4004         EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
4005             || ' SET x_profile = b.id FROM permission.grp_tree b'
4006             || ' WHERE BTRIM(UPPER(a.desired_profile)) = BTRIM(UPPER(b.name))';
4007
4008         EXECUTE 'SELECT migration_tools.assert(
4009             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE desired_profile <> '''' AND x_profile IS NULL),
4010             ''Cannot find a desired profile'',
4011             ''Found all desired profiles''
4012         );';
4013
4014     END;
4015 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4016
4017 -- convenience function for handling desired actor stat cats
4018
4019 CREATE OR REPLACE FUNCTION migration_tools.vivicate_actor_sc_and_sce (TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
4020     DECLARE
4021         table_schema ALIAS FOR $1;
4022         table_name ALIAS FOR $2;
4023         field_suffix ALIAS FOR $3; -- for distinguishing between desired_sce1, desired_sce2, etc.
4024         org_shortname ALIAS FOR $4;
4025         proceed BOOLEAN;
4026         org INTEGER;
4027         org_list INTEGER[];
4028         sc TEXT;
4029         sce TEXT;
4030     BEGIN
4031
4032         SELECT 'desired_sc' || field_suffix INTO sc;
4033         SELECT 'desired_sce' || field_suffix INTO sce;
4034
4035         EXECUTE 'SELECT EXISTS (
4036             SELECT 1
4037             FROM information_schema.columns
4038             WHERE table_schema = $1
4039             AND table_name = $2
4040             and column_name = $3
4041         )' INTO proceed USING table_schema, table_name, sc;
4042         IF NOT proceed THEN
4043             RAISE EXCEPTION 'Missing column %', sc; 
4044         END IF;
4045         EXECUTE 'SELECT EXISTS (
4046             SELECT 1
4047             FROM information_schema.columns
4048             WHERE table_schema = $1
4049             AND table_name = $2
4050             and column_name = $3
4051         )' INTO proceed USING table_schema, table_name, sce;
4052         IF NOT proceed THEN
4053             RAISE EXCEPTION 'Missing column %', sce; 
4054         END IF;
4055
4056         SELECT id INTO org FROM actor.org_unit WHERE shortname = org_shortname;
4057         IF org IS NULL THEN
4058             RAISE EXCEPTION 'Cannot find org by shortname';
4059         END IF;
4060         SELECT INTO org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( org );
4061
4062         -- caller responsible for their own truncates though we try to prevent duplicates
4063         EXECUTE 'INSERT INTO actor_stat_cat (owner, name)
4064             SELECT DISTINCT
4065                  $1
4066                 ,BTRIM('||sc||')
4067             FROM 
4068                 ' || quote_ident(table_name) || '
4069             WHERE
4070                 NULLIF(BTRIM('||sc||'),'''') IS NOT NULL
4071                 AND NOT EXISTS (
4072                     SELECT id
4073                     FROM actor.stat_cat
4074                     WHERE owner = ANY ($2)
4075                     AND name = BTRIM('||sc||')
4076                 )
4077                 AND NOT EXISTS (
4078                     SELECT id
4079                     FROM actor_stat_cat
4080                     WHERE owner = ANY ($2)
4081                     AND name = BTRIM('||sc||')
4082                 )
4083             ORDER BY 2;'
4084         USING org, org_list;
4085
4086         EXECUTE 'INSERT INTO actor_stat_cat_entry (stat_cat, owner, value)
4087             SELECT DISTINCT
4088                 COALESCE(
4089                     (SELECT id
4090                         FROM actor.stat_cat
4091                         WHERE owner = ANY ($2)
4092                         AND BTRIM('||sc||') = BTRIM(name))
4093                    ,(SELECT id
4094                         FROM actor_stat_cat
4095                         WHERE owner = ANY ($2)
4096                         AND BTRIM('||sc||') = BTRIM(name))
4097                 )
4098                 ,$1
4099                 ,BTRIM('||sce||')
4100             FROM 
4101                 ' || quote_ident(table_name) || '
4102             WHERE
4103                     NULLIF(BTRIM('||sc||'),'''') IS NOT NULL
4104                 AND NULLIF(BTRIM('||sce||'),'''') IS NOT NULL
4105                 AND NOT EXISTS (
4106                     SELECT id
4107                     FROM actor.stat_cat_entry
4108                     WHERE stat_cat = (
4109                         SELECT id
4110                         FROM actor.stat_cat
4111                         WHERE owner = ANY ($2)
4112                         AND BTRIM('||sc||') = BTRIM(name)
4113                     ) AND value = BTRIM('||sce||')
4114                     AND owner = ANY ($2)
4115                 )
4116                 AND NOT EXISTS (
4117                     SELECT id
4118                     FROM actor_stat_cat_entry
4119                     WHERE stat_cat = (
4120                         SELECT id
4121                         FROM actor_stat_cat
4122                         WHERE owner = ANY ($2)
4123                         AND BTRIM('||sc||') = BTRIM(name)
4124                     ) AND value = BTRIM('||sce||')
4125                     AND owner = ANY ($2)
4126                 )
4127             ORDER BY 1,3;'
4128         USING org, org_list;
4129     END;
4130 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4131
4132 CREATE OR REPLACE FUNCTION migration_tools.handle_actor_sc_and_sce (TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
4133     DECLARE
4134         table_schema ALIAS FOR $1;
4135         table_name ALIAS FOR $2;
4136         field_suffix ALIAS FOR $3; -- for distinguishing between desired_sce1, desired_sce2, etc.
4137         org_shortname ALIAS FOR $4;
4138         proceed BOOLEAN;
4139         org INTEGER;
4140         org_list INTEGER[];
4141         o INTEGER;
4142         sc TEXT;
4143         sce TEXT;
4144     BEGIN
4145         SELECT 'desired_sc' || field_suffix INTO sc;
4146         SELECT 'desired_sce' || field_suffix INTO sce;
4147         EXECUTE 'SELECT EXISTS (
4148             SELECT 1
4149             FROM information_schema.columns
4150             WHERE table_schema = $1
4151             AND table_name = $2
4152             and column_name = $3
4153         )' INTO proceed USING table_schema, table_name, sc;
4154         IF NOT proceed THEN
4155             RAISE EXCEPTION 'Missing column %', sc; 
4156         END IF;
4157         EXECUTE 'SELECT EXISTS (
4158             SELECT 1
4159             FROM information_schema.columns
4160             WHERE table_schema = $1
4161             AND table_name = $2
4162             and column_name = $3
4163         )' INTO proceed USING table_schema, table_name, sce;
4164         IF NOT proceed THEN
4165             RAISE EXCEPTION 'Missing column %', sce; 
4166         END IF;
4167
4168         SELECT id INTO org FROM actor.org_unit WHERE shortname = org_shortname;
4169         IF org IS NULL THEN
4170             RAISE EXCEPTION 'Cannot find org by shortname';
4171         END IF;
4172
4173         SELECT INTO org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( org );
4174
4175         EXECUTE 'ALTER TABLE '
4176             || quote_ident(table_name)
4177             || ' DROP COLUMN IF EXISTS x_sc' || field_suffix;
4178         EXECUTE 'ALTER TABLE '
4179             || quote_ident(table_name)
4180             || ' ADD COLUMN x_sc' || field_suffix || ' INTEGER';
4181         EXECUTE 'ALTER TABLE '
4182             || quote_ident(table_name)
4183             || ' DROP COLUMN IF EXISTS x_sce' || field_suffix;
4184         EXECUTE 'ALTER TABLE '
4185             || quote_ident(table_name)
4186             || ' ADD COLUMN x_sce' || field_suffix || ' INTEGER';
4187
4188
4189         EXECUTE 'UPDATE ' || quote_ident(table_name) || '
4190             SET
4191                 x_sc' || field_suffix || ' = id
4192             FROM
4193                 (SELECT id, name, owner FROM actor_stat_cat
4194                     UNION SELECT id, name, owner FROM actor.stat_cat) u
4195             WHERE
4196                     BTRIM(UPPER(u.name)) = BTRIM(UPPER(' || sc || '))
4197                 AND u.owner = ANY ($1);'
4198         USING org_list;
4199
4200         EXECUTE 'UPDATE ' || quote_ident(table_name) || '
4201             SET
4202                 x_sce' || field_suffix || ' = id
4203             FROM
4204                 (SELECT id, stat_cat, owner, value FROM actor_stat_cat_entry
4205                     UNION SELECT id, stat_cat, owner, value FROM actor.stat_cat_entry) u
4206             WHERE
4207                     u.stat_cat = x_sc' || field_suffix || '
4208                 AND BTRIM(UPPER(u.value)) = BTRIM(UPPER(' || sce || '))
4209                 AND u.owner = ANY ($1);'
4210         USING org_list;
4211
4212         EXECUTE 'SELECT migration_tools.assert(
4213             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE desired_sc' || field_suffix || ' <> '''' AND x_sc' || field_suffix || ' IS NULL),
4214             ''Cannot find a desired stat cat'',
4215             ''Found all desired stat cats''
4216         );';
4217
4218         EXECUTE 'SELECT migration_tools.assert(
4219             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE desired_sce' || field_suffix || ' <> '''' AND x_sce' || field_suffix || ' IS NULL),
4220             ''Cannot find a desired stat cat entry'',
4221             ''Found all desired stat cat entries''
4222         );';
4223
4224     END;
4225 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4226
4227 -- convenience functions for adding shelving locations
4228 DROP FUNCTION IF EXISTS migration_tools.find_shelf(INT,TEXT);
4229 CREATE OR REPLACE FUNCTION migration_tools.find_shelf(org_id INT, shelf_name TEXT) RETURNS INTEGER AS $$
4230 DECLARE
4231     return_id   INT;
4232     d           INT;
4233     cur_id      INT;
4234 BEGIN
4235     SELECT INTO d MAX(distance) FROM actor.org_unit_ancestors_distance(org_id);
4236     WHILE d >= 0
4237     LOOP
4238         SELECT INTO cur_id id FROM actor.org_unit_ancestor_at_depth(org_id,d);
4239         SELECT INTO return_id id FROM asset.copy_location WHERE owning_lib = cur_id AND name ILIKE shelf_name;
4240         IF return_id IS NOT NULL THEN
4241                 RETURN return_id;
4242         END IF;
4243         d := d - 1;
4244     END LOOP;
4245
4246     RETURN NULL;
4247 END
4248 $$ LANGUAGE plpgsql;
4249
4250 -- may remove later but testing using this with new migration scripts and not loading acls until go live
4251
4252 DROP FUNCTION IF EXISTS migration_tools.find_mig_shelf(INT,TEXT);
4253 CREATE OR REPLACE FUNCTION migration_tools.find_mig_shelf(org_id INT, shelf_name TEXT) RETURNS INTEGER AS $$
4254 DECLARE
4255     return_id   INT;
4256     d           INT;
4257     cur_id      INT;
4258 BEGIN
4259     SELECT INTO d MAX(distance) FROM actor.org_unit_ancestors_distance(org_id);
4260     WHILE d >= 0
4261     LOOP
4262         SELECT INTO cur_id id FROM actor.org_unit_ancestor_at_depth(org_id,d);
4263         
4264         SELECT INTO return_id id FROM 
4265             (SELECT * FROM asset.copy_location UNION ALL SELECT * FROM asset_copy_location) x
4266             WHERE owning_lib = cur_id AND name ILIKE shelf_name;
4267         IF return_id IS NOT NULL THEN
4268                 RETURN return_id;
4269         END IF;
4270         d := d - 1;
4271     END LOOP;
4272
4273     RETURN NULL;
4274 END
4275 $$ LANGUAGE plpgsql;
4276
4277 DROP FUNCTION IF EXISTS migration_tools.munge_sf9(INTEGER,TEXT,TEXT);
4278 CREATE OR REPLACE FUNCTION migration_tools.merge_group(bib_id INTEGER,new_sf9 TEXT,force TEXT DEFAULT 'false')
4279     RETURNS BOOLEAN AS 
4280 $BODY$
4281 DECLARE
4282         marc_xml        TEXT;
4283         new_marc        TEXT;
4284 BEGIN
4285         SELECT marc FROM biblio.record_entry WHERE id = bib_id INTO marc_xml;
4286         
4287         SELECT munge_sf9(marc_xml,new_sf9,force) INTO new_marc;
4288         UPDATE biblio.record_entry SET marc = new_marc WHERE id = bib_id;
4289         
4290         RETURN true;
4291 END;
4292 $BODY$ LANGUAGE plpgsql;
4293
4294 DROP FUNCTION IF EXISTS migration_tools.munge_sf9(TEXT,TEXT,TEXT);
4295 CREATE OR REPLACE FUNCTION migration_tools.munge_sf9(marc_xml TEXT, new_9_to_set TEXT, force TEXT)
4296  RETURNS TEXT
4297  LANGUAGE plperlu
4298 AS $function$
4299 use strict;
4300 use warnings;
4301
4302 use MARC::Record;
4303 use MARC::File::XML (BinaryEncoding => 'utf8');
4304
4305 binmode(STDERR, ':bytes');
4306 binmode(STDOUT, ':utf8');
4307 binmode(STDERR, ':utf8');
4308
4309 my $marc_xml = shift;
4310 my $new_9_to_set = shift;
4311 my $force = shift;
4312
4313 $marc_xml =~ s/(<leader>.........)./${1}a/;
4314
4315 eval {
4316     $marc_xml = MARC::Record->new_from_xml($marc_xml);
4317 };
4318 if ($@) {
4319     #elog("could not parse $bibid: $@\n");
4320     import MARC::File::XML (BinaryEncoding => 'utf8');
4321     return $marc_xml;
4322 }
4323
4324 my @uris = $marc_xml->field('856');
4325 return $marc_xml->as_xml_record() unless @uris;
4326
4327 foreach my $field (@uris) {
4328     my $ind1 = $field->indicator('1');
4329     if (!defined $ind1) { next; }
4330     if ($ind1 ne '1' && $ind1 ne '4' && $force eq 'false') { next; }
4331         if ($ind1 ne '1' && $ind1 ne '4' && $force eq 'true') { $field->set_indicator(1,'4'); }
4332     my $ind2 = $field->indicator('2');
4333     if (!defined $ind2) { next; }
4334     if ($ind2 ne '0' && $ind2 ne '1' && $force eq 'false') { next; }
4335     if ($ind2 ne '0' && $ind2 ne '1' && $force eq 'true') { $field->set_indicator(2,'0'); }
4336     $field->add_subfields( '9' => $new_9_to_set );
4337 }
4338
4339 return $marc_xml->as_xml_record();
4340
4341 $function$;
4342
4343 -- strip marc tag
4344 DROP FUNCTION IF EXISTS migration_tools.strip_tag(TEXT,TEXT);
4345 CREATE OR REPLACE FUNCTION migration_tools.strip_tag(marc TEXT, tag TEXT)
4346  RETURNS TEXT
4347  LANGUAGE plperlu
4348 AS $function$
4349 use strict;
4350 use warnings;
4351
4352 use MARC::Record;
4353 use MARC::File::XML (BinaryEncoding => 'utf8');
4354
4355 binmode(STDERR, ':bytes');
4356 binmode(STDOUT, ':utf8');
4357 binmode(STDERR, ':utf8');
4358
4359 my $marc_xml = shift;
4360 my $tag = shift;
4361
4362 $marc_xml =~ s/(<leader>.........)./${1}a/;
4363
4364 eval {
4365     $marc_xml = MARC::Record->new_from_xml($marc_xml);
4366 };
4367 if ($@) {
4368     #elog("could not parse $bibid: $@\n");
4369     import MARC::File::XML (BinaryEncoding => 'utf8');
4370     return $marc_xml;
4371 }
4372
4373 my @fields = $marc_xml->field($tag);
4374 return $marc_xml->as_xml_record() unless @fields;
4375
4376 $marc_xml->delete_fields(@fields);
4377
4378 return $marc_xml->as_xml_record();
4379
4380 $function$;
4381
4382 -- convenience function for linking to the item staging table
4383
4384 CREATE OR REPLACE FUNCTION migration_tools.handle_item_barcode (TEXT,TEXT,TEXT,TEXT,BOOLEAN) RETURNS VOID AS $$
4385     DECLARE
4386         table_schema ALIAS FOR $1;
4387         table_name ALIAS FOR $2;
4388         foreign_column_name ALIAS FOR $3;
4389         main_column_name ALIAS FOR $4;
4390         btrim_desired ALIAS FOR $5;
4391         proceed BOOLEAN;
4392     BEGIN
4393         EXECUTE 'SELECT EXISTS (
4394             SELECT 1
4395             FROM information_schema.columns
4396             WHERE table_schema = $1
4397             AND table_name = $2
4398             and column_name = $3
4399         )' INTO proceed USING table_schema, table_name, foreign_column_name;
4400         IF NOT proceed THEN
4401             RAISE EXCEPTION '%.% missing column %', table_schema, table_name, foreign_column_name; 
4402         END IF;
4403
4404         EXECUTE 'SELECT EXISTS (
4405             SELECT 1
4406             FROM information_schema.columns
4407             WHERE table_schema = $1
4408             AND table_name = ''asset_copy_legacy''
4409             and column_name = $2
4410         )' INTO proceed USING table_schema, main_column_name;
4411         IF NOT proceed THEN
4412             RAISE EXCEPTION 'No %.asset_copy_legacy with column %', table_schema, main_column_name; 
4413         END IF;
4414
4415         EXECUTE 'ALTER TABLE '
4416             || quote_ident(table_name)
4417             || ' DROP COLUMN IF EXISTS x_item';
4418         EXECUTE 'ALTER TABLE '
4419             || quote_ident(table_name)
4420             || ' ADD COLUMN x_item BIGINT';
4421
4422         IF btrim_desired THEN
4423             EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
4424                 || ' SET x_item = b.id FROM asset_copy_legacy b'
4425                 || ' WHERE BTRIM(a.' || quote_ident(foreign_column_name)
4426                 || ') = BTRIM(b.' || quote_ident(main_column_name) || ')';
4427         ELSE
4428             EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
4429                 || ' SET x_item = b.id FROM asset_copy_legacy b'
4430                 || ' WHERE a.' || quote_ident(foreign_column_name)
4431                 || ' = b.' || quote_ident(main_column_name);
4432         END IF;
4433
4434         --EXECUTE 'SELECT migration_tools.assert(
4435         --    NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE ' || quote_ident(foreign_column_name) || ' <> '''' AND x_item IS NULL),
4436         --    ''Cannot link every barcode'',
4437         --    ''Every barcode linked''
4438         --);';
4439
4440     END;
4441 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4442
4443 -- convenience function for linking to the user staging table
4444
4445 CREATE OR REPLACE FUNCTION migration_tools.handle_user_barcode (TEXT,TEXT,TEXT,TEXT,BOOLEAN) RETURNS VOID AS $$
4446     DECLARE
4447         table_schema ALIAS FOR $1;
4448         table_name ALIAS FOR $2;
4449         foreign_column_name ALIAS FOR $3;
4450         main_column_name ALIAS FOR $4;
4451         btrim_desired ALIAS FOR $5;
4452         proceed BOOLEAN;
4453     BEGIN
4454         EXECUTE 'SELECT EXISTS (
4455             SELECT 1
4456             FROM information_schema.columns
4457             WHERE table_schema = $1
4458             AND table_name = $2
4459             and column_name = $3
4460         )' INTO proceed USING table_schema, table_name, foreign_column_name;
4461         IF NOT proceed THEN
4462             RAISE EXCEPTION '%.% missing column %', table_schema, table_name, foreign_column_name; 
4463         END IF;
4464
4465         EXECUTE 'SELECT EXISTS (
4466             SELECT 1
4467             FROM information_schema.columns
4468             WHERE table_schema = $1
4469             AND table_name = ''actor_usr_legacy''
4470             and column_name = $2
4471         )' INTO proceed USING table_schema, main_column_name;
4472         IF NOT proceed THEN
4473             RAISE EXCEPTION 'No %.actor_usr_legacy with column %', table_schema, main_column_name; 
4474         END IF;
4475
4476         EXECUTE 'ALTER TABLE '
4477             || quote_ident(table_name)
4478             || ' DROP COLUMN IF EXISTS x_user';
4479         EXECUTE 'ALTER TABLE '
4480             || quote_ident(table_name)
4481             || ' ADD COLUMN x_user INTEGER';
4482
4483         IF btrim_desired THEN
4484             EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
4485                 || ' SET x_user = b.id FROM actor_usr_legacy b'
4486                 || ' WHERE BTRIM(a.' || quote_ident(foreign_column_name)
4487                 || ') = BTRIM(b.' || quote_ident(main_column_name) || ')';
4488         ELSE
4489             EXECUTE 'UPDATE ' || quote_ident(table_name) || ' a'
4490                 || ' SET x_user = b.id FROM actor_usr_legacy b'
4491                 || ' WHERE a.' || quote_ident(foreign_column_name)
4492                 || ' = b.' || quote_ident(main_column_name);
4493         END IF;
4494
4495         --EXECUTE 'SELECT migration_tools.assert(
4496         --    NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE ' || quote_ident(foreign_column_name) || ' <> '''' AND x_user IS NULL),
4497         --    ''Cannot link every barcode'',
4498         --    ''Every barcode linked''
4499         --);';
4500
4501     END;
4502 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4503
4504 -- convenience function for linking two tables
4505 -- e.g. select migration_tools.handle_link(:'migschema','asset_copy','barcode','test_foo','l_barcode','x_acp_id',false);
4506 CREATE OR REPLACE FUNCTION migration_tools.handle_link (TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,BOOLEAN) RETURNS VOID AS $$
4507     DECLARE
4508         table_schema ALIAS FOR $1;
4509         table_a ALIAS FOR $2;
4510         column_a ALIAS FOR $3;
4511         table_b ALIAS FOR $4;
4512         column_b ALIAS FOR $5;
4513         column_x ALIAS FOR $6;
4514         btrim_desired ALIAS FOR $7;
4515         proceed BOOLEAN;
4516     BEGIN
4517         EXECUTE 'SELECT EXISTS (
4518             SELECT 1
4519             FROM information_schema.columns
4520             WHERE table_schema = $1
4521             AND table_name = $2
4522             and column_name = $3
4523         )' INTO proceed USING table_schema, table_a, column_a;
4524         IF NOT proceed THEN
4525             RAISE EXCEPTION '%.% missing column %', table_schema, table_a, column_a; 
4526         END IF;
4527
4528         EXECUTE 'SELECT EXISTS (
4529             SELECT 1
4530             FROM information_schema.columns
4531             WHERE table_schema = $1
4532             AND table_name = $2
4533             and column_name = $3
4534         )' INTO proceed USING table_schema, table_b, column_b;
4535         IF NOT proceed THEN
4536             RAISE EXCEPTION '%.% missing column %', table_schema, table_b, column_b; 
4537         END IF;
4538
4539         EXECUTE 'ALTER TABLE '
4540             || quote_ident(table_b)
4541             || ' DROP COLUMN IF EXISTS ' || quote_ident(column_x);
4542         EXECUTE 'ALTER TABLE '
4543             || quote_ident(table_b)
4544             || ' ADD COLUMN ' || quote_ident(column_x) || ' BIGINT';
4545
4546         IF btrim_desired THEN
4547             EXECUTE 'UPDATE ' || quote_ident(table_b) || ' b'
4548                 || ' SET ' || quote_ident(column_x) || ' = a.id FROM ' || quote_ident(table_a) || ' a'
4549                 || ' WHERE BTRIM(a.' || quote_ident(column_a)
4550                 || ') = BTRIM(b.' || quote_ident(column_b) || ')';
4551         ELSE
4552             EXECUTE 'UPDATE ' || quote_ident(table_b) || ' b'
4553                 || ' SET ' || quote_ident(column_x) || ' = a.id FROM ' || quote_ident(table_a) || ' a'
4554                 || ' WHERE a.' || quote_ident(column_a)
4555                 || ' = b.' || quote_ident(column_b);
4556         END IF;
4557
4558     END;
4559 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4560
4561 -- convenience function for linking two tables, but copying column w into column x instead of "id"
4562 -- e.g. select migration_tools.handle_link2(:'migschema','asset_copy','barcode','test_foo','l_barcode','id','x_acp_id',false);
4563 CREATE OR REPLACE FUNCTION migration_tools.handle_link2 (TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,BOOLEAN) RETURNS VOID AS $$
4564     DECLARE
4565         table_schema ALIAS FOR $1;
4566         table_a ALIAS FOR $2;
4567         column_a ALIAS FOR $3;
4568         table_b ALIAS FOR $4;
4569         column_b ALIAS FOR $5;
4570         column_w ALIAS FOR $6;
4571         column_x ALIAS FOR $7;
4572         btrim_desired ALIAS FOR $8;
4573         proceed BOOLEAN;
4574     BEGIN
4575         EXECUTE 'SELECT EXISTS (
4576             SELECT 1
4577             FROM information_schema.columns
4578             WHERE table_schema = $1
4579             AND table_name = $2
4580             and column_name = $3
4581         )' INTO proceed USING table_schema, table_a, column_a;
4582         IF NOT proceed THEN
4583             RAISE EXCEPTION '%.% missing column %', table_schema, table_a, column_a; 
4584         END IF;
4585
4586         EXECUTE 'SELECT EXISTS (
4587             SELECT 1
4588             FROM information_schema.columns
4589             WHERE table_schema = $1
4590             AND table_name = $2
4591             and column_name = $3
4592         )' INTO proceed USING table_schema, table_b, column_b;
4593         IF NOT proceed THEN
4594             RAISE EXCEPTION '%.% missing column %', table_schema, table_b, column_b; 
4595         END IF;
4596
4597         EXECUTE 'ALTER TABLE '
4598             || quote_ident(table_b)
4599             || ' DROP COLUMN IF EXISTS ' || quote_ident(column_x);
4600         EXECUTE 'ALTER TABLE '
4601             || quote_ident(table_b)
4602             || ' ADD COLUMN ' || quote_ident(column_x) || ' TEXT';
4603
4604         IF btrim_desired THEN
4605             EXECUTE 'UPDATE ' || quote_ident(table_b) || ' b'
4606                 || ' SET ' || quote_ident(column_x) || ' = a.' || quote_ident(column_w) || ' FROM ' || quote_ident(table_a) || ' a'
4607                 || ' WHERE BTRIM(a.' || quote_ident(column_a)
4608                 || ') = BTRIM(b.' || quote_ident(column_b) || ')';
4609         ELSE
4610             EXECUTE 'UPDATE ' || quote_ident(table_b) || ' b'
4611                 || ' SET ' || quote_ident(column_x) || ' = a.' || quote_ident(column_w) || ' FROM ' || quote_ident(table_a) || ' a'
4612                 || ' WHERE a.' || quote_ident(column_a)
4613                 || ' = b.' || quote_ident(column_b);
4614         END IF;
4615
4616     END;
4617 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4618
4619 -- convenience function for linking two tables, but copying column w into column x instead of "id". Unlike handle_link2, this one won't drop the target column, and it also doesn't have a final boolean argument for btrim
4620 -- e.g. select migration_tools.handle_link3(:'migschema','asset_copy','barcode','test_foo','l_barcode','id','x_acp_id');
4621 CREATE OR REPLACE FUNCTION migration_tools.handle_link3 (TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
4622     DECLARE
4623         table_schema ALIAS FOR $1;
4624         table_a ALIAS FOR $2;
4625         column_a ALIAS FOR $3;
4626         table_b ALIAS FOR $4;
4627         column_b ALIAS FOR $5;
4628         column_w ALIAS FOR $6;
4629         column_x ALIAS FOR $7;
4630         proceed BOOLEAN;
4631     BEGIN
4632         EXECUTE 'SELECT EXISTS (
4633             SELECT 1
4634             FROM information_schema.columns
4635             WHERE table_schema = $1
4636             AND table_name = $2
4637             and column_name = $3
4638         )' INTO proceed USING table_schema, table_a, column_a;
4639         IF NOT proceed THEN
4640             RAISE EXCEPTION '%.% missing column %', table_schema, table_a, column_a; 
4641         END IF;
4642
4643         EXECUTE 'SELECT EXISTS (
4644             SELECT 1
4645             FROM information_schema.columns
4646             WHERE table_schema = $1
4647             AND table_name = $2
4648             and column_name = $3
4649         )' INTO proceed USING table_schema, table_b, column_b;
4650         IF NOT proceed THEN
4651             RAISE EXCEPTION '%.% missing column %', table_schema, table_b, column_b; 
4652         END IF;
4653
4654         EXECUTE 'UPDATE ' || quote_ident(table_b) || ' b'
4655             || ' SET ' || quote_ident(column_x) || ' = a.' || quote_ident(column_w) || ' FROM ' || quote_ident(table_a) || ' a'
4656             || ' WHERE a.' || quote_ident(column_a)
4657             || ' = b.' || quote_ident(column_b);
4658
4659     END;
4660 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4661
4662 CREATE OR REPLACE FUNCTION migration_tools.handle_link3_skip_null_or_empty_string (TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
4663     DECLARE
4664         table_schema ALIAS FOR $1;
4665         table_a ALIAS FOR $2;
4666         column_a ALIAS FOR $3;
4667         table_b ALIAS FOR $4;
4668         column_b ALIAS FOR $5;
4669         column_w ALIAS FOR $6;
4670         column_x ALIAS FOR $7;
4671         proceed BOOLEAN;
4672     BEGIN
4673         EXECUTE 'SELECT EXISTS (
4674             SELECT 1
4675             FROM information_schema.columns
4676             WHERE table_schema = $1
4677             AND table_name = $2
4678             and column_name = $3
4679         )' INTO proceed USING table_schema, table_a, column_a;
4680         IF NOT proceed THEN
4681             RAISE EXCEPTION '%.% missing column %', table_schema, table_a, column_a; 
4682         END IF;
4683
4684         EXECUTE 'SELECT EXISTS (
4685             SELECT 1
4686             FROM information_schema.columns
4687             WHERE table_schema = $1
4688             AND table_name = $2
4689             and column_name = $3
4690         )' INTO proceed USING table_schema, table_b, column_b;
4691         IF NOT proceed THEN
4692             RAISE EXCEPTION '%.% missing column %', table_schema, table_b, column_b; 
4693         END IF;
4694
4695         EXECUTE 'UPDATE ' || quote_ident(table_b) || ' b'
4696             || ' SET ' || quote_ident(column_x) || ' = a.' || quote_ident(column_w) || ' FROM ' || quote_ident(table_a) || ' a'
4697             || ' WHERE a.' || quote_ident(column_a)
4698             || ' = b.' || quote_ident(column_b)
4699             || ' AND NULLIF(a.' || quote_ident(column_w) || ','''') IS NOT NULL';
4700
4701     END;
4702 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4703
4704 CREATE OR REPLACE FUNCTION migration_tools.handle_link3_skip_null (TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
4705     DECLARE
4706         table_schema ALIAS FOR $1;
4707         table_a ALIAS FOR $2;
4708         column_a ALIAS FOR $3;
4709         table_b ALIAS FOR $4;
4710         column_b ALIAS FOR $5;
4711         column_w ALIAS FOR $6;
4712         column_x ALIAS FOR $7;
4713         proceed BOOLEAN;
4714     BEGIN
4715         EXECUTE 'SELECT EXISTS (
4716             SELECT 1
4717             FROM information_schema.columns
4718             WHERE table_schema = $1
4719             AND table_name = $2
4720             and column_name = $3
4721         )' INTO proceed USING table_schema, table_a, column_a;
4722         IF NOT proceed THEN
4723             RAISE EXCEPTION '%.% missing column %', table_schema, table_a, column_a; 
4724         END IF;
4725
4726         EXECUTE 'SELECT EXISTS (
4727             SELECT 1
4728             FROM information_schema.columns
4729             WHERE table_schema = $1
4730             AND table_name = $2
4731             and column_name = $3
4732         )' INTO proceed USING table_schema, table_b, column_b;
4733         IF NOT proceed THEN
4734             RAISE EXCEPTION '%.% missing column %', table_schema, table_b, column_b; 
4735         END IF;
4736
4737         EXECUTE 'UPDATE ' || quote_ident(table_b) || ' b'
4738             || ' SET ' || quote_ident(column_x) || ' = a.' || quote_ident(column_w) || ' FROM ' || quote_ident(table_a) || ' a'
4739             || ' WHERE a.' || quote_ident(column_a)
4740             || ' = b.' || quote_ident(column_b)
4741             || ' AND a.' || quote_ident(column_w) || ' IS NOT NULL';
4742
4743     END;
4744 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4745
4746 CREATE OR REPLACE FUNCTION migration_tools.handle_link3_skip_true (TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
4747     DECLARE
4748         table_schema ALIAS FOR $1;
4749         table_a ALIAS FOR $2;
4750         column_a ALIAS FOR $3;
4751         table_b ALIAS FOR $4;
4752         column_b ALIAS FOR $5;
4753         column_w ALIAS FOR $6;
4754         column_x ALIAS FOR $7;
4755         proceed BOOLEAN;
4756     BEGIN
4757         EXECUTE 'SELECT EXISTS (
4758             SELECT 1
4759             FROM information_schema.columns
4760             WHERE table_schema = $1
4761             AND table_name = $2
4762             and column_name = $3
4763         )' INTO proceed USING table_schema, table_a, column_a;
4764         IF NOT proceed THEN
4765             RAISE EXCEPTION '%.% missing column %', table_schema, table_a, column_a; 
4766         END IF;
4767
4768         EXECUTE 'SELECT EXISTS (
4769             SELECT 1
4770             FROM information_schema.columns
4771             WHERE table_schema = $1
4772             AND table_name = $2
4773             and column_name = $3
4774         )' INTO proceed USING table_schema, table_b, column_b;
4775         IF NOT proceed THEN
4776             RAISE EXCEPTION '%.% missing column %', table_schema, table_b, column_b; 
4777         END IF;
4778
4779         EXECUTE 'UPDATE ' || quote_ident(table_b) || ' b'
4780             || ' SET ' || quote_ident(column_x) || ' = a.' || quote_ident(column_w) || ' FROM ' || quote_ident(table_a) || ' a'
4781             || ' WHERE a.' || quote_ident(column_a)
4782             || ' = b.' || quote_ident(column_b)
4783             || ' AND a.' || quote_ident(column_w) || ' IS NOT TRUE';
4784
4785     END;
4786 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4787
4788 CREATE OR REPLACE FUNCTION migration_tools.handle_link3_skip_false (TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
4789     DECLARE
4790         table_schema ALIAS FOR $1;
4791         table_a ALIAS FOR $2;
4792         column_a ALIAS FOR $3;
4793         table_b ALIAS FOR $4;
4794         column_b ALIAS FOR $5;
4795         column_w ALIAS FOR $6;
4796         column_x ALIAS FOR $7;
4797         proceed BOOLEAN;
4798     BEGIN
4799         EXECUTE 'SELECT EXISTS (
4800             SELECT 1
4801             FROM information_schema.columns
4802             WHERE table_schema = $1
4803             AND table_name = $2
4804             and column_name = $3
4805         )' INTO proceed USING table_schema, table_a, column_a;
4806         IF NOT proceed THEN
4807             RAISE EXCEPTION '%.% missing column %', table_schema, table_a, column_a; 
4808         END IF;
4809
4810         EXECUTE 'SELECT EXISTS (
4811             SELECT 1
4812             FROM information_schema.columns
4813             WHERE table_schema = $1
4814             AND table_name = $2
4815             and column_name = $3
4816         )' INTO proceed USING table_schema, table_b, column_b;
4817         IF NOT proceed THEN
4818             RAISE EXCEPTION '%.% missing column %', table_schema, table_b, column_b; 
4819         END IF;
4820
4821         EXECUTE 'UPDATE ' || quote_ident(table_b) || ' b'
4822             || ' SET ' || quote_ident(column_x) || ' = a.' || quote_ident(column_w) || ' FROM ' || quote_ident(table_a) || ' a'
4823             || ' WHERE a.' || quote_ident(column_a)
4824             || ' = b.' || quote_ident(column_b)
4825             || ' AND a.' || quote_ident(column_w) || ' IS NOT FALSE';
4826
4827     END;
4828 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4829
4830 CREATE OR REPLACE FUNCTION migration_tools.handle_link3_concat_skip_null (TEXT,TEXT,TEXT,TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
4831     DECLARE
4832         table_schema ALIAS FOR $1;
4833         table_a ALIAS FOR $2;
4834         column_a ALIAS FOR $3;
4835         table_b ALIAS FOR $4;
4836         column_b ALIAS FOR $5;
4837         column_w ALIAS FOR $6;
4838         column_x ALIAS FOR $7;
4839         proceed BOOLEAN;
4840     BEGIN
4841         EXECUTE 'SELECT EXISTS (
4842             SELECT 1
4843             FROM information_schema.columns
4844             WHERE table_schema = $1
4845             AND table_name = $2
4846             and column_name = $3
4847         )' INTO proceed USING table_schema, table_a, column_a;
4848         IF NOT proceed THEN
4849             RAISE EXCEPTION '%.% missing column %', table_schema, table_a, column_a; 
4850         END IF;
4851
4852         EXECUTE 'SELECT EXISTS (
4853             SELECT 1
4854             FROM information_schema.columns
4855             WHERE table_schema = $1
4856             AND table_name = $2
4857             and column_name = $3
4858         )' INTO proceed USING table_schema, table_b, column_b;
4859         IF NOT proceed THEN
4860             RAISE EXCEPTION '%.% missing column %', table_schema, table_b, column_b; 
4861         END IF;
4862
4863         EXECUTE 'UPDATE ' || quote_ident(table_b) || ' b'
4864             || ' SET ' || quote_ident(column_x) || ' = CONCAT_WS('' ; '',b.' || quote_ident(column_x) || ',a.' || quote_ident(column_w) || ') FROM ' || quote_ident(table_a) || ' a'
4865             || ' WHERE a.' || quote_ident(column_a)
4866             || ' = b.' || quote_ident(column_b)
4867             || ' AND NULLIF(a.' || quote_ident(column_w) || ','''') IS NOT NULL';
4868
4869     END;
4870 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4871
4872 -- convenience function for handling desired asset stat cats
4873
4874 CREATE OR REPLACE FUNCTION migration_tools.vivicate_asset_sc_and_sce (TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
4875     DECLARE
4876         table_schema ALIAS FOR $1;
4877         table_name ALIAS FOR $2;
4878         field_suffix ALIAS FOR $3; -- for distinguishing between desired_sce1, desired_sce2, etc.
4879         org_shortname ALIAS FOR $4;
4880         proceed BOOLEAN;
4881         org INTEGER;
4882         org_list INTEGER[];
4883         sc TEXT;
4884         sce TEXT;
4885     BEGIN
4886
4887         SELECT 'desired_sc' || field_suffix INTO sc;
4888         SELECT 'desired_sce' || field_suffix INTO sce;
4889
4890         EXECUTE 'SELECT EXISTS (
4891             SELECT 1
4892             FROM information_schema.columns
4893             WHERE table_schema = $1
4894             AND table_name = $2
4895             and column_name = $3
4896         )' INTO proceed USING table_schema, table_name, sc;
4897         IF NOT proceed THEN
4898             RAISE EXCEPTION 'Missing column %', sc; 
4899         END IF;
4900         EXECUTE 'SELECT EXISTS (
4901             SELECT 1
4902             FROM information_schema.columns
4903             WHERE table_schema = $1
4904             AND table_name = $2
4905             and column_name = $3
4906         )' INTO proceed USING table_schema, table_name, sce;
4907         IF NOT proceed THEN
4908             RAISE EXCEPTION 'Missing column %', sce; 
4909         END IF;
4910
4911         SELECT id INTO org FROM actor.org_unit WHERE shortname = org_shortname;
4912         IF org IS NULL THEN
4913             RAISE EXCEPTION 'Cannot find org by shortname';
4914         END IF;
4915         SELECT INTO org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( org );
4916
4917         -- caller responsible for their own truncates though we try to prevent duplicates
4918         EXECUTE 'INSERT INTO asset_stat_cat (owner, name)
4919             SELECT DISTINCT
4920                  $1
4921                 ,BTRIM('||sc||')
4922             FROM 
4923                 ' || quote_ident(table_name) || '
4924             WHERE
4925                 NULLIF(BTRIM('||sc||'),'''') IS NOT NULL
4926                 AND NOT EXISTS (
4927                     SELECT id
4928                     FROM asset.stat_cat
4929                     WHERE owner = ANY ($2)
4930                     AND name = BTRIM('||sc||')
4931                 )
4932                 AND NOT EXISTS (
4933                     SELECT id
4934                     FROM asset_stat_cat
4935                     WHERE owner = ANY ($2)
4936                     AND name = BTRIM('||sc||')
4937                 )
4938             ORDER BY 2;'
4939         USING org, org_list;
4940
4941         EXECUTE 'INSERT INTO asset_stat_cat_entry (stat_cat, owner, value)
4942             SELECT DISTINCT
4943                 COALESCE(
4944                     (SELECT id
4945                         FROM asset.stat_cat
4946                         WHERE owner = ANY ($2)
4947                         AND BTRIM('||sc||') = BTRIM(name))
4948                    ,(SELECT id
4949                         FROM asset_stat_cat
4950                         WHERE owner = ANY ($2)
4951                         AND BTRIM('||sc||') = BTRIM(name))
4952                 )
4953                 ,$1
4954                 ,BTRIM('||sce||')
4955             FROM 
4956                 ' || quote_ident(table_name) || '
4957             WHERE
4958                     NULLIF(BTRIM('||sc||'),'''') IS NOT NULL
4959                 AND NULLIF(BTRIM('||sce||'),'''') IS NOT NULL
4960                 AND NOT EXISTS (
4961                     SELECT id
4962                     FROM asset.stat_cat_entry
4963                     WHERE stat_cat = (
4964                         SELECT id
4965                         FROM asset.stat_cat
4966                         WHERE owner = ANY ($2)
4967                         AND BTRIM('||sc||') = BTRIM(name)
4968                     ) AND value = BTRIM('||sce||')
4969                     AND owner = ANY ($2)
4970                 )
4971                 AND NOT EXISTS (
4972                     SELECT id
4973                     FROM asset_stat_cat_entry
4974                     WHERE stat_cat = (
4975                         SELECT id
4976                         FROM asset_stat_cat
4977                         WHERE owner = ANY ($2)
4978                         AND BTRIM('||sc||') = BTRIM(name)
4979                     ) AND value = BTRIM('||sce||')
4980                     AND owner = ANY ($2)
4981                 )
4982             ORDER BY 1,3;'
4983         USING org, org_list;
4984     END;
4985 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
4986
4987 CREATE OR REPLACE FUNCTION migration_tools.handle_asset_sc_and_sce (TEXT,TEXT,TEXT,TEXT) RETURNS VOID AS $$
4988     DECLARE
4989         table_schema ALIAS FOR $1;
4990         table_name ALIAS FOR $2;
4991         field_suffix ALIAS FOR $3; -- for distinguishing between desired_sce1, desired_sce2, etc.
4992         org_shortname ALIAS FOR $4;
4993         proceed BOOLEAN;
4994         org INTEGER;
4995         org_list INTEGER[];
4996         o INTEGER;
4997         sc TEXT;
4998         sce TEXT;
4999     BEGIN
5000         SELECT 'desired_sc' || field_suffix INTO sc;
5001         SELECT 'desired_sce' || field_suffix INTO sce;
5002         EXECUTE 'SELECT EXISTS (
5003             SELECT 1
5004             FROM information_schema.columns
5005             WHERE table_schema = $1
5006             AND table_name = $2
5007             and column_name = $3
5008         )' INTO proceed USING table_schema, table_name, sc;
5009         IF NOT proceed THEN
5010             RAISE EXCEPTION 'Missing column %', sc; 
5011         END IF;
5012         EXECUTE 'SELECT EXISTS (
5013             SELECT 1
5014             FROM information_schema.columns
5015             WHERE table_schema = $1
5016             AND table_name = $2
5017             and column_name = $3
5018         )' INTO proceed USING table_schema, table_name, sce;
5019         IF NOT proceed THEN
5020             RAISE EXCEPTION 'Missing column %', sce; 
5021         END IF;
5022
5023         SELECT id INTO org FROM actor.org_unit WHERE shortname = org_shortname;
5024         IF org IS NULL THEN
5025             RAISE EXCEPTION 'Cannot find org by shortname';
5026         END IF;
5027
5028         SELECT INTO org_list ARRAY_ACCUM(id) FROM actor.org_unit_full_path( org );
5029
5030         EXECUTE 'ALTER TABLE '
5031             || quote_ident(table_name)
5032             || ' DROP COLUMN IF EXISTS x_sc' || field_suffix;
5033         EXECUTE 'ALTER TABLE '
5034             || quote_ident(table_name)
5035             || ' ADD COLUMN x_sc' || field_suffix || ' INTEGER';
5036         EXECUTE 'ALTER TABLE '
5037             || quote_ident(table_name)
5038             || ' DROP COLUMN IF EXISTS x_sce' || field_suffix;
5039         EXECUTE 'ALTER TABLE '
5040             || quote_ident(table_name)
5041             || ' ADD COLUMN x_sce' || field_suffix || ' INTEGER';
5042
5043
5044         EXECUTE 'UPDATE ' || quote_ident(table_name) || '
5045             SET
5046                 x_sc' || field_suffix || ' = id
5047             FROM
5048                 (SELECT id, name, owner FROM asset_stat_cat
5049                     UNION SELECT id, name, owner FROM asset.stat_cat) u
5050             WHERE
5051                     BTRIM(UPPER(u.name)) = BTRIM(UPPER(' || sc || '))
5052                 AND u.owner = ANY ($1);'
5053         USING org_list;
5054
5055         EXECUTE 'UPDATE ' || quote_ident(table_name) || '
5056             SET
5057                 x_sce' || field_suffix || ' = id
5058             FROM
5059                 (SELECT id, stat_cat, owner, value FROM asset_stat_cat_entry
5060                     UNION SELECT id, stat_cat, owner, value FROM asset.stat_cat_entry) u
5061             WHERE
5062                     u.stat_cat = x_sc' || field_suffix || '
5063                 AND BTRIM(UPPER(u.value)) = BTRIM(UPPER(' || sce || '))
5064                 AND u.owner = ANY ($1);'
5065         USING org_list;
5066
5067         EXECUTE 'SELECT migration_tools.assert(
5068             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE desired_sc' || field_suffix || ' <> '''' AND x_sc' || field_suffix || ' IS NULL),
5069             ''Cannot find a desired stat cat'',
5070             ''Found all desired stat cats''
5071         );';
5072
5073         EXECUTE 'SELECT migration_tools.assert(
5074             NOT EXISTS (SELECT 1 FROM ' || quote_ident(table_name) || ' WHERE desired_sce' || field_suffix || ' <> '''' AND x_sce' || field_suffix || ' IS NULL),
5075             ''Cannot find a desired stat cat entry'',
5076             ''Found all desired stat cat entries''
5077         );';
5078
5079     END;
5080 $$ LANGUAGE PLPGSQL STRICT VOLATILE;
5081
5082 DROP FUNCTION IF EXISTS migration_tools.btrim_lcolumns(TEXT,TEXT);
5083 CREATE OR REPLACE FUNCTION migration_tools.btrim_lcolumns(s_name TEXT, t_name TEXT) RETURNS BOOLEAN
5084  LANGUAGE plpgsql
5085 AS $function$
5086 DECLARE
5087     c_name     TEXT;
5088 BEGIN
5089
5090     FOR c_name IN SELECT column_name FROM information_schema.columns WHERE 
5091             table_name = t_name
5092             AND table_schema = s_name
5093             AND (data_type='text' OR data_type='character varying')
5094             AND column_name like 'l_%'
5095     LOOP
5096        EXECUTE FORMAT('UPDATE ' || s_name || '.' || t_name || ' SET ' || c_name || ' = BTRIM(' || c_name || ')'); 
5097     END LOOP;  
5098
5099     RETURN TRUE;
5100 END
5101 $function$;
5102
5103 DROP FUNCTION IF EXISTS migration_tools.btrim_columns(TEXT,TEXT);
5104 CREATE OR REPLACE FUNCTION migration_tools.btrim_columns(s_name TEXT, t_name TEXT) RETURNS BOOLEAN
5105  LANGUAGE plpgsql
5106 AS $function$
5107 DECLARE
5108     c_name     TEXT;
5109 BEGIN
5110
5111     FOR c_name IN SELECT column_name FROM information_schema.columns WHERE 
5112             table_name = t_name
5113             AND table_schema = s_name
5114             AND (data_type='text' OR data_type='character varying')
5115     LOOP
5116        EXECUTE FORMAT('UPDATE ' || s_name || '.' || t_name || ' SET ' || c_name || ' = BTRIM(' || c_name || ')'); 
5117     END LOOP;  
5118
5119     RETURN TRUE;
5120 END
5121 $function$;
5122
5123 DROP FUNCTION IF EXISTS migration_tools.null_empty_lcolumns(TEXT,TEXT);
5124 CREATE OR REPLACE FUNCTION migration_tools.null_empty_lcolumns(s_name TEXT, t_name TEXT) RETURNS BOOLEAN
5125  LANGUAGE plpgsql
5126 AS $function$
5127 DECLARE
5128     c_name     TEXT;
5129 BEGIN
5130
5131     FOR c_name IN SELECT column_name FROM information_schema.columns WHERE 
5132             table_name = t_name
5133             AND table_schema = s_name
5134             AND (data_type='text' OR data_type='character varying')
5135             AND column_name like 'l_%'
5136     LOOP
5137        EXECUTE FORMAT('UPDATE ' || s_name || '.' || t_name || ' SET ' || c_name || ' = NULL WHERE ' || c_name || ' = '''' '); 
5138     END LOOP;  
5139
5140     RETURN TRUE;
5141 END
5142 $function$;
5143
5144 DROP FUNCTION IF EXISTS migration_tools.null_empty_columns(TEXT,TEXT);
5145 CREATE OR REPLACE FUNCTION migration_tools.null_empty_columns(s_name TEXT, t_name TEXT) RETURNS BOOLEAN
5146  LANGUAGE plpgsql
5147 AS $function$
5148 DECLARE
5149     c_name     TEXT;
5150 BEGIN
5151
5152     FOR c_name IN SELECT column_name FROM information_schema.columns WHERE
5153             table_name = t_name
5154             AND table_schema = s_name
5155             AND (data_type='text' OR data_type='character varying')
5156     LOOP
5157        EXECUTE FORMAT('UPDATE ' || s_name || '.' || t_name || ' SET ' || c_name || ' = NULL WHERE ' || c_name || ' = '''' ');
5158     END LOOP;
5159
5160     RETURN TRUE;
5161 END
5162 $function$;
5163