]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/012.schema.vandelay.sql
LP#1322285: Exclude default values for fixed fields when ingesting
[working/Evergreen.git] / Open-ILS / src / sql / Pg / 012.schema.vandelay.sql
1 DROP SCHEMA IF EXISTS vandelay CASCADE;
2
3 BEGIN;
4
5 CREATE SCHEMA vandelay;
6
7 CREATE TABLE vandelay.match_set (
8     id      SERIAL  PRIMARY KEY,
9     name    TEXT        NOT NULL,
10     owner   INT     NOT NULL REFERENCES actor.org_unit (id) ON DELETE CASCADE,
11     mtype   TEXT        NOT NULL DEFAULT 'biblio', -- 'biblio','authority','mfhd'?, others?
12     CONSTRAINT name_once_per_owner_mtype UNIQUE (name, owner, mtype)
13 );
14
15 -- Table to define match points, either FF via SVF or tag+subfield
16 CREATE TABLE vandelay.match_set_point (
17     id          SERIAL  PRIMARY KEY,
18     match_set   INT     REFERENCES vandelay.match_set (id) ON DELETE CASCADE,
19     parent      INT     REFERENCES vandelay.match_set_point (id),
20     bool_op     TEXT    CHECK (bool_op IS NULL OR (bool_op IN ('AND','OR','NOT'))),
21     svf         TEXT    REFERENCES config.record_attr_definition (name),
22     tag         TEXT,
23     subfield    TEXT,
24     negate      BOOL    DEFAULT FALSE,
25     quality     INT     NOT NULL DEFAULT 1, -- higher is better
26     CONSTRAINT vmsp_need_a_subfield_with_a_tag CHECK ((tag IS NOT NULL AND subfield IS NOT NULL) OR tag IS NULL),
27     CONSTRAINT vmsp_need_a_tag_or_a_ff_or_a_bo CHECK (
28         (tag IS NOT NULL AND svf IS NULL AND bool_op IS NULL) OR
29         (tag IS NULL AND svf IS NOT NULL AND bool_op IS NULL) OR
30         (tag IS NULL AND svf IS NULL AND bool_op IS NOT NULL)
31     )
32 );
33
34 CREATE TABLE vandelay.match_set_quality (
35     id          SERIAL  PRIMARY KEY,
36     match_set   INT     NOT NULL REFERENCES vandelay.match_set (id) ON DELETE CASCADE,
37     svf         TEXT    REFERENCES config.record_attr_definition,
38     tag         TEXT,
39     subfield    TEXT,
40     value       TEXT    NOT NULL,
41     quality     INT     NOT NULL DEFAULT 1, -- higher is better
42     CONSTRAINT vmsq_need_a_subfield_with_a_tag CHECK ((tag IS NOT NULL AND subfield IS NOT NULL) OR tag IS NULL),
43     CONSTRAINT vmsq_need_a_tag_or_a_ff CHECK ((tag IS NOT NULL AND svf IS NULL) OR (tag IS NULL AND svf IS NOT NULL))
44 );
45 CREATE UNIQUE INDEX vmsq_def_once_per_set ON vandelay.match_set_quality (match_set, COALESCE(tag,''), COALESCE(subfield,''), COALESCE(svf,''), value);
46
47
48 CREATE TABLE vandelay.queue (
49         id                              BIGSERIAL       PRIMARY KEY,
50         owner                   INT                     NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
51         name                    TEXT            NOT NULL,
52         complete                BOOL            NOT NULL DEFAULT FALSE,
53     match_set       INT         REFERENCES vandelay.match_set (id) ON UPDATE CASCADE ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED
54 );
55
56 CREATE TABLE vandelay.queued_record (
57     id                  BIGSERIAL                   PRIMARY KEY,
58     create_time TIMESTAMP WITH TIME ZONE    NOT NULL DEFAULT NOW(),
59     import_time TIMESTAMP WITH TIME ZONE,
60         purpose         TEXT                                            NOT NULL DEFAULT 'import' CHECK (purpose IN ('import','overlay')),
61     marc                TEXT                        NOT NULL,
62     quality     INT                         NOT NULL DEFAULT 0
63 );
64
65
66
67 /* Bib stuff at the top */
68 ----------------------------------------------------
69
70 CREATE TABLE vandelay.bib_attr_definition (
71         id                      SERIAL  PRIMARY KEY,
72         code            TEXT    UNIQUE NOT NULL,
73         description     TEXT,
74         xpath           TEXT    NOT NULL,
75         remove          TEXT    NOT NULL DEFAULT ''
76 );
77
78 -- Each TEXT field (other than 'name') should hold an XPath predicate for pulling the data needed
79 -- DROP TABLE vandelay.import_item_attr_definition CASCADE;
80 CREATE TABLE vandelay.import_item_attr_definition (
81     id              BIGSERIAL   PRIMARY KEY,
82     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
83     name            TEXT        NOT NULL,
84     tag             TEXT        NOT NULL,
85     keep            BOOL        NOT NULL DEFAULT FALSE,
86     owning_lib      TEXT,
87     circ_lib        TEXT,
88     call_number     TEXT,
89     copy_number     TEXT,
90     status          TEXT,
91     location        TEXT,
92     circulate       TEXT,
93     deposit         TEXT,
94     deposit_amount  TEXT,
95     ref             TEXT,
96     holdable        TEXT,
97     price           TEXT,
98     barcode         TEXT,
99     circ_modifier   TEXT,
100     circ_as_type    TEXT,
101     alert_message   TEXT,
102     opac_visible    TEXT,
103     pub_note_title  TEXT,
104     pub_note        TEXT,
105     priv_note_title TEXT,
106     priv_note       TEXT,
107     internal_id     TEXT,
108         CONSTRAINT vand_import_item_attr_def_idx UNIQUE (owner,name)
109 );
110
111 CREATE TABLE vandelay.import_error (
112     code        TEXT    PRIMARY KEY,
113     description TEXT    NOT NULL -- i18n
114 );
115
116 CREATE TYPE vandelay.bib_queue_queue_type AS ENUM ('bib', 'acq');
117
118 CREATE TABLE vandelay.bib_queue (
119         queue_type          vandelay.bib_queue_queue_type       NOT NULL DEFAULT 'bib',
120         item_attr_def   BIGINT REFERENCES vandelay.import_item_attr_definition (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
121     match_bucket    INTEGER, -- REFERENCES container.biblio_record_entry_bucket(id);
122         CONSTRAINT vand_bib_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
123 ) INHERITS (vandelay.queue);
124 ALTER TABLE vandelay.bib_queue ADD PRIMARY KEY (id);
125
126 CREATE TABLE vandelay.queued_bib_record (
127         queue               INT         NOT NULL REFERENCES vandelay.bib_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
128         bib_source          INT         REFERENCES config.bib_source (id) DEFERRABLE INITIALLY DEFERRED,
129         imported_as     BIGINT  REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
130         import_error    TEXT    REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
131         error_detail    TEXT
132 ) INHERITS (vandelay.queued_record);
133 ALTER TABLE vandelay.queued_bib_record ADD PRIMARY KEY (id);
134 CREATE INDEX queued_bib_record_queue_idx ON vandelay.queued_bib_record (queue);
135
136 CREATE TABLE vandelay.queued_bib_record_attr (
137         id                      BIGSERIAL       PRIMARY KEY,
138         record          BIGINT          NOT NULL REFERENCES vandelay.queued_bib_record (id) DEFERRABLE INITIALLY DEFERRED,
139         field           INT                     NOT NULL REFERENCES vandelay.bib_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
140         attr_value      TEXT            NOT NULL
141 );
142 CREATE INDEX queued_bib_record_attr_record_idx ON vandelay.queued_bib_record_attr (record);
143
144 CREATE TABLE vandelay.bib_match (
145         id                              BIGSERIAL       PRIMARY KEY,
146         queued_record   BIGINT          REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
147         eg_record               BIGINT          REFERENCES biblio.record_entry (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
148     quality         INT         NOT NULL DEFAULT 1,
149     match_score     INT         NOT NULL DEFAULT 0
150 );
151
152 CREATE TABLE vandelay.import_item (
153     id              BIGSERIAL   PRIMARY KEY,
154     record          BIGINT      NOT NULL REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
155     definition      BIGINT      NOT NULL REFERENCES vandelay.import_item_attr_definition (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
156         import_error    TEXT        REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
157         error_detail    TEXT,
158     imported_as     BIGINT,
159     import_time     TIMESTAMP WITH TIME ZONE,
160     owning_lib      INT,
161     circ_lib        INT,
162     call_number     TEXT,
163     copy_number     INT,
164     status          INT,
165     location        INT,
166     circulate       BOOL,
167     deposit         BOOL,
168     deposit_amount  NUMERIC(8,2),
169     ref             BOOL,
170     holdable        BOOL,
171     price           NUMERIC(8,2),
172     barcode         TEXT,
173     circ_modifier   TEXT,
174     circ_as_type    TEXT,
175     alert_message   TEXT,
176     pub_note        TEXT,
177     priv_note       TEXT,
178     opac_visible    BOOL,
179     internal_id     BIGINT -- queue_type == 'acq' ? acq.lineitem_detail.id : asset.copy.id
180 );
181
182 CREATE TABLE vandelay.import_bib_trash_group(
183     id           SERIAL  PRIMARY KEY,
184     owner        INTEGER NOT NULL REFERENCES actor.org_unit(id),
185     label        TEXT    NOT NULL, --i18n
186     always_apply BOOLEAN NOT NULL DEFAULT FALSE,
187         CONSTRAINT vand_import_bib_trash_grp_owner_label UNIQUE (owner, label)
188 );
189  
190 CREATE TABLE vandelay.import_bib_trash_fields (
191     id         BIGSERIAL PRIMARY KEY,
192     grp        INTEGER   NOT NULL REFERENCES vandelay.import_bib_trash_group,
193     field      TEXT      NOT NULL,
194     CONSTRAINT vand_import_bib_trash_fields_once_per UNIQUE (grp, field)
195 );
196
197 CREATE TABLE vandelay.merge_profile (
198     id              BIGSERIAL   PRIMARY KEY,
199     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
200     name            TEXT        NOT NULL,
201     add_spec        TEXT,
202     replace_spec    TEXT,
203     strip_spec      TEXT,
204     preserve_spec   TEXT,
205     lwm_ratio       NUMERIC,
206         CONSTRAINT vand_merge_prof_owner_name_idx UNIQUE (owner,name),
207         CONSTRAINT add_replace_strip_or_preserve CHECK ((preserve_spec IS NOT NULL OR replace_spec IS NOT NULL) OR (preserve_spec IS NULL AND replace_spec IS NULL))
208 );
209
210 CREATE OR REPLACE FUNCTION vandelay.marc21_record_type( marc TEXT ) RETURNS config.marc21_rec_type_map AS $func$
211 DECLARE
212         ldr         TEXT;
213         tval        TEXT;
214         tval_rec    RECORD;
215         bval        TEXT;
216         bval_rec    RECORD;
217     retval      config.marc21_rec_type_map%ROWTYPE;
218 BEGIN
219     ldr := oils_xpath_string( '//*[local-name()="leader"]', marc );
220
221     IF ldr IS NULL OR ldr = '' THEN
222         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
223         RETURN retval;
224     END IF;
225
226     SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
227     SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
228
229
230     tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
231     bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
232
233     -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
234
235     SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
236
237
238     IF retval.code IS NULL THEN
239         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
240     END IF;
241
242     RETURN retval;
243 END;
244 $func$ LANGUAGE PLPGSQL;
245
246 CREATE TYPE biblio.record_ff_map AS (record BIGINT, ff_name TEXT, ff_value TEXT);
247 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_all_fixed_fields( marc TEXT, use_default BOOL DEFAULT FALSE ) RETURNS SETOF biblio.record_ff_map AS $func$
248 DECLARE
249     tag_data    TEXT;
250     rtype       TEXT;
251     ff_pos      RECORD;
252     output      biblio.record_ff_map%ROWTYPE;
253 BEGIN
254     rtype := (vandelay.marc21_record_type( marc )).code;
255
256     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE rec_type = rtype ORDER BY tag DESC LOOP
257         output.ff_name  := ff_pos.fixed_field;
258         output.ff_value := NULL;
259
260         IF ff_pos.tag = 'ldr' THEN
261             output.ff_value := oils_xpath_string('//*[local-name()="leader"]', marc);
262             IF output.ff_value IS NOT NULL THEN
263                 output.ff_value := SUBSTRING( output.ff_value, ff_pos.start_pos + 1, ff_pos.length );
264                 RETURN NEXT output;
265                 output.ff_value := NULL;
266             END IF;
267         ELSE
268             FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
269                 output.ff_value := SUBSTRING( tag_data, ff_pos.start_pos + 1, ff_pos.length );
270                 CONTINUE WHEN output.ff_value IS NULL AND NOT use_default;
271                 IF output.ff_value IS NULL THEN output.ff_value := REPEAT( ff_pos.default_val, ff_pos.length ); END IF;
272                 RETURN NEXT output;
273                 output.ff_value := NULL;
274             END LOOP;
275         END IF;
276
277     END LOOP;
278
279     RETURN;
280 END;
281 $func$ LANGUAGE PLPGSQL;
282
283 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field_list( marc TEXT, ff TEXT, use_default BOOL DEFAULT FALSE ) RETURNS TEXT[] AS $func$
284 DECLARE
285     rtype       TEXT;
286     ff_pos      RECORD;
287     tag_data    RECORD;
288     val         TEXT;
289     collection  TEXT[] := '{}'::TEXT[];
290 BEGIN
291     rtype := (vandelay.marc21_record_type( marc )).code;
292     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
293         IF ff_pos.tag = 'ldr' THEN
294             val := oils_xpath_string('//*[local-name()="leader"]', marc);
295             IF val IS NOT NULL THEN
296                 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
297                 collection := collection || val;
298             END IF;
299         ELSE
300             FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
301                 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
302                 collection := collection || val;
303             END LOOP;
304         END IF;
305         CONTINUE WHEN NOT use_default;
306         CONTINUE WHEN ARRAY_UPPER(collection, 1) > 0;
307         val := REPEAT( ff_pos.default_val, ff_pos.length );
308         collection := collection || val;
309     END LOOP;
310
311     RETURN collection;
312 END;
313 $func$ LANGUAGE PLPGSQL;
314
315 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field( marc TEXT, ff TEXT, use_default BOOL DEFAULT FALSE ) RETURNS TEXT AS $func$
316 DECLARE
317     rtype       TEXT;
318     ff_pos      RECORD;
319     tag_data    RECORD;
320     val         TEXT;
321 BEGIN
322     rtype := (vandelay.marc21_record_type( marc )).code;
323     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
324         IF ff_pos.tag = 'ldr' THEN
325             val := oils_xpath_string('//*[local-name()="leader"]', marc);
326             IF val IS NOT NULL THEN
327                 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
328                 RETURN val;
329             END IF;
330         ELSE
331             FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
332                 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
333                 RETURN val;
334             END LOOP;
335         END IF;
336         CONTINUE WHEN NOT use_default;
337         val := REPEAT( ff_pos.default_val, ff_pos.length );
338         RETURN val;
339     END LOOP;
340
341     RETURN NULL;
342 END;
343 $func$ LANGUAGE PLPGSQL;
344
345 CREATE TYPE biblio.marc21_physical_characteristics AS ( id INT, record BIGINT, ptype TEXT, subfield INT, value INT );
346 CREATE OR REPLACE FUNCTION vandelay.marc21_physical_characteristics( marc TEXT) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
347 DECLARE
348     rowid   INT := 0;
349     _007    TEXT;
350     ptype   config.marc21_physical_characteristic_type_map%ROWTYPE;
351     psf     config.marc21_physical_characteristic_subfield_map%ROWTYPE;
352     pval    config.marc21_physical_characteristic_value_map%ROWTYPE;
353     retval  biblio.marc21_physical_characteristics%ROWTYPE;
354 BEGIN
355
356     FOR _007 IN SELECT oils_xpath_string('//*', value) FROM UNNEST(oils_xpath('//*[@tag="007"]', marc)) x(value) LOOP
357         IF _007 IS NOT NULL AND _007 <> '' THEN
358             SELECT * INTO ptype FROM config.marc21_physical_characteristic_type_map WHERE ptype_key = SUBSTRING( _007, 1, 1 );
359
360             IF ptype.ptype_key IS NOT NULL THEN
361                 FOR psf IN SELECT * FROM config.marc21_physical_characteristic_subfield_map WHERE ptype_key = ptype.ptype_key LOOP
362                     SELECT * INTO pval FROM config.marc21_physical_characteristic_value_map WHERE ptype_subfield = psf.id AND value = SUBSTRING( _007, psf.start_pos + 1, psf.length );
363
364                     IF pval.id IS NOT NULL THEN
365                         rowid := rowid + 1;
366                         retval.id := rowid;
367                         retval.ptype := ptype.ptype_key;
368                         retval.subfield := psf.id;
369                         retval.value := pval.id;
370                         RETURN NEXT retval;
371                     END IF;
372
373                 END LOOP;
374             END IF;
375         END IF;
376     END LOOP;
377
378     RETURN;
379 END;
380 $func$ LANGUAGE PLPGSQL;
381
382 CREATE TYPE vandelay.flat_marc AS ( tag CHAR(3), ind1 TEXT, ind2 TEXT, subfield TEXT, value TEXT );
383 CREATE OR REPLACE FUNCTION vandelay.flay_marc ( TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
384
385 use MARC::Record;
386 use MARC::File::XML (BinaryEncoding => 'UTF-8');
387 use MARC::Charset;
388 use strict;
389
390 MARC::Charset->assume_unicode(1);
391
392 my $xml = shift;
393 my $r = MARC::Record->new_from_xml( $xml );
394
395 return_next( { tag => 'LDR', value => $r->leader } );
396
397 for my $f ( $r->fields ) {
398     if ($f->is_control_field) {
399         return_next({ tag => $f->tag, value => $f->data });
400     } else {
401         for my $s ($f->subfields) {
402             return_next({
403                 tag      => $f->tag,
404                 ind1     => $f->indicator(1),
405                 ind2     => $f->indicator(2),
406                 subfield => $s->[0],
407                 value    => $s->[1]
408             });
409
410             if ( $f->tag eq '245' and $s->[0] eq 'a' ) {
411                 my $trim = $f->indicator(2) || 0;
412                 return_next({
413                     tag      => 'tnf',
414                     ind1     => $f->indicator(1),
415                     ind2     => $f->indicator(2),
416                     subfield => 'a',
417                     value    => substr( $s->[1], $trim )
418                 });
419             }
420         }
421     }
422 }
423
424 return undef;
425
426 $func$ LANGUAGE PLPERLU;
427
428 CREATE OR REPLACE FUNCTION vandelay.flatten_marc ( marc TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
429 DECLARE
430     output  vandelay.flat_marc%ROWTYPE;
431     field   RECORD;
432 BEGIN
433     FOR field IN SELECT * FROM vandelay.flay_marc( marc ) LOOP
434         output.ind1 := field.ind1;
435         output.ind2 := field.ind2;
436         output.tag := field.tag;
437         output.subfield := field.subfield;
438         IF field.subfield IS NOT NULL AND field.tag NOT IN ('020','022','024') THEN -- exclude standard numbers and control fields
439             output.value := naco_normalize(field.value, field.subfield);
440         ELSE
441             output.value := field.value;
442         END IF;
443
444         CONTINUE WHEN output.value IS NULL;
445
446         RETURN NEXT output;
447     END LOOP;
448 END;
449 $func$ LANGUAGE PLPGSQL;
450
451 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT, attr_defs TEXT[]) RETURNS hstore AS $_$
452 DECLARE
453     transformed_xml TEXT;
454     prev_xfrm       TEXT;
455     normalizer      RECORD;
456     xfrm            config.xml_transform%ROWTYPE;
457     attr_value      TEXT;
458     new_attrs       HSTORE := ''::HSTORE;
459     attr_def        config.record_attr_definition%ROWTYPE;
460 BEGIN
461
462     FOR attr_def IN SELECT * FROM config.record_attr_definition WHERE name IN (SELECT * FROM UNNEST(attr_defs)) ORDER BY format LOOP
463
464         IF attr_def.tag IS NOT NULL THEN -- tag (and optional subfield list) selection
465             SELECT  STRING_AGG(x.value, COALESCE(attr_def.joiner,' ')) INTO attr_value
466               FROM  vandelay.flatten_marc(xml) AS x
467               WHERE x.tag LIKE attr_def.tag
468                     AND CASE
469                         WHEN attr_def.sf_list IS NOT NULL
470                             THEN POSITION(x.subfield IN attr_def.sf_list) > 0
471                         ELSE TRUE
472                         END
473               GROUP BY x.tag
474               ORDER BY x.tag
475               LIMIT 1;
476
477         ELSIF attr_def.fixed_field IS NOT NULL THEN -- a named fixed field, see config.marc21_ff_pos_map.fixed_field
478             attr_value := vandelay.marc21_extract_fixed_field(xml, attr_def.fixed_field);
479
480         ELSIF attr_def.xpath IS NOT NULL THEN -- and xpath expression
481
482             SELECT INTO xfrm * FROM config.xml_transform WHERE name = attr_def.format;
483
484             -- See if we can skip the XSLT ... it's expensive
485             IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
486                 -- Can't skip the transform
487                 IF xfrm.xslt <> '---' THEN
488                     transformed_xml := oils_xslt_process(xml,xfrm.xslt);
489                 ELSE
490                     transformed_xml := xml;
491                 END IF;
492
493                 prev_xfrm := xfrm.name;
494             END IF;
495
496             IF xfrm.name IS NULL THEN
497                 -- just grab the marcxml (empty) transform
498                 SELECT INTO xfrm * FROM config.xml_transform WHERE xslt = '---' LIMIT 1;
499                 prev_xfrm := xfrm.name;
500             END IF;
501
502             attr_value := oils_xpath_string(attr_def.xpath, transformed_xml, COALESCE(attr_def.joiner,' '), ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]);
503
504         ELSIF attr_def.phys_char_sf IS NOT NULL THEN -- a named Physical Characteristic, see config.marc21_physical_characteristic_*_map
505             SELECT  m.value::TEXT INTO attr_value
506               FROM  vandelay.marc21_physical_characteristics(xml) v
507                     JOIN config.marc21_physical_characteristic_value_map m ON (m.id = v.value)
508               WHERE v.subfield = attr_def.phys_char_sf
509               LIMIT 1; -- Just in case ...
510
511         END IF;
512
513         -- apply index normalizers to attr_value
514         FOR normalizer IN
515             SELECT  n.func AS func,
516                     n.param_count AS param_count,
517                     m.params AS params
518               FROM  config.index_normalizer n
519                     JOIN config.record_attr_index_norm_map m ON (m.norm = n.id)
520               WHERE attr = attr_def.name
521               ORDER BY m.pos LOOP
522                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
523                     quote_nullable( attr_value ) ||
524                     CASE
525                         WHEN normalizer.param_count > 0
526                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
527                             ELSE ''
528                         END ||
529                     ')' INTO attr_value;
530
531         END LOOP;
532
533         -- Add the new value to the hstore
534         new_attrs := new_attrs || hstore( attr_def.name, attr_value );
535
536     END LOOP;
537
538     RETURN new_attrs;
539 END;
540 $_$ LANGUAGE PLPGSQL;
541
542 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT ) RETURNS hstore AS $_$
543     SELECT vandelay.extract_rec_attrs( $1, (SELECT ARRAY_AGG(name) FROM config.record_attr_definition));
544 $_$ LANGUAGE SQL;
545
546 -- Everything between this comment and the beginning of the definition of
547 -- vandelay.match_bib_record() is strictly in service of that function.
548 CREATE TYPE vandelay.match_set_test_result AS (record BIGINT, quality INTEGER);
549
550 CREATE OR REPLACE FUNCTION vandelay.match_set_test_marcxml(
551     match_set_id INTEGER, record_xml TEXT, bucket_id INTEGER 
552 ) RETURNS SETOF vandelay.match_set_test_result AS $$
553 DECLARE
554     tags_rstore HSTORE;
555     svf_rstore  HSTORE;
556     coal        TEXT;
557     joins       TEXT;
558     query_      TEXT;
559     wq          TEXT;
560     qvalue      INTEGER;
561     rec         RECORD;
562 BEGIN
563     tags_rstore := vandelay.flatten_marc_hstore(record_xml);
564     svf_rstore := vandelay.extract_rec_attrs(record_xml);
565
566     CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
567     CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
568
569     -- generate the where clause and return that directly (into wq), and as
570     -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
571     wq := vandelay.get_expr_from_match_set(match_set_id, tags_rstore);
572
573     query_ := 'SELECT DISTINCT(record), ';
574
575     -- qrows table is for the quality bits we add to the SELECT clause
576     SELECT STRING_AGG(
577         'COALESCE(n' || q::TEXT || '.quality, 0)', ' + '
578     ) INTO coal FROM _vandelay_tmp_qrows;
579
580     -- our query string so far is the SELECT clause and the inital FROM.
581     -- no JOINs yet nor the WHERE clause
582     query_ := query_ || coal || ' AS quality ' || E'\n';
583
584     -- jrows table is for the joins we must make (and the real text conditions)
585     SELECT STRING_AGG(j, E'\n') INTO joins
586         FROM _vandelay_tmp_jrows;
587
588     -- add those joins and the where clause to our query.
589     query_ := query_ || joins || E'\n';
590
591     -- join the record bucket
592     IF bucket_id IS NOT NULL THEN
593         query_ := query_ || 'JOIN container.biblio_record_entry_bucket_item ' ||
594             'brebi ON (brebi.target_biblio_record_entry = record ' ||
595             'AND brebi.bucket = ' || bucket_id || E')\n';
596     END IF;
597
598     query_ := query_ || 'JOIN biblio.record_entry bre ON (bre.id = record) ' || 'WHERE ' || wq || ' AND not bre.deleted';
599
600     -- this will return rows of record,quality
601     FOR rec IN EXECUTE query_ USING tags_rstore, svf_rstore LOOP
602         RETURN NEXT rec;
603     END LOOP;
604
605     DROP TABLE _vandelay_tmp_qrows;
606     DROP TABLE _vandelay_tmp_jrows;
607     RETURN;
608 END;
609 $$ LANGUAGE PLPGSQL;
610
611
612 CREATE OR REPLACE FUNCTION vandelay.flatten_marc_hstore(
613     record_xml TEXT
614 ) RETURNS HSTORE AS $func$
615 BEGIN
616     RETURN (SELECT
617         HSTORE(
618             ARRAY_AGG(tag || (COALESCE(subfield, ''))),
619             ARRAY_AGG(value)
620         )
621         FROM (
622             SELECT  tag, subfield, ARRAY_AGG(value)::TEXT AS value
623               FROM  (SELECT tag,
624                             subfield,
625                             CASE WHEN tag = '020' THEN -- caseless -- isbn
626                                 LOWER((REGEXP_MATCHES(value,$$^(\S{10,17})$$))[1] || '%')
627                             WHEN tag = '022' THEN -- caseless -- issn
628                                 LOWER((REGEXP_MATCHES(value,$$^(\S{4}[- ]?\S{4})$$))[1] || '%')
629                             WHEN tag = '024' THEN -- caseless -- upc (other)
630                                 LOWER(value || '%')
631                             ELSE
632                                 value
633                             END AS value
634                       FROM  vandelay.flatten_marc(record_xml)) x
635                 GROUP BY tag, subfield ORDER BY tag, subfield
636         ) subquery
637     );
638 END;
639 $func$ LANGUAGE PLPGSQL;
640
641 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
642     match_set_id INTEGER,
643     tags_rstore HSTORE
644 ) RETURNS TEXT AS $$
645 DECLARE
646     root    vandelay.match_set_point;
647 BEGIN
648     SELECT * INTO root FROM vandelay.match_set_point
649         WHERE parent IS NULL AND match_set = match_set_id;
650
651     RETURN vandelay.get_expr_from_match_set_point(root, tags_rstore);
652 END;
653 $$  LANGUAGE PLPGSQL;
654
655 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set_point(
656     node vandelay.match_set_point,
657     tags_rstore HSTORE
658 ) RETURNS TEXT AS $$
659 DECLARE
660     q           TEXT;
661     i           INTEGER;
662     this_op     TEXT;
663     children    INTEGER[];
664     child       vandelay.match_set_point;
665 BEGIN
666     SELECT ARRAY_AGG(id) INTO children FROM vandelay.match_set_point
667         WHERE parent = node.id;
668
669     IF ARRAY_LENGTH(children, 1) > 0 THEN
670         this_op := vandelay._get_expr_render_one(node);
671         q := '(';
672         i := 1;
673         WHILE children[i] IS NOT NULL LOOP
674             SELECT * INTO child FROM vandelay.match_set_point
675                 WHERE id = children[i];
676             IF i > 1 THEN
677                 q := q || ' ' || this_op || ' ';
678             END IF;
679             i := i + 1;
680             q := q || vandelay.get_expr_from_match_set_point(child, tags_rstore);
681         END LOOP;
682         q := q || ')';
683         RETURN q;
684     ELSIF node.bool_op IS NULL THEN
685         PERFORM vandelay._get_expr_push_qrow(node);
686         PERFORM vandelay._get_expr_push_jrow(node, tags_rstore);
687         RETURN vandelay._get_expr_render_one(node);
688     ELSE
689         RETURN '';
690     END IF;
691 END;
692 $$  LANGUAGE PLPGSQL;
693
694 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_qrow(
695     node vandelay.match_set_point
696 ) RETURNS VOID AS $$
697 DECLARE
698 BEGIN
699     INSERT INTO _vandelay_tmp_qrows (q) VALUES (node.id);
700 END;
701 $$ LANGUAGE PLPGSQL;
702
703 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_jrow(
704     node vandelay.match_set_point,
705     tags_rstore HSTORE
706 ) RETURNS VOID AS $$
707 DECLARE
708     jrow        TEXT;
709     my_alias    TEXT;
710     op          TEXT;
711     tagkey      TEXT;
712     caseless    BOOL;
713     jrow_count  INT;
714     my_using    TEXT;
715     my_join     TEXT;
716 BEGIN
717     -- remember $1 is tags_rstore, and $2 is svf_rstore
718
719     caseless := FALSE;
720     SELECT COUNT(*) INTO jrow_count FROM _vandelay_tmp_jrows;
721     IF jrow_count > 0 THEN
722         my_using := ' USING (record)';
723         my_join := 'FULL OUTER JOIN';
724     ELSE
725         my_using := '';
726         my_join := 'FROM';
727     END IF;
728
729     IF node.tag IS NOT NULL THEN
730         caseless := (node.tag IN ('020', '022', '024'));
731         tagkey := node.tag;
732         IF node.subfield IS NOT NULL THEN
733             tagkey := tagkey || node.subfield;
734         END IF;
735     END IF;
736
737     IF node.negate THEN
738         IF caseless THEN
739             op := 'NOT LIKE';
740         ELSE
741             op := '<>';
742         END IF;
743     ELSE
744         IF caseless THEN
745             op := 'LIKE';
746         ELSE
747             op := '=';
748         END IF;
749     END IF;
750
751     my_alias := 'n' || node.id::TEXT;
752
753     jrow := my_join || ' (SELECT *, ';
754     IF node.tag IS NOT NULL THEN
755         jrow := jrow  || node.quality ||
756             ' AS quality FROM metabib.full_rec mfr WHERE mfr.tag = ''' ||
757             node.tag || '''';
758         IF node.subfield IS NOT NULL THEN
759             jrow := jrow || ' AND mfr.subfield = ''' ||
760                 node.subfield || '''';
761         END IF;
762         jrow := jrow || ' AND (';
763         jrow := jrow || vandelay._node_tag_comparisons(caseless, op, tags_rstore, tagkey);
764         jrow := jrow || ')) ' || my_alias || my_using || E'\n';
765     ELSE    -- svf
766         jrow := jrow || 'id AS record, ' || node.quality ||
767             ' AS quality FROM metabib.record_attr_flat mraf WHERE mraf.attr = ''' ||
768             node.svf || ''' AND mraf.value ' || op || ' $2->''' || node.svf || ''') ' ||
769             my_alias || my_using || E'\n';
770     END IF;
771     INSERT INTO _vandelay_tmp_jrows (j) VALUES (jrow);
772 END;
773 $$ LANGUAGE PLPGSQL;
774
775 CREATE OR REPLACE FUNCTION vandelay._node_tag_comparisons(
776     caseless BOOLEAN,
777     op TEXT,
778     tags_rstore HSTORE,
779     tagkey TEXT
780 ) RETURNS TEXT AS $$
781 DECLARE
782     result  TEXT;
783     i       INT;
784     vals    TEXT[];
785 BEGIN
786     i := 1;
787     vals := tags_rstore->tagkey;
788     result := '';
789
790     WHILE TRUE LOOP
791         IF i > 1 THEN
792             IF vals[i] IS NULL THEN
793                 EXIT;
794             ELSE
795                 result := result || ' OR ';
796             END IF;
797         END IF;
798
799         IF caseless THEN
800             result := result || 'LOWER(mfr.value) ' || op;
801         ELSE
802             result := result || 'mfr.value ' || op;
803         END IF;
804
805         result := result || ' ' || COALESCE('''' || vals[i] || '''', 'NULL');
806
807         IF vals[i] IS NULL THEN
808             EXIT;
809         END IF;
810         i := i + 1;
811     END LOOP;
812
813     RETURN result;
814
815 END;
816 $$ LANGUAGE PLPGSQL;
817
818 CREATE OR REPLACE FUNCTION vandelay._get_expr_render_one(
819     node vandelay.match_set_point
820 ) RETURNS TEXT AS $$
821 DECLARE
822     s           TEXT;
823 BEGIN
824     IF node.bool_op IS NOT NULL THEN
825         RETURN node.bool_op;
826     ELSE
827         RETURN '(n' || node.id::TEXT || '.id IS NOT NULL)';
828     END IF;
829 END;
830 $$ LANGUAGE PLPGSQL;
831
832 CREATE OR REPLACE FUNCTION vandelay.match_bib_record() RETURNS TRIGGER AS $func$
833 DECLARE
834     incoming_existing_id    TEXT;
835     test_result             vandelay.match_set_test_result%ROWTYPE;
836     tmp_rec                 BIGINT;
837     match_set               INT;
838     match_bucket            INT;
839 BEGIN
840     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
841         RETURN NEW;
842     END IF;
843
844     DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
845
846     SELECT q.match_set INTO match_set FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
847
848     IF match_set IS NOT NULL THEN
849         NEW.quality := vandelay.measure_record_quality( NEW.marc, match_set );
850     END IF;
851
852     -- Perfect matches on 901$c exit early with a match with high quality.
853     incoming_existing_id :=
854         oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
855
856     IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
857         SELECT id INTO tmp_rec FROM biblio.record_entry WHERE id = incoming_existing_id::bigint;
858         IF tmp_rec IS NOT NULL THEN
859             INSERT INTO vandelay.bib_match (queued_record, eg_record, match_score, quality) 
860                 SELECT
861                     NEW.id, 
862                     b.id,
863                     9999,
864                     -- note: no match_set means quality==0
865                     vandelay.measure_record_quality( b.marc, match_set )
866                 FROM biblio.record_entry b
867                 WHERE id = incoming_existing_id::bigint;
868         END IF;
869     END IF;
870
871     IF match_set IS NULL THEN
872         RETURN NEW;
873     END IF;
874
875     SELECT q.match_bucket INTO match_bucket FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
876
877     FOR test_result IN SELECT * FROM
878         vandelay.match_set_test_marcxml(match_set, NEW.marc, match_bucket) LOOP
879
880         INSERT INTO vandelay.bib_match ( queued_record, eg_record, match_score, quality )
881             SELECT  
882                 NEW.id,
883                 test_result.record,
884                 test_result.quality,
885                 vandelay.measure_record_quality( b.marc, match_set )
886                 FROM  biblio.record_entry b
887                 WHERE id = test_result.record;
888
889     END LOOP;
890
891     RETURN NEW;
892 END;
893 $func$ LANGUAGE PLPGSQL;
894
895 CREATE OR REPLACE FUNCTION vandelay.measure_record_quality ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
896 DECLARE
897     out_q   INT := 0;
898     rvalue  TEXT;
899     test    vandelay.match_set_quality%ROWTYPE;
900 BEGIN
901
902     FOR test IN SELECT * FROM vandelay.match_set_quality WHERE match_set = match_set_id LOOP
903         IF test.tag IS NOT NULL THEN
904             FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml ) WHERE tag = test.tag AND subfield = test.subfield LOOP
905                 IF test.value = rvalue THEN
906                     out_q := out_q + test.quality;
907                 END IF;
908             END LOOP;
909         ELSE
910             IF test.value = vandelay.extract_rec_attrs(xml, ARRAY[test.svf]) -> test.svf THEN
911                 out_q := out_q + test.quality;
912             END IF;
913         END IF;
914     END LOOP;
915
916     RETURN out_q;
917 END;
918 $_$ LANGUAGE PLPGSQL;
919
920 CREATE TYPE vandelay.tcn_data AS (tcn TEXT, tcn_source TEXT, used BOOL);
921 CREATE OR REPLACE FUNCTION vandelay.find_bib_tcn_data ( xml TEXT ) RETURNS SETOF vandelay.tcn_data AS $_$
922 DECLARE
923     eg_tcn          TEXT;
924     eg_tcn_source   TEXT;
925     output          vandelay.tcn_data%ROWTYPE;
926 BEGIN
927
928     -- 001/003
929     eg_tcn := BTRIM((oils_xpath('//*[@tag="001"]/text()',xml))[1]);
930     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
931
932         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="003"]/text()',xml))[1]);
933         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
934             eg_tcn_source := 'System Local';
935         END IF;
936
937         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
938
939         IF NOT FOUND THEN
940             output.used := FALSE;
941         ELSE
942             output.used := TRUE;
943         END IF;
944
945         output.tcn := eg_tcn;
946         output.tcn_source := eg_tcn_source;
947         RETURN NEXT output;
948
949     END IF;
950
951     -- 901 ab
952     eg_tcn := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="a"]/text()',xml))[1]);
953     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
954
955         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="b"]/text()',xml))[1]);
956         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
957             eg_tcn_source := 'System Local';
958         END IF;
959
960         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
961
962         IF NOT FOUND THEN
963             output.used := FALSE;
964         ELSE
965             output.used := TRUE;
966         END IF;
967
968         output.tcn := eg_tcn;
969         output.tcn_source := eg_tcn_source;
970         RETURN NEXT output;
971
972     END IF;
973
974     -- 039 ab
975     eg_tcn := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="a"]/text()',xml))[1]);
976     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
977
978         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="b"]/text()',xml))[1]);
979         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
980             eg_tcn_source := 'System Local';
981         END IF;
982
983         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
984
985         IF NOT FOUND THEN
986             output.used := FALSE;
987         ELSE
988             output.used := TRUE;
989         END IF;
990
991         output.tcn := eg_tcn;
992         output.tcn_source := eg_tcn_source;
993         RETURN NEXT output;
994
995     END IF;
996
997     -- 020 a
998     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="020"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
999     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1000
1001         eg_tcn_source := 'ISBN';
1002
1003         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
1004
1005         IF NOT FOUND THEN
1006             output.used := FALSE;
1007         ELSE
1008             output.used := TRUE;
1009         END IF;
1010
1011         output.tcn := eg_tcn;
1012         output.tcn_source := eg_tcn_source;
1013         RETURN NEXT output;
1014
1015     END IF;
1016
1017     -- 022 a
1018     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="022"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1019     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1020
1021         eg_tcn_source := 'ISSN';
1022
1023         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
1024
1025         IF NOT FOUND THEN
1026             output.used := FALSE;
1027         ELSE
1028             output.used := TRUE;
1029         END IF;
1030
1031         output.tcn := eg_tcn;
1032         output.tcn_source := eg_tcn_source;
1033         RETURN NEXT output;
1034
1035     END IF;
1036
1037     -- 010 a
1038     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="010"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1039     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1040
1041         eg_tcn_source := 'LCCN';
1042
1043         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
1044
1045         IF NOT FOUND THEN
1046             output.used := FALSE;
1047         ELSE
1048             output.used := TRUE;
1049         END IF;
1050
1051         output.tcn := eg_tcn;
1052         output.tcn_source := eg_tcn_source;
1053         RETURN NEXT output;
1054
1055     END IF;
1056
1057     -- 035 a
1058     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="035"]/*[@code="a"]/text()',xml))[1], $re$^.*?(\w+)$$re$, $re$\1$re$);
1059     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1060
1061         eg_tcn_source := 'System Legacy';
1062
1063         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
1064
1065         IF NOT FOUND THEN
1066             output.used := FALSE;
1067         ELSE
1068             output.used := TRUE;
1069         END IF;
1070
1071         output.tcn := eg_tcn;
1072         output.tcn_source := eg_tcn_source;
1073         RETURN NEXT output;
1074
1075     END IF;
1076
1077     RETURN;
1078 END;
1079 $_$ LANGUAGE PLPGSQL;
1080
1081 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT, force_add INT ) RETURNS TEXT AS $_$
1082
1083     use MARC::Record;
1084     use MARC::File::XML (BinaryEncoding => 'UTF-8');
1085     use MARC::Charset;
1086     use strict;
1087
1088     MARC::Charset->assume_unicode(1);
1089
1090     my $target_xml = shift;
1091     my $source_xml = shift;
1092     my $field_spec = shift;
1093     my $force_add = shift || 0;
1094
1095     my $target_r = MARC::Record->new_from_xml( $target_xml );
1096     my $source_r = MARC::Record->new_from_xml( $source_xml );
1097
1098     return $target_xml unless ($target_r && $source_r);
1099
1100     my @field_list = split(',', $field_spec);
1101
1102     my %fields;
1103     for my $f (@field_list) {
1104         $f =~ s/^\s*//; $f =~ s/\s*$//;
1105         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1106             my $field = $1;
1107             $field =~ s/\s+//;
1108             my $sf = $2;
1109             $sf =~ s/\s+//;
1110             my $match = $3;
1111             $match =~ s/^\s*//; $match =~ s/\s*$//;
1112             $fields{$field} = { sf => [ split('', $sf) ] };
1113             if ($match) {
1114                 my ($msf,$mre) = split('~', $match);
1115                 if (length($msf) > 0 and length($mre) > 0) {
1116                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1117                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1118                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1119                 }
1120             }
1121         }
1122     }
1123
1124     for my $f ( keys %fields) {
1125         if ( @{$fields{$f}{sf}} ) {
1126             for my $from_field ($source_r->field( $f )) {
1127                 my @tos = $target_r->field( $f );
1128                 if (!@tos) {
1129                     next if (exists($fields{$f}{match}) and !$force_add);
1130                     my @new_fields = map { $_->clone } $source_r->field( $f );
1131                     $target_r->insert_fields_ordered( @new_fields );
1132                 } else {
1133                     for my $to_field (@tos) {
1134                         if (exists($fields{$f}{match})) {
1135                             next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1136                         }
1137                         for my $old_sf ($from_field->subfields) {
1138                             $to_field->add_subfields( @$old_sf ) if grep(/$$old_sf[0]/,@{$fields{$f}{sf}});
1139                         }
1140                     }
1141                 }
1142             }
1143         } else {
1144             my @new_fields = map { $_->clone } $source_r->field( $f );
1145             $target_r->insert_fields_ordered( @new_fields );
1146         }
1147     }
1148
1149     $target_xml = $target_r->as_xml_record;
1150     $target_xml =~ s/^<\?.+?\?>$//mo;
1151     $target_xml =~ s/\n//sgo;
1152     $target_xml =~ s/>\s+</></sgo;
1153
1154     return $target_xml;
1155
1156 $_$ LANGUAGE PLPERLU;
1157
1158 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1159     SELECT vandelay.add_field( $1, $2, $3, 0 );
1160 $_$ LANGUAGE SQL;
1161
1162 CREATE OR REPLACE FUNCTION vandelay.strip_field ( xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1163
1164     use MARC::Record;
1165     use MARC::File::XML (BinaryEncoding => 'UTF-8');
1166     use MARC::Charset;
1167     use strict;
1168
1169     MARC::Charset->assume_unicode(1);
1170
1171     my $xml = shift;
1172     my $r = MARC::Record->new_from_xml( $xml );
1173
1174     return $xml unless ($r);
1175
1176     my $field_spec = shift;
1177     my @field_list = split(',', $field_spec);
1178
1179     my %fields;
1180     for my $f (@field_list) {
1181         $f =~ s/^\s*//; $f =~ s/\s*$//;
1182         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1183             my $field = $1;
1184             $field =~ s/\s+//;
1185             my $sf = $2;
1186             $sf =~ s/\s+//;
1187             my $match = $3;
1188             $match =~ s/^\s*//; $match =~ s/\s*$//;
1189             $fields{$field} = { sf => [ split('', $sf) ] };
1190             if ($match) {
1191                 my ($msf,$mre) = split('~', $match);
1192                 if (length($msf) > 0 and length($mre) > 0) {
1193                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1194                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1195                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1196                 }
1197             }
1198         }
1199     }
1200
1201     for my $f ( keys %fields) {
1202         for my $to_field ($r->field( $f )) {
1203             if (exists($fields{$f}{match})) {
1204                 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1205             }
1206
1207             if ( @{$fields{$f}{sf}} ) {
1208                 $to_field->delete_subfield(code => $fields{$f}{sf});
1209             } else {
1210                 $r->delete_field( $to_field );
1211             }
1212         }
1213     }
1214
1215     $xml = $r->as_xml_record;
1216     $xml =~ s/^<\?.+?\?>$//mo;
1217     $xml =~ s/\n//sgo;
1218     $xml =~ s/>\s+</></sgo;
1219
1220     return $xml;
1221
1222 $_$ LANGUAGE PLPERLU;
1223
1224 CREATE OR REPLACE FUNCTION vandelay.replace_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1225 DECLARE
1226     xml_output TEXT;
1227     parsed_target TEXT;
1228     curr_field TEXT;
1229 BEGIN
1230
1231     parsed_target := vandelay.strip_field( target_xml, ''); -- this dance normalizes the format of the xml for the IF below
1232     xml_output := parsed_target; -- if there are no replace rules, just return the input
1233
1234     FOR curr_field IN SELECT UNNEST( STRING_TO_ARRAY(field, ',') ) LOOP -- naive split, but it's the same we use in the perl
1235
1236         xml_output := vandelay.strip_field( parsed_target, curr_field);
1237
1238         IF xml_output <> parsed_target  AND curr_field ~ E'~' THEN
1239             -- we removed something, and there was a regexp restriction in the curr_field definition, so proceed
1240             xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 1 );
1241         ELSIF curr_field !~ E'~' THEN
1242             -- No regexp restriction, add the curr_field
1243             xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 0 );
1244         END IF;
1245
1246         parsed_target := xml_output; -- in prep for any following loop iterations
1247
1248     END LOOP;
1249
1250     RETURN xml_output;
1251 END;
1252 $_$ LANGUAGE PLPGSQL;
1253
1254 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_xml TEXT, source_xml TEXT, add_rule TEXT, replace_preserve_rule TEXT, strip_rule TEXT ) RETURNS TEXT AS $_$
1255     SELECT vandelay.replace_field( vandelay.add_field( vandelay.strip_field( $1, $5) , $2, $3 ), $2, $4);
1256 $_$ LANGUAGE SQL;
1257
1258 CREATE TYPE vandelay.compile_profile AS (add_rule TEXT, replace_rule TEXT, preserve_rule TEXT, strip_rule TEXT);
1259 CREATE OR REPLACE FUNCTION vandelay.compile_profile ( incoming_xml TEXT ) RETURNS vandelay.compile_profile AS $_$
1260 DECLARE
1261     output              vandelay.compile_profile%ROWTYPE;
1262     profile             vandelay.merge_profile%ROWTYPE;
1263     profile_tmpl        TEXT;
1264     profile_tmpl_owner  TEXT;
1265     add_rule            TEXT := '';
1266     strip_rule          TEXT := '';
1267     replace_rule        TEXT := '';
1268     preserve_rule       TEXT := '';
1269
1270 BEGIN
1271
1272     profile_tmpl := (oils_xpath('//*[@tag="905"]/*[@code="t"]/text()',incoming_xml))[1];
1273     profile_tmpl_owner := (oils_xpath('//*[@tag="905"]/*[@code="o"]/text()',incoming_xml))[1];
1274
1275     IF profile_tmpl IS NOT NULL AND profile_tmpl <> '' AND profile_tmpl_owner IS NOT NULL AND profile_tmpl_owner <> '' THEN
1276         SELECT  p.* INTO profile
1277           FROM  vandelay.merge_profile p
1278                 JOIN actor.org_unit u ON (u.id = p.owner)
1279           WHERE p.name = profile_tmpl
1280                 AND u.shortname = profile_tmpl_owner;
1281
1282         IF profile.id IS NOT NULL THEN
1283             add_rule := COALESCE(profile.add_spec,'');
1284             strip_rule := COALESCE(profile.strip_spec,'');
1285             replace_rule := COALESCE(profile.replace_spec,'');
1286             preserve_rule := COALESCE(profile.preserve_spec,'');
1287         END IF;
1288     END IF;
1289
1290     add_rule := add_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="a"]/text()',incoming_xml),','),'');
1291     strip_rule := strip_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="d"]/text()',incoming_xml),','),'');
1292     replace_rule := replace_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="r"]/text()',incoming_xml),','),'');
1293     preserve_rule := preserve_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="p"]/text()',incoming_xml),','),'');
1294
1295     output.add_rule := BTRIM(add_rule,',');
1296     output.replace_rule := BTRIM(replace_rule,',');
1297     output.strip_rule := BTRIM(strip_rule,',');
1298     output.preserve_rule := BTRIM(preserve_rule,',');
1299
1300     RETURN output;
1301 END;
1302 $_$ LANGUAGE PLPGSQL;
1303
1304 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1305 DECLARE
1306     merge_profile   vandelay.merge_profile%ROWTYPE;
1307     dyn_profile     vandelay.compile_profile%ROWTYPE;
1308     editor_string   TEXT;
1309     editor_id       INT;
1310     source_marc     TEXT;
1311     target_marc     TEXT;
1312     eg_marc         TEXT;
1313     replace_rule    TEXT;
1314     match_count     INT;
1315 BEGIN
1316
1317     SELECT  b.marc INTO eg_marc
1318       FROM  biblio.record_entry b
1319       WHERE b.id = eg_id
1320       LIMIT 1;
1321
1322     IF eg_marc IS NULL OR v_marc IS NULL THEN
1323         -- RAISE NOTICE 'no marc for template or bib record';
1324         RETURN FALSE;
1325     END IF;
1326
1327     dyn_profile := vandelay.compile_profile( v_marc );
1328
1329     IF merge_profile_id IS NOT NULL THEN
1330         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1331         IF FOUND THEN
1332             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1333             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1334             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1335             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1336         END IF;
1337     END IF;
1338
1339     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1340         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1341         RETURN FALSE;
1342     END IF;
1343
1344     IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1345         --Since we have nothing to do, just return a NOOP "we did it"
1346         RETURN TRUE;
1347     ELSIF dyn_profile.replace_rule <> '' THEN
1348         source_marc = v_marc;
1349         target_marc = eg_marc;
1350         replace_rule = dyn_profile.replace_rule;
1351     ELSE
1352         source_marc = eg_marc;
1353         target_marc = v_marc;
1354         replace_rule = dyn_profile.preserve_rule;
1355     END IF;
1356
1357     UPDATE  biblio.record_entry
1358       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1359       WHERE id = eg_id;
1360
1361     IF NOT FOUND THEN
1362         -- RAISE NOTICE 'update of biblio.record_entry failed';
1363         RETURN FALSE;
1364     END IF;
1365
1366     RETURN TRUE;
1367
1368 END;
1369 $$ LANGUAGE PLPGSQL;
1370
1371 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_marc TEXT, template_marc TEXT ) RETURNS TEXT AS $$
1372 DECLARE
1373     dyn_profile     vandelay.compile_profile%ROWTYPE;
1374     replace_rule    TEXT;
1375     tmp_marc        TEXT;
1376     trgt_marc        TEXT;
1377     tmpl_marc        TEXT;
1378     match_count     INT;
1379 BEGIN
1380
1381     IF target_marc IS NULL OR template_marc IS NULL THEN
1382         -- RAISE NOTICE 'no marc for target or template record';
1383         RETURN NULL;
1384     END IF;
1385
1386     dyn_profile := vandelay.compile_profile( template_marc );
1387
1388     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1389         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1390         RETURN NULL;
1391     END IF;
1392
1393     IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1394         --Since we have nothing to do, just return what we were given.
1395         RETURN target_marc;
1396     ELSIF dyn_profile.replace_rule <> '' THEN
1397         trgt_marc = target_marc;
1398         tmpl_marc = template_marc;
1399         replace_rule = dyn_profile.replace_rule;
1400     ELSE
1401         tmp_marc = target_marc;
1402         trgt_marc = template_marc;
1403         tmpl_marc = tmp_marc;
1404         replace_rule = dyn_profile.preserve_rule;
1405     END IF;
1406
1407     RETURN vandelay.merge_record_xml( trgt_marc, tmpl_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
1408
1409 END;
1410 $$ LANGUAGE PLPGSQL;
1411
1412 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT) RETURNS BOOL AS $$
1413     SELECT vandelay.template_overlay_bib_record( $1, $2, NULL);
1414 $$ LANGUAGE SQL;
1415
1416 CREATE OR REPLACE FUNCTION vandelay.overlay_bib_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1417 DECLARE
1418     merge_profile   vandelay.merge_profile%ROWTYPE;
1419     dyn_profile     vandelay.compile_profile%ROWTYPE;
1420     editor_string   TEXT;
1421     editor_id       INT;
1422     source_marc     TEXT;
1423     target_marc     TEXT;
1424     eg_marc         TEXT;
1425     v_marc          TEXT;
1426     replace_rule    TEXT;
1427 BEGIN
1428
1429     SELECT  q.marc INTO v_marc
1430       FROM  vandelay.queued_record q
1431             JOIN vandelay.bib_match m ON (m.queued_record = q.id AND q.id = import_id)
1432       LIMIT 1;
1433
1434     IF v_marc IS NULL THEN
1435         -- RAISE NOTICE 'no marc for vandelay or bib record';
1436         RETURN FALSE;
1437     END IF;
1438
1439     IF vandelay.template_overlay_bib_record( v_marc, eg_id, merge_profile_id) THEN
1440         UPDATE  vandelay.queued_bib_record
1441           SET   imported_as = eg_id,
1442                 import_time = NOW()
1443           WHERE id = import_id;
1444
1445         editor_string := (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
1446
1447         IF editor_string IS NOT NULL AND editor_string <> '' THEN
1448             SELECT usr INTO editor_id FROM actor.card WHERE barcode = editor_string;
1449
1450             IF editor_id IS NULL THEN
1451                 SELECT id INTO editor_id FROM actor.usr WHERE usrname = editor_string;
1452             END IF;
1453
1454             IF editor_id IS NOT NULL THEN
1455                 UPDATE biblio.record_entry SET editor = editor_id WHERE id = eg_id;
1456             END IF;
1457         END IF;
1458
1459         RETURN TRUE;
1460     END IF;
1461
1462     -- RAISE NOTICE 'update of biblio.record_entry failed';
1463
1464     RETURN FALSE;
1465
1466 END;
1467 $$ LANGUAGE PLPGSQL;
1468
1469 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT, lwm_ratio_value_p NUMERIC ) RETURNS BOOL AS $$
1470 DECLARE
1471     eg_id           BIGINT;
1472     lwm_ratio_value NUMERIC;
1473 BEGIN
1474
1475     lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
1476
1477     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1478
1479     IF FOUND THEN
1480         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1481         RETURN FALSE;
1482     END IF;
1483
1484     SELECT  m.eg_record INTO eg_id
1485       FROM  vandelay.bib_match m
1486             JOIN vandelay.queued_bib_record qr ON (m.queued_record = qr.id)
1487             JOIN vandelay.bib_queue q ON (qr.queue = q.id)
1488             JOIN biblio.record_entry r ON (r.id = m.eg_record)
1489       WHERE m.queued_record = import_id
1490             AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
1491       ORDER BY  m.match_score DESC, -- required match score
1492                 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
1493                 m.id -- when in doubt, use the first match
1494       LIMIT 1;
1495
1496     IF eg_id IS NULL THEN
1497         -- RAISE NOTICE 'incoming record is not of high enough quality';
1498         RETURN FALSE;
1499     END IF;
1500
1501     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1502 END;
1503 $$ LANGUAGE PLPGSQL;
1504
1505 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1506     SELECT vandelay.auto_overlay_bib_record_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1507 $$ LANGUAGE SQL;
1508
1509 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1510 DECLARE
1511     eg_id           BIGINT;
1512     match_count     INT;
1513 BEGIN
1514
1515     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1516
1517     IF FOUND THEN
1518         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1519         RETURN FALSE;
1520     END IF;
1521
1522     SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
1523
1524     IF match_count <> 1 THEN
1525         -- RAISE NOTICE 'not an exact match';
1526         RETURN FALSE;
1527     END IF;
1528
1529     -- Check that the one match is on the first 901c
1530     SELECT  m.eg_record INTO eg_id
1531       FROM  vandelay.queued_bib_record q
1532             JOIN vandelay.bib_match m ON (m.queued_record = q.id)
1533       WHERE q.id = import_id
1534             AND m.eg_record = oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]',marc)::BIGINT;
1535
1536     IF NOT FOUND THEN
1537         -- RAISE NOTICE 'not a 901c match';
1538         RETURN FALSE;
1539     END IF;
1540
1541     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1542 END;
1543 $$ LANGUAGE PLPGSQL;
1544
1545 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1546 DECLARE
1547     queued_record   vandelay.queued_bib_record%ROWTYPE;
1548 BEGIN
1549
1550     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1551
1552         IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
1553             RETURN NEXT queued_record.id;
1554         END IF;
1555
1556     END LOOP;
1557
1558     RETURN;
1559     
1560 END;
1561 $$ LANGUAGE PLPGSQL;
1562
1563 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( queue_id BIGINT, merge_profile_id INT, lwm_ratio_value NUMERIC ) RETURNS SETOF BIGINT AS $$
1564 DECLARE
1565     queued_record   vandelay.queued_bib_record%ROWTYPE;
1566 BEGIN
1567
1568     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1569
1570         IF vandelay.auto_overlay_bib_record_with_best( queued_record.id, merge_profile_id, lwm_ratio_value ) THEN
1571             RETURN NEXT queued_record.id;
1572         END IF;
1573
1574     END LOOP;
1575
1576     RETURN;
1577     
1578 END;
1579 $$ LANGUAGE PLPGSQL;
1580
1581 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1582     SELECT vandelay.auto_overlay_bib_queue_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1583 $$ LANGUAGE SQL;
1584
1585 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1586     SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
1587 $$ LANGUAGE SQL;
1588
1589 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_marc ( ) RETURNS TRIGGER AS $$
1590 DECLARE
1591     value   TEXT;
1592     atype   TEXT;
1593     adef    RECORD;
1594 BEGIN
1595     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1596         RETURN NEW;
1597     END IF;
1598
1599     FOR adef IN SELECT * FROM vandelay.bib_attr_definition LOOP
1600
1601         SELECT extract_marc_field('vandelay.queued_bib_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_bib_record WHERE id = NEW.id;
1602         IF (value IS NOT NULL AND value <> '') THEN
1603             INSERT INTO vandelay.queued_bib_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1604         END IF;
1605
1606     END LOOP;
1607
1608     RETURN NULL;
1609 END;
1610 $$ LANGUAGE PLPGSQL;
1611
1612 CREATE OR REPLACE FUNCTION vandelay.cleanup_bib_marc ( ) RETURNS TRIGGER AS $$
1613 BEGIN
1614     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1615         RETURN NEW;
1616     END IF;
1617
1618     DELETE FROM vandelay.queued_bib_record_attr WHERE record = OLD.id;
1619     DELETE FROM vandelay.import_item WHERE record = OLD.id;
1620
1621     IF TG_OP = 'UPDATE' THEN
1622         RETURN NEW;
1623     END IF;
1624     RETURN OLD;
1625 END;
1626 $$ LANGUAGE PLPGSQL;
1627
1628 CREATE TRIGGER cleanup_bib_trigger
1629     BEFORE UPDATE OR DELETE ON vandelay.queued_bib_record
1630     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_bib_marc();
1631
1632 CREATE TRIGGER ingest_bib_trigger
1633     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1634     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_marc();
1635
1636 CREATE TRIGGER zz_match_bibs_trigger
1637     BEFORE INSERT OR UPDATE ON vandelay.queued_bib_record
1638     FOR EACH ROW EXECUTE PROCEDURE vandelay.match_bib_record();
1639
1640
1641 /* Authority stuff down here */
1642 ---------------------------------------
1643 CREATE TABLE vandelay.authority_attr_definition (
1644         id                      SERIAL  PRIMARY KEY,
1645         code            TEXT    UNIQUE NOT NULL,
1646         description     TEXT,
1647         xpath           TEXT    NOT NULL,
1648         remove          TEXT    NOT NULL DEFAULT ''
1649 );
1650
1651 CREATE TYPE vandelay.authority_queue_queue_type AS ENUM ('authority');
1652 CREATE TABLE vandelay.authority_queue (
1653         queue_type      vandelay.authority_queue_queue_type NOT NULL DEFAULT 'authority',
1654         CONSTRAINT vand_authority_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
1655 ) INHERITS (vandelay.queue);
1656 ALTER TABLE vandelay.authority_queue ADD PRIMARY KEY (id);
1657
1658 CREATE TABLE vandelay.queued_authority_record (
1659         queue           INT     NOT NULL REFERENCES vandelay.authority_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1660         imported_as     INT     REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1661         import_error    TEXT    REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
1662         error_detail    TEXT
1663 ) INHERITS (vandelay.queued_record);
1664 ALTER TABLE vandelay.queued_authority_record ADD PRIMARY KEY (id);
1665 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
1666
1667 CREATE TABLE vandelay.queued_authority_record_attr (
1668         id                      BIGSERIAL       PRIMARY KEY,
1669         record          BIGINT          NOT NULL REFERENCES vandelay.queued_authority_record (id) DEFERRABLE INITIALLY DEFERRED,
1670         field           INT                     NOT NULL REFERENCES vandelay.authority_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
1671         attr_value      TEXT            NOT NULL
1672 );
1673 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
1674
1675 CREATE TABLE vandelay.authority_match (
1676         id                              BIGSERIAL       PRIMARY KEY,
1677         queued_record   BIGINT          REFERENCES vandelay.queued_authority_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1678         eg_record               BIGINT          REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1679     quality         INT         NOT NULL DEFAULT 0
1680 );
1681
1682 CREATE OR REPLACE FUNCTION vandelay.ingest_authority_marc ( ) RETURNS TRIGGER AS $$
1683 DECLARE
1684     value   TEXT;
1685     atype   TEXT;
1686     adef    RECORD;
1687 BEGIN
1688     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1689         RETURN NEW;
1690     END IF;
1691
1692     FOR adef IN SELECT * FROM vandelay.authority_attr_definition LOOP
1693
1694         SELECT extract_marc_field('vandelay.queued_authority_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_authority_record WHERE id = NEW.id;
1695         IF (value IS NOT NULL AND value <> '') THEN
1696             INSERT INTO vandelay.queued_authority_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1697         END IF;
1698
1699     END LOOP;
1700
1701     RETURN NULL;
1702 END;
1703 $$ LANGUAGE PLPGSQL;
1704
1705 CREATE OR REPLACE FUNCTION vandelay.cleanup_authority_marc ( ) RETURNS TRIGGER AS $$
1706 BEGIN
1707     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1708         RETURN NEW;
1709     END IF;
1710
1711     DELETE FROM vandelay.queued_authority_record_attr WHERE record = OLD.id;
1712     IF TG_OP = 'UPDATE' THEN
1713         RETURN NEW;
1714     END IF;
1715     RETURN OLD;
1716 END;
1717 $$ LANGUAGE PLPGSQL;
1718
1719 CREATE TRIGGER cleanup_authority_trigger
1720     BEFORE UPDATE OR DELETE ON vandelay.queued_authority_record
1721     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_authority_marc();
1722
1723 CREATE TRIGGER ingest_authority_trigger
1724     AFTER INSERT OR UPDATE ON vandelay.queued_authority_record
1725     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_authority_marc();
1726
1727 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1728 DECLARE
1729     merge_profile   vandelay.merge_profile%ROWTYPE;
1730     dyn_profile     vandelay.compile_profile%ROWTYPE;
1731     source_marc     TEXT;
1732     target_marc     TEXT;
1733     eg_marc         TEXT;
1734     v_marc          TEXT;
1735     replace_rule    TEXT;
1736     match_count     INT;
1737 BEGIN
1738
1739     SELECT  b.marc INTO eg_marc
1740       FROM  authority.record_entry b
1741             JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
1742       LIMIT 1;
1743
1744     SELECT  q.marc INTO v_marc
1745       FROM  vandelay.queued_record q
1746             JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
1747       LIMIT 1;
1748
1749     IF eg_marc IS NULL OR v_marc IS NULL THEN
1750         -- RAISE NOTICE 'no marc for vandelay or authority record';
1751         RETURN FALSE;
1752     END IF;
1753
1754     dyn_profile := vandelay.compile_profile( v_marc );
1755
1756     IF merge_profile_id IS NOT NULL THEN
1757         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1758         IF FOUND THEN
1759             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1760             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1761             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1762             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1763         END IF;
1764     END IF;
1765
1766     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1767         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1768         RETURN FALSE;
1769     END IF;
1770
1771     IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1772         --Since we have nothing to do, just return a NOOP "we did it"
1773         RETURN TRUE;
1774     ELSIF dyn_profile.replace_rule <> '' THEN
1775         source_marc = v_marc;
1776         target_marc = eg_marc;
1777         replace_rule = dyn_profile.replace_rule;
1778     ELSE
1779         source_marc = eg_marc;
1780         target_marc = v_marc;
1781         replace_rule = dyn_profile.preserve_rule;
1782     END IF;
1783
1784     UPDATE  authority.record_entry
1785       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1786       WHERE id = eg_id;
1787
1788     IF FOUND THEN
1789         UPDATE  vandelay.queued_authority_record
1790           SET   imported_as = eg_id,
1791                 import_time = NOW()
1792           WHERE id = import_id;
1793         RETURN TRUE;
1794     END IF;
1795
1796     -- RAISE NOTICE 'update of authority.record_entry failed';
1797
1798     RETURN FALSE;
1799
1800 END;
1801 $$ LANGUAGE PLPGSQL;
1802
1803 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1804 DECLARE
1805     eg_id           BIGINT;
1806     match_count     INT;
1807 BEGIN
1808     SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
1809
1810     IF match_count <> 1 THEN
1811         -- RAISE NOTICE 'not an exact match';
1812         RETURN FALSE;
1813     END IF;
1814
1815     SELECT  m.eg_record INTO eg_id
1816       FROM  vandelay.authority_match m
1817       WHERE m.queued_record = import_id
1818       LIMIT 1;
1819
1820     IF eg_id IS NULL THEN
1821         RETURN FALSE;
1822     END IF;
1823
1824     RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
1825 END;
1826 $$ LANGUAGE PLPGSQL;
1827
1828 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1829 DECLARE
1830     queued_record   vandelay.queued_authority_record%ROWTYPE;
1831 BEGIN
1832
1833     FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
1834
1835         IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
1836             RETURN NEXT queued_record.id;
1837         END IF;
1838
1839     END LOOP;
1840
1841     RETURN;
1842     
1843 END;
1844 $$ LANGUAGE PLPGSQL;
1845
1846 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1847     SELECT * FROM vandelay.auto_overlay_authority_queue( $1, NULL );
1848 $$ LANGUAGE SQL;
1849
1850
1851 -- Vandelay (for importing and exporting records) 012.schema.vandelay.sql 
1852 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (1, 'title', oils_i18n_gettext(1, 'vqbrad', 'Title of work', 'description'),'//*[@tag="245"]/*[contains("abcmnopr",@code)]');
1853 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (2, 'author', oils_i18n_gettext(1, 'vqbrad', 'Author of work', 'description'),'//*[@tag="100" or @tag="110" or @tag="113"]/*[contains("ad",@code)]');
1854 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (3, 'language', oils_i18n_gettext(3, 'vqbrad', 'Language of work', 'description'),'//*[@tag="240"]/*[@code="l"][1]');
1855 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (4, 'pagination', oils_i18n_gettext(4, 'vqbrad', 'Pagination', 'description'),'//*[@tag="300"]/*[@code="a"][1]');
1856 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident, remove ) VALUES (5, 'isbn',oils_i18n_gettext(5, 'vqbrad', 'ISBN', 'description'),'//*[@tag="020"]/*[@code="a"]', TRUE, $r$(?:-|\s.+$)$r$);
1857 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident, remove ) VALUES (6, 'issn',oils_i18n_gettext(6, 'vqbrad', 'ISSN', 'description'),'//*[@tag="022"]/*[@code="a"]', TRUE, $r$(?:-|\s.+$)$r$);
1858 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (7, 'price',oils_i18n_gettext(7, 'vqbrad', 'Price', 'description'),'//*[@tag="020" or @tag="022"]/*[@code="c"][1]');
1859 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident ) VALUES (8, 'rec_identifier',oils_i18n_gettext(8, 'vqbrad', 'Accession Number', 'description'),'//*[@tag="001"]', TRUE);
1860 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident ) VALUES (9, 'eg_tcn',oils_i18n_gettext(9, 'vqbrad', 'TCN Value', 'description'),'//*[@tag="901"]/*[@code="a"]', TRUE);
1861 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident ) VALUES (10, 'eg_tcn_source',oils_i18n_gettext(10, 'vqbrad', 'TCN Source', 'description'),'//*[@tag="901"]/*[@code="b"]', TRUE);
1862 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident ) VALUES (11, 'eg_identifier',oils_i18n_gettext(11, 'vqbrad', 'Internal ID', 'description'),'//*[@tag="901"]/*[@code="c"]', TRUE);
1863 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (12, 'publisher',oils_i18n_gettext(12, 'vqbrad', 'Publisher', 'description'),'//*[@tag="260"]/*[@code="b"][1]');
1864 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, remove ) VALUES (13, 'pubdate',oils_i18n_gettext(13, 'vqbrad', 'Publication Date', 'description'),'//*[@tag="260"]/*[@code="c"][1]',$r$\D$r$);
1865 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (14, 'edition',oils_i18n_gettext(14, 'vqbrad', 'Edition', 'description'),'//*[@tag="250"]/*[@code="a"][1]');
1866 --
1867 --INSERT INTO vandelay.import_item_attr_definition (
1868 --    owner, name, tag, owning_lib, circ_lib, location,
1869 --    call_number, circ_modifier, barcode, price, copy_number,
1870 --    circulate, ref, holdable, opac_visible, status
1871 --) VALUES (
1872 --    1,
1873 --    'Evergreen 852 export format',
1874 --    '852',
1875 --    '[@code = "b"][1]',
1876 --    '[@code = "b"][2]',
1877 --    'c',
1878 --    'j',
1879 --    'g',
1880 --    'p',
1881 --    'y',
1882 --    't',
1883 --    '[@code = "x" and text() = "circulating"]',
1884 --    '[@code = "x" and text() = "reference"]',
1885 --    '[@code = "x" and text() = "holdable"]',
1886 --    '[@code = "x" and text() = "visible"]',
1887 --    'z'
1888 --);
1889 --
1890 --INSERT INTO vandelay.import_item_attr_definition (
1891 --    owner,
1892 --    name,
1893 --    tag,
1894 --    owning_lib,
1895 --    location,
1896 --    call_number,
1897 --    circ_modifier,
1898 --    barcode,
1899 --    price,
1900 --    status
1901 --) VALUES (
1902 --    1,
1903 --    'Unicorn Import format -- 999',
1904 --    '999',
1905 --    'm',
1906 --    'l',
1907 --    'a',
1908 --    't',
1909 --    'i',
1910 --    'p',
1911 --    'k'
1912 --);
1913 --
1914 --INSERT INTO vandelay.authority_attr_definition ( code, description, xpath, ident ) VALUES ('rec_identifier','Identifier','//*[@tag="001"]', TRUE);
1915
1916 COMMIT;
1917