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