]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/012.schema.vandelay.sql
Merge remote branch 'working/collab/phasefx/unified_vol_copy_ui_from_item_status_ui'
[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 tag, subfield, ARRAY_ACCUM(value)::TEXT AS value
553                 FROM vandelay.flatten_marc(record_xml)
554                 GROUP BY tag, subfield ORDER BY tag, subfield
555         ) subquery
556     );
557 END;
558 $$ LANGUAGE PLPGSQL;
559
560 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
561     match_set_id INTEGER
562 ) RETURNS TEXT AS $$
563 DECLARE
564     root    vandelay.match_set_point;
565 BEGIN
566     SELECT * INTO root FROM vandelay.match_set_point
567         WHERE parent IS NULL AND match_set = match_set_id;
568
569     RETURN vandelay.get_expr_from_match_set_point(root);
570 END;
571 $$  LANGUAGE PLPGSQL;
572
573 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set_point(
574     node vandelay.match_set_point
575 ) RETURNS TEXT AS $$
576 DECLARE
577     q           TEXT;
578     i           INTEGER;
579     this_op     TEXT;
580     children    INTEGER[];
581     child       vandelay.match_set_point;
582 BEGIN
583     SELECT ARRAY_ACCUM(id) INTO children FROM vandelay.match_set_point
584         WHERE parent = node.id;
585
586     IF ARRAY_LENGTH(children, 1) > 0 THEN
587         this_op := vandelay._get_expr_render_one(node);
588         q := '(';
589         i := 1;
590         WHILE children[i] IS NOT NULL LOOP
591             SELECT * INTO child FROM vandelay.match_set_point
592                 WHERE id = children[i];
593             IF i > 1 THEN
594                 q := q || ' ' || this_op || ' ';
595             END IF;
596             i := i + 1;
597             q := q || vandelay.get_expr_from_match_set_point(child);
598         END LOOP;
599         q := q || ')';
600         RETURN q;
601     ELSIF node.bool_op IS NULL THEN
602         PERFORM vandelay._get_expr_push_qrow(node);
603         PERFORM vandelay._get_expr_push_jrow(node);
604         RETURN vandelay._get_expr_render_one(node);
605     ELSE
606         RETURN '';
607     END IF;
608 END;
609 $$  LANGUAGE PLPGSQL;
610
611 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_qrow(
612     node vandelay.match_set_point
613 ) RETURNS VOID AS $$
614 DECLARE
615 BEGIN
616     INSERT INTO _vandelay_tmp_qrows (q) VALUES (node.id);
617 END;
618 $$ LANGUAGE PLPGSQL;
619
620 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_jrow(
621     node vandelay.match_set_point
622 ) RETURNS VOID AS $$
623 DECLARE
624     jrow        TEXT;
625     my_alias    TEXT;
626     op          TEXT;
627     tagkey      TEXT;
628 BEGIN
629     IF node.negate THEN
630         op := '<>';
631     ELSE
632         op := '=';
633     END IF;
634
635     IF node.tag IS NOT NULL THEN
636         tagkey := node.tag;
637         IF node.subfield IS NOT NULL THEN
638             tagkey := tagkey || node.subfield;
639         END IF;
640     END IF;
641
642     my_alias := 'n' || node.id::TEXT;
643
644     jrow := 'LEFT JOIN (SELECT *, ' || node.quality ||
645         ' AS quality FROM metabib.';
646     IF node.tag IS NOT NULL THEN
647         jrow := jrow || 'full_rec) ' || my_alias || ' ON (' ||
648             my_alias || '.record = bre.id AND ' || my_alias || '.tag = ''' ||
649             node.tag || '''';
650         IF node.subfield IS NOT NULL THEN
651             jrow := jrow || ' AND ' || my_alias || '.subfield = ''' ||
652                 node.subfield || '''';
653         END IF;
654         jrow := jrow || ' AND (' || my_alias || '.value ' || op ||
655             ' ANY(($1->''' || tagkey || ''')::TEXT[])))';
656     ELSE    -- svf
657         jrow := jrow || 'record_attr) ' || my_alias || ' ON (' ||
658             my_alias || '.id = bre.id AND (' ||
659             my_alias || '.attrs->''' || node.svf ||
660             ''' ' || op || ' $2->''' || node.svf || '''))';
661     END IF;
662     INSERT INTO _vandelay_tmp_jrows (j) VALUES (jrow);
663 END;
664 $$ LANGUAGE PLPGSQL;
665
666 CREATE OR REPLACE FUNCTION vandelay._get_expr_render_one(
667     node vandelay.match_set_point
668 ) RETURNS TEXT AS $$
669 DECLARE
670     s           TEXT;
671 BEGIN
672     IF node.bool_op IS NOT NULL THEN
673         RETURN node.bool_op;
674     ELSE
675         RETURN '(n' || node.id::TEXT || '.id IS NOT NULL)';
676     END IF;
677 END;
678 $$ LANGUAGE PLPGSQL;
679
680 CREATE OR REPLACE FUNCTION vandelay.match_bib_record() RETURNS TRIGGER AS $func$
681 DECLARE
682     incoming_existing_id    TEXT;
683     test_result             vandelay.match_set_test_result%ROWTYPE;
684     tmp_rec                 BIGINT;
685     match_set               INT;
686 BEGIN
687     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
688         RETURN NEW;
689     END IF;
690
691     DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
692
693     SELECT q.match_set INTO match_set FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
694
695     IF match_set IS NOT NULL THEN
696         NEW.quality := vandelay.measure_record_quality( NEW.marc, match_set );
697     END IF;
698
699     -- Perfect matches on 901$c exit early with a match with high quality.
700     incoming_existing_id :=
701         oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
702
703     IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
704         SELECT id INTO tmp_rec FROM biblio.record_entry WHERE id = incoming_existing_id::bigint;
705         IF tmp_rec IS NOT NULL THEN
706             INSERT INTO vandelay.bib_match (queued_record, eg_record, match_score, quality) 
707                 SELECT
708                     NEW.id, 
709                     b.id,
710                     9999,
711                     -- note: no match_set means quality==0
712                     vandelay.measure_record_quality( b.marc, match_set )
713                 FROM biblio.record_entry b
714                 WHERE id = incoming_existing_id::bigint;
715         END IF;
716     END IF;
717
718     IF match_set IS NULL THEN
719         RETURN NEW;
720     END IF;
721
722     FOR test_result IN SELECT * FROM
723         vandelay.match_set_test_marcxml(match_set, NEW.marc) LOOP
724
725         INSERT INTO vandelay.bib_match ( queued_record, eg_record, match_score, quality )
726             SELECT  
727                 NEW.id,
728                 test_result.record,
729                 test_result.quality,
730                 vandelay.measure_record_quality( b.marc, match_set )
731                 FROM  biblio.record_entry b
732                 WHERE id = test_result.record;
733
734     END LOOP;
735
736     RETURN NEW;
737 END;
738 $func$ LANGUAGE PLPGSQL;
739
740 CREATE OR REPLACE FUNCTION vandelay.measure_record_quality ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
741 DECLARE
742     out_q   INT := 0;
743     rvalue  TEXT;
744     test    vandelay.match_set_quality%ROWTYPE;
745 BEGIN
746
747     FOR test IN SELECT * FROM vandelay.match_set_quality WHERE match_set = match_set_id LOOP
748         IF test.tag IS NOT NULL THEN
749             FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml ) WHERE tag = test.tag AND subfield = test.subfield LOOP
750                 IF test.value = rvalue THEN
751                     out_q := out_q + test.quality;
752                 END IF;
753             END LOOP;
754         ELSE
755             IF test.value = vandelay.extract_rec_attrs(xml, ARRAY[test.svf]) -> test.svf THEN
756                 out_q := out_q + test.quality;
757             END IF;
758         END IF;
759     END LOOP;
760
761     RETURN out_q;
762 END;
763 $_$ LANGUAGE PLPGSQL;
764
765 CREATE TYPE vandelay.tcn_data AS (tcn TEXT, tcn_source TEXT, used BOOL);
766 CREATE OR REPLACE FUNCTION vandelay.find_bib_tcn_data ( xml TEXT ) RETURNS SETOF vandelay.tcn_data AS $_$
767 DECLARE
768     eg_tcn          TEXT;
769     eg_tcn_source   TEXT;
770     output          vandelay.tcn_data%ROWTYPE;
771 BEGIN
772
773     -- 001/003
774     eg_tcn := BTRIM((oils_xpath('//*[@tag="001"]/text()',xml))[1]);
775     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
776
777         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="003"]/text()',xml))[1]);
778         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
779             eg_tcn_source := 'System Local';
780         END IF;
781
782         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
783
784         IF NOT FOUND THEN
785             output.used := FALSE;
786         ELSE
787             output.used := TRUE;
788         END IF;
789
790         output.tcn := eg_tcn;
791         output.tcn_source := eg_tcn_source;
792         RETURN NEXT output;
793
794     END IF;
795
796     -- 901 ab
797     eg_tcn := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="a"]/text()',xml))[1]);
798     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
799
800         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="b"]/text()',xml))[1]);
801         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
802             eg_tcn_source := 'System Local';
803         END IF;
804
805         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
806
807         IF NOT FOUND THEN
808             output.used := FALSE;
809         ELSE
810             output.used := TRUE;
811         END IF;
812
813         output.tcn := eg_tcn;
814         output.tcn_source := eg_tcn_source;
815         RETURN NEXT output;
816
817     END IF;
818
819     -- 039 ab
820     eg_tcn := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="a"]/text()',xml))[1]);
821     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
822
823         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="b"]/text()',xml))[1]);
824         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
825             eg_tcn_source := 'System Local';
826         END IF;
827
828         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
829
830         IF NOT FOUND THEN
831             output.used := FALSE;
832         ELSE
833             output.used := TRUE;
834         END IF;
835
836         output.tcn := eg_tcn;
837         output.tcn_source := eg_tcn_source;
838         RETURN NEXT output;
839
840     END IF;
841
842     -- 020 a
843     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="020"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
844     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
845
846         eg_tcn_source := 'ISBN';
847
848         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
849
850         IF NOT FOUND THEN
851             output.used := FALSE;
852         ELSE
853             output.used := TRUE;
854         END IF;
855
856         output.tcn := eg_tcn;
857         output.tcn_source := eg_tcn_source;
858         RETURN NEXT output;
859
860     END IF;
861
862     -- 022 a
863     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="022"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
864     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
865
866         eg_tcn_source := 'ISSN';
867
868         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
869
870         IF NOT FOUND THEN
871             output.used := FALSE;
872         ELSE
873             output.used := TRUE;
874         END IF;
875
876         output.tcn := eg_tcn;
877         output.tcn_source := eg_tcn_source;
878         RETURN NEXT output;
879
880     END IF;
881
882     -- 010 a
883     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="010"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
884     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
885
886         eg_tcn_source := 'LCCN';
887
888         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
889
890         IF NOT FOUND THEN
891             output.used := FALSE;
892         ELSE
893             output.used := TRUE;
894         END IF;
895
896         output.tcn := eg_tcn;
897         output.tcn_source := eg_tcn_source;
898         RETURN NEXT output;
899
900     END IF;
901
902     -- 035 a
903     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="035"]/*[@code="a"]/text()',xml))[1], $re$^.*?(\w+)$$re$, $re$\1$re$);
904     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
905
906         eg_tcn_source := 'System Legacy';
907
908         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
909
910         IF NOT FOUND THEN
911             output.used := FALSE;
912         ELSE
913             output.used := TRUE;
914         END IF;
915
916         output.tcn := eg_tcn;
917         output.tcn_source := eg_tcn_source;
918         RETURN NEXT output;
919
920     END IF;
921
922     RETURN;
923 END;
924 $_$ LANGUAGE PLPGSQL;
925
926 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT, force_add INT ) RETURNS TEXT AS $_$
927
928     use MARC::Record;
929     use MARC::File::XML (BinaryEncoding => 'UTF-8');
930     use MARC::Charset;
931     use strict;
932
933     MARC::Charset->assume_unicode(1);
934
935     my $target_xml = shift;
936     my $source_xml = shift;
937     my $field_spec = shift;
938     my $force_add = shift || 0;
939
940     my $target_r = MARC::Record->new_from_xml( $target_xml );
941     my $source_r = MARC::Record->new_from_xml( $source_xml );
942
943     return $target_xml unless ($target_r && $source_r);
944
945     my @field_list = split(',', $field_spec);
946
947     my %fields;
948     for my $f (@field_list) {
949         $f =~ s/^\s*//; $f =~ s/\s*$//;
950         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
951             my $field = $1;
952             $field =~ s/\s+//;
953             my $sf = $2;
954             $sf =~ s/\s+//;
955             my $match = $3;
956             $match =~ s/^\s*//; $match =~ s/\s*$//;
957             $fields{$field} = { sf => [ split('', $sf) ] };
958             if ($match) {
959                 my ($msf,$mre) = split('~', $match);
960                 if (length($msf) > 0 and length($mre) > 0) {
961                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
962                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
963                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
964                 }
965             }
966         }
967     }
968
969     for my $f ( keys %fields) {
970         if ( @{$fields{$f}{sf}} ) {
971             for my $from_field ($source_r->field( $f )) {
972                 my @tos = $target_r->field( $f );
973                 if (!@tos) {
974                     next if (exists($fields{$f}{match}) and !$force_add);
975                     my @new_fields = map { $_->clone } $source_r->field( $f );
976                     $target_r->insert_fields_ordered( @new_fields );
977                 } else {
978                     for my $to_field (@tos) {
979                         if (exists($fields{$f}{match})) {
980                             next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
981                         }
982                         my @new_sf = map { ($_ => $from_field->subfield($_)) } grep { defined($from_field->subfield($_)) } @{$fields{$f}{sf}};
983                         $to_field->add_subfields( @new_sf );
984                     }
985                 }
986             }
987         } else {
988             my @new_fields = map { $_->clone } $source_r->field( $f );
989             $target_r->insert_fields_ordered( @new_fields );
990         }
991     }
992
993     $target_xml = $target_r->as_xml_record;
994     $target_xml =~ s/^<\?.+?\?>$//mo;
995     $target_xml =~ s/\n//sgo;
996     $target_xml =~ s/>\s+</></sgo;
997
998     return $target_xml;
999
1000 $_$ LANGUAGE PLPERLU;
1001
1002 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1003     SELECT vandelay.add_field( $1, $2, $3, 0 );
1004 $_$ LANGUAGE SQL;
1005
1006 CREATE OR REPLACE FUNCTION vandelay.strip_field ( xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1007
1008     use MARC::Record;
1009     use MARC::File::XML (BinaryEncoding => 'UTF-8');
1010     use MARC::Charset;
1011     use strict;
1012
1013     MARC::Charset->assume_unicode(1);
1014
1015     my $xml = shift;
1016     my $r = MARC::Record->new_from_xml( $xml );
1017
1018     return $xml unless ($r);
1019
1020     my $field_spec = shift;
1021     my @field_list = split(',', $field_spec);
1022
1023     my %fields;
1024     for my $f (@field_list) {
1025         $f =~ s/^\s*//; $f =~ s/\s*$//;
1026         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1027             my $field = $1;
1028             $field =~ s/\s+//;
1029             my $sf = $2;
1030             $sf =~ s/\s+//;
1031             my $match = $3;
1032             $match =~ s/^\s*//; $match =~ s/\s*$//;
1033             $fields{$field} = { sf => [ split('', $sf) ] };
1034             if ($match) {
1035                 my ($msf,$mre) = split('~', $match);
1036                 if (length($msf) > 0 and length($mre) > 0) {
1037                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1038                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1039                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1040                 }
1041             }
1042         }
1043     }
1044
1045     for my $f ( keys %fields) {
1046         for my $to_field ($r->field( $f )) {
1047             if (exists($fields{$f}{match})) {
1048                 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1049             }
1050
1051             if ( @{$fields{$f}{sf}} ) {
1052                 $to_field->delete_subfield(code => $fields{$f}{sf});
1053             } else {
1054                 $r->delete_field( $to_field );
1055             }
1056         }
1057     }
1058
1059     $xml = $r->as_xml_record;
1060     $xml =~ s/^<\?.+?\?>$//mo;
1061     $xml =~ s/\n//sgo;
1062     $xml =~ s/>\s+</></sgo;
1063
1064     return $xml;
1065
1066 $_$ LANGUAGE PLPERLU;
1067
1068 CREATE OR REPLACE FUNCTION vandelay.replace_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1069 DECLARE
1070     xml_output TEXT;
1071     parsed_target TEXT;
1072     curr_field TEXT;
1073 BEGIN
1074
1075     parsed_target := vandelay.strip_field( target_xml, ''); -- this dance normalizes the format of the xml for the IF below
1076
1077     FOR curr_field IN SELECT UNNEST( STRING_TO_ARRAY(field, ',') ) LOOP -- naive split, but it's the same we use in the perl
1078
1079         xml_output := vandelay.strip_field( parsed_target, curr_field);
1080
1081         IF xml_output <> parsed_target  AND curr_field ~ E'~' THEN
1082             -- we removed something, and there was a regexp restriction in the curr_field definition, so proceed
1083             xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 1 );
1084         ELSIF curr_field !~ E'~' THEN
1085             -- No regexp restriction, add the curr_field
1086             xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 0 );
1087         END IF;
1088
1089         parsed_target := xml_output; -- in prep for any following loop iterations
1090
1091     END LOOP;
1092
1093     RETURN xml_output;
1094 END;
1095 $_$ LANGUAGE PLPGSQL;
1096
1097 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 $_$
1098     SELECT vandelay.replace_field( vandelay.add_field( vandelay.strip_field( $1, $5) , $2, $3 ), $2, $4);
1099 $_$ LANGUAGE SQL;
1100
1101 CREATE TYPE vandelay.compile_profile AS (add_rule TEXT, replace_rule TEXT, preserve_rule TEXT, strip_rule TEXT);
1102 CREATE OR REPLACE FUNCTION vandelay.compile_profile ( incoming_xml TEXT ) RETURNS vandelay.compile_profile AS $_$
1103 DECLARE
1104     output              vandelay.compile_profile%ROWTYPE;
1105     profile             vandelay.merge_profile%ROWTYPE;
1106     profile_tmpl        TEXT;
1107     profile_tmpl_owner  TEXT;
1108     add_rule            TEXT := '';
1109     strip_rule          TEXT := '';
1110     replace_rule        TEXT := '';
1111     preserve_rule       TEXT := '';
1112
1113 BEGIN
1114
1115     profile_tmpl := (oils_xpath('//*[@tag="905"]/*[@code="t"]/text()',incoming_xml))[1];
1116     profile_tmpl_owner := (oils_xpath('//*[@tag="905"]/*[@code="o"]/text()',incoming_xml))[1];
1117
1118     IF profile_tmpl IS NOT NULL AND profile_tmpl <> '' AND profile_tmpl_owner IS NOT NULL AND profile_tmpl_owner <> '' THEN
1119         SELECT  p.* INTO profile
1120           FROM  vandelay.merge_profile p
1121                 JOIN actor.org_unit u ON (u.id = p.owner)
1122           WHERE p.name = profile_tmpl
1123                 AND u.shortname = profile_tmpl_owner;
1124
1125         IF profile.id IS NOT NULL THEN
1126             add_rule := COALESCE(profile.add_spec,'');
1127             strip_rule := COALESCE(profile.strip_spec,'');
1128             replace_rule := COALESCE(profile.replace_spec,'');
1129             preserve_rule := COALESCE(profile.preserve_spec,'');
1130         END IF;
1131     END IF;
1132
1133     add_rule := add_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="a"]/text()',incoming_xml),','),'');
1134     strip_rule := strip_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="d"]/text()',incoming_xml),','),'');
1135     replace_rule := replace_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="r"]/text()',incoming_xml),','),'');
1136     preserve_rule := preserve_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="p"]/text()',incoming_xml),','),'');
1137
1138     output.add_rule := BTRIM(add_rule,',');
1139     output.replace_rule := BTRIM(replace_rule,',');
1140     output.strip_rule := BTRIM(strip_rule,',');
1141     output.preserve_rule := BTRIM(preserve_rule,',');
1142
1143     RETURN output;
1144 END;
1145 $_$ LANGUAGE PLPGSQL;
1146
1147 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1148 DECLARE
1149     merge_profile   vandelay.merge_profile%ROWTYPE;
1150     dyn_profile     vandelay.compile_profile%ROWTYPE;
1151     editor_string   TEXT;
1152     editor_id       INT;
1153     source_marc     TEXT;
1154     target_marc     TEXT;
1155     eg_marc         TEXT;
1156     replace_rule    TEXT;
1157     match_count     INT;
1158 BEGIN
1159
1160     SELECT  b.marc INTO eg_marc
1161       FROM  biblio.record_entry b
1162       WHERE b.id = eg_id
1163       LIMIT 1;
1164
1165     IF eg_marc IS NULL OR v_marc IS NULL THEN
1166         -- RAISE NOTICE 'no marc for template or bib record';
1167         RETURN FALSE;
1168     END IF;
1169
1170     dyn_profile := vandelay.compile_profile( v_marc );
1171
1172     IF merge_profile_id IS NOT NULL THEN
1173         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1174         IF FOUND THEN
1175             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1176             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1177             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1178             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1179         END IF;
1180     END IF;
1181
1182     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1183         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1184         RETURN FALSE;
1185     END IF;
1186
1187     IF dyn_profile.replace_rule <> '' THEN
1188         source_marc = v_marc;
1189         target_marc = eg_marc;
1190         replace_rule = dyn_profile.replace_rule;
1191     ELSE
1192         source_marc = eg_marc;
1193         target_marc = v_marc;
1194         replace_rule = dyn_profile.preserve_rule;
1195     END IF;
1196
1197     UPDATE  biblio.record_entry
1198       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1199       WHERE id = eg_id;
1200
1201     IF NOT FOUND THEN
1202         -- RAISE NOTICE 'update of biblio.record_entry failed';
1203         RETURN FALSE;
1204     END IF;
1205
1206     RETURN TRUE;
1207
1208 END;
1209 $$ LANGUAGE PLPGSQL;
1210
1211 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_marc TEXT, template_marc TEXT ) RETURNS TEXT AS $$
1212 DECLARE
1213     dyn_profile     vandelay.compile_profile%ROWTYPE;
1214     replace_rule    TEXT;
1215     tmp_marc        TEXT;
1216     trgt_marc        TEXT;
1217     tmpl_marc        TEXT;
1218     match_count     INT;
1219 BEGIN
1220
1221     IF target_marc IS NULL OR template_marc IS NULL THEN
1222         -- RAISE NOTICE 'no marc for target or template record';
1223         RETURN NULL;
1224     END IF;
1225
1226     dyn_profile := vandelay.compile_profile( template_marc );
1227
1228     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1229         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1230         RETURN NULL;
1231     END IF;
1232
1233     IF dyn_profile.replace_rule <> '' THEN
1234         trgt_marc = target_marc;
1235         tmpl_marc = template_marc;
1236         replace_rule = dyn_profile.replace_rule;
1237     ELSE
1238         tmp_marc = target_marc;
1239         trgt_marc = template_marc;
1240         tmpl_marc = tmp_marc;
1241         replace_rule = dyn_profile.preserve_rule;
1242     END IF;
1243
1244     RETURN vandelay.merge_record_xml( trgt_marc, tmpl_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
1245
1246 END;
1247 $$ LANGUAGE PLPGSQL;
1248
1249 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT) RETURNS BOOL AS $$
1250     SELECT vandelay.template_overlay_bib_record( $1, $2, NULL);
1251 $$ LANGUAGE SQL;
1252
1253 CREATE OR REPLACE FUNCTION vandelay.overlay_bib_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1254 DECLARE
1255     merge_profile   vandelay.merge_profile%ROWTYPE;
1256     dyn_profile     vandelay.compile_profile%ROWTYPE;
1257     editor_string   TEXT;
1258     editor_id       INT;
1259     source_marc     TEXT;
1260     target_marc     TEXT;
1261     eg_marc         TEXT;
1262     v_marc          TEXT;
1263     replace_rule    TEXT;
1264 BEGIN
1265
1266     SELECT  q.marc INTO v_marc
1267       FROM  vandelay.queued_record q
1268             JOIN vandelay.bib_match m ON (m.queued_record = q.id AND q.id = import_id)
1269       LIMIT 1;
1270
1271     IF v_marc IS NULL THEN
1272         -- RAISE NOTICE 'no marc for vandelay or bib record';
1273         RETURN FALSE;
1274     END IF;
1275
1276     IF vandelay.template_overlay_bib_record( v_marc, eg_id, merge_profile_id) THEN
1277         UPDATE  vandelay.queued_bib_record
1278           SET   imported_as = eg_id,
1279                 import_time = NOW()
1280           WHERE id = import_id;
1281
1282         editor_string := (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
1283
1284         IF editor_string IS NOT NULL AND editor_string <> '' THEN
1285             SELECT usr INTO editor_id FROM actor.card WHERE barcode = editor_string;
1286
1287             IF editor_id IS NULL THEN
1288                 SELECT id INTO editor_id FROM actor.usr WHERE usrname = editor_string;
1289             END IF;
1290
1291             IF editor_id IS NOT NULL THEN
1292                 UPDATE biblio.record_entry SET editor = editor_id WHERE id = eg_id;
1293             END IF;
1294         END IF;
1295
1296         RETURN TRUE;
1297     END IF;
1298
1299     -- RAISE NOTICE 'update of biblio.record_entry failed';
1300
1301     RETURN FALSE;
1302
1303 END;
1304 $$ LANGUAGE PLPGSQL;
1305
1306 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 $$
1307 DECLARE
1308     eg_id           BIGINT;
1309     lwm_ratio_value NUMERIC;
1310 BEGIN
1311
1312     lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
1313
1314     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1315
1316     IF FOUND THEN
1317         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1318         RETURN FALSE;
1319     END IF;
1320
1321     SELECT  m.eg_record INTO eg_id
1322       FROM  vandelay.bib_match m
1323             JOIN vandelay.queued_bib_record qr ON (m.queued_record = qr.id)
1324             JOIN vandelay.bib_queue q ON (qr.queue = q.id)
1325             JOIN biblio.record_entry r ON (r.id = m.eg_record)
1326       WHERE m.queued_record = import_id
1327             AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
1328       ORDER BY  m.match_score DESC, -- required match score
1329                 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
1330                 m.id -- when in doubt, use the first match
1331       LIMIT 1;
1332
1333     IF eg_id IS NULL THEN
1334         -- RAISE NOTICE 'incoming record is not of high enough quality';
1335         RETURN FALSE;
1336     END IF;
1337
1338     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1339 END;
1340 $$ LANGUAGE PLPGSQL;
1341
1342 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1343     SELECT vandelay.auto_overlay_bib_record_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1344 $$ LANGUAGE SQL;
1345
1346 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1347 DECLARE
1348     eg_id           BIGINT;
1349     match_count     INT;
1350 BEGIN
1351
1352     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1353
1354     IF FOUND THEN
1355         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1356         RETURN FALSE;
1357     END IF;
1358
1359     SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
1360
1361     IF match_count <> 1 THEN
1362         -- RAISE NOTICE 'not an exact match';
1363         RETURN FALSE;
1364     END IF;
1365
1366     -- Check that the one match is on the first 901c
1367     SELECT  m.eg_record INTO eg_id
1368       FROM  vandelay.queued_bib_record q
1369             JOIN vandelay.bib_match m ON (m.queued_record = q.id)
1370       WHERE q.id = import_id
1371             AND m.eg_record = oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]',marc)::BIGINT;
1372
1373     IF NOT FOUND THEN
1374         -- RAISE NOTICE 'not a 901c match';
1375         RETURN FALSE;
1376     END IF;
1377
1378     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1379 END;
1380 $$ LANGUAGE PLPGSQL;
1381
1382 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1383 DECLARE
1384     queued_record   vandelay.queued_bib_record%ROWTYPE;
1385 BEGIN
1386
1387     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1388
1389         IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
1390             RETURN NEXT queued_record.id;
1391         END IF;
1392
1393     END LOOP;
1394
1395     RETURN;
1396     
1397 END;
1398 $$ LANGUAGE PLPGSQL;
1399
1400 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 $$
1401 DECLARE
1402     queued_record   vandelay.queued_bib_record%ROWTYPE;
1403 BEGIN
1404
1405     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1406
1407         IF vandelay.auto_overlay_bib_record_with_best( queued_record.id, merge_profile_id, lwm_ratio_value ) THEN
1408             RETURN NEXT queued_record.id;
1409         END IF;
1410
1411     END LOOP;
1412
1413     RETURN;
1414     
1415 END;
1416 $$ LANGUAGE PLPGSQL;
1417
1418 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1419     SELECT vandelay.auto_overlay_bib_queue_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1420 $$ LANGUAGE SQL;
1421
1422 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1423     SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
1424 $$ LANGUAGE SQL;
1425
1426 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_marc ( ) RETURNS TRIGGER AS $$
1427 DECLARE
1428     value   TEXT;
1429     atype   TEXT;
1430     adef    RECORD;
1431 BEGIN
1432     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1433         RETURN NEW;
1434     END IF;
1435
1436     FOR adef IN SELECT * FROM vandelay.bib_attr_definition LOOP
1437
1438         SELECT extract_marc_field('vandelay.queued_bib_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_bib_record WHERE id = NEW.id;
1439         IF (value IS NOT NULL AND value <> '') THEN
1440             INSERT INTO vandelay.queued_bib_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1441         END IF;
1442
1443     END LOOP;
1444
1445     RETURN NULL;
1446 END;
1447 $$ LANGUAGE PLPGSQL;
1448
1449 CREATE OR REPLACE FUNCTION vandelay.cleanup_bib_marc ( ) RETURNS TRIGGER AS $$
1450 BEGIN
1451     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1452         RETURN NEW;
1453     END IF;
1454
1455     DELETE FROM vandelay.queued_bib_record_attr WHERE record = OLD.id;
1456     DELETE FROM vandelay.import_item WHERE record = OLD.id;
1457
1458     IF TG_OP = 'UPDATE' THEN
1459         RETURN NEW;
1460     END IF;
1461     RETURN OLD;
1462 END;
1463 $$ LANGUAGE PLPGSQL;
1464
1465 CREATE TRIGGER cleanup_bib_trigger
1466     BEFORE UPDATE OR DELETE ON vandelay.queued_bib_record
1467     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_bib_marc();
1468
1469 CREATE TRIGGER ingest_bib_trigger
1470     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1471     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_marc();
1472
1473 CREATE TRIGGER zz_match_bibs_trigger
1474     BEFORE INSERT OR UPDATE ON vandelay.queued_bib_record
1475     FOR EACH ROW EXECUTE PROCEDURE vandelay.match_bib_record();
1476
1477
1478 /* Authority stuff down here */
1479 ---------------------------------------
1480 CREATE TABLE vandelay.authority_attr_definition (
1481         id                      SERIAL  PRIMARY KEY,
1482         code            TEXT    UNIQUE NOT NULL,
1483         description     TEXT,
1484         xpath           TEXT    NOT NULL,
1485         remove          TEXT    NOT NULL DEFAULT ''
1486 );
1487
1488 CREATE TABLE vandelay.authority_queue (
1489         queue_type      TEXT            NOT NULL DEFAULT 'authority' CHECK (queue_type = 'authority'),
1490         CONSTRAINT vand_authority_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
1491 ) INHERITS (vandelay.queue);
1492 ALTER TABLE vandelay.authority_queue ADD PRIMARY KEY (id);
1493
1494 CREATE TABLE vandelay.queued_authority_record (
1495         queue           INT     NOT NULL REFERENCES vandelay.authority_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1496         imported_as     INT     REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1497         import_error    TEXT    REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
1498         error_detail    TEXT
1499 ) INHERITS (vandelay.queued_record);
1500 ALTER TABLE vandelay.queued_authority_record ADD PRIMARY KEY (id);
1501 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
1502
1503 CREATE TABLE vandelay.queued_authority_record_attr (
1504         id                      BIGSERIAL       PRIMARY KEY,
1505         record          BIGINT          NOT NULL REFERENCES vandelay.queued_authority_record (id) DEFERRABLE INITIALLY DEFERRED,
1506         field           INT                     NOT NULL REFERENCES vandelay.authority_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
1507         attr_value      TEXT            NOT NULL
1508 );
1509 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
1510
1511 CREATE TABLE vandelay.authority_match (
1512         id                              BIGSERIAL       PRIMARY KEY,
1513         queued_record   BIGINT          REFERENCES vandelay.queued_authority_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1514         eg_record               BIGINT          REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1515     quality         INT         NOT NULL DEFAULT 0
1516 );
1517
1518 CREATE OR REPLACE FUNCTION vandelay.ingest_authority_marc ( ) RETURNS TRIGGER AS $$
1519 DECLARE
1520     value   TEXT;
1521     atype   TEXT;
1522     adef    RECORD;
1523 BEGIN
1524     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1525         RETURN NEW;
1526     END IF;
1527
1528     FOR adef IN SELECT * FROM vandelay.authority_attr_definition LOOP
1529
1530         SELECT extract_marc_field('vandelay.queued_authority_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_authority_record WHERE id = NEW.id;
1531         IF (value IS NOT NULL AND value <> '') THEN
1532             INSERT INTO vandelay.queued_authority_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1533         END IF;
1534
1535     END LOOP;
1536
1537     RETURN NULL;
1538 END;
1539 $$ LANGUAGE PLPGSQL;
1540
1541 CREATE OR REPLACE FUNCTION vandelay.cleanup_authority_marc ( ) RETURNS TRIGGER AS $$
1542 BEGIN
1543     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1544         RETURN NEW;
1545     END IF;
1546
1547     DELETE FROM vandelay.queued_authority_record_attr WHERE record = OLD.id;
1548     IF TG_OP = 'UPDATE' THEN
1549         RETURN NEW;
1550     END IF;
1551     RETURN OLD;
1552 END;
1553 $$ LANGUAGE PLPGSQL;
1554
1555 CREATE TRIGGER cleanup_authority_trigger
1556     BEFORE UPDATE OR DELETE ON vandelay.queued_authority_record
1557     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_authority_marc();
1558
1559 CREATE TRIGGER ingest_authority_trigger
1560     AFTER INSERT OR UPDATE ON vandelay.queued_authority_record
1561     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_authority_marc();
1562
1563 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1564 DECLARE
1565     merge_profile   vandelay.merge_profile%ROWTYPE;
1566     dyn_profile     vandelay.compile_profile%ROWTYPE;
1567     source_marc     TEXT;
1568     target_marc     TEXT;
1569     eg_marc         TEXT;
1570     v_marc          TEXT;
1571     replace_rule    TEXT;
1572     match_count     INT;
1573 BEGIN
1574
1575     SELECT  b.marc INTO eg_marc
1576       FROM  authority.record_entry b
1577             JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
1578       LIMIT 1;
1579
1580     SELECT  q.marc INTO v_marc
1581       FROM  vandelay.queued_record q
1582             JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
1583       LIMIT 1;
1584
1585     IF eg_marc IS NULL OR v_marc IS NULL THEN
1586         -- RAISE NOTICE 'no marc for vandelay or authority record';
1587         RETURN FALSE;
1588     END IF;
1589
1590     dyn_profile := vandelay.compile_profile( v_marc );
1591
1592     IF merge_profile_id IS NOT NULL THEN
1593         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1594         IF FOUND THEN
1595             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1596             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1597             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1598             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1599         END IF;
1600     END IF;
1601
1602     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1603         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1604         RETURN FALSE;
1605     END IF;
1606
1607     IF dyn_profile.replace_rule <> '' THEN
1608         source_marc = v_marc;
1609         target_marc = eg_marc;
1610         replace_rule = dyn_profile.replace_rule;
1611     ELSE
1612         source_marc = eg_marc;
1613         target_marc = v_marc;
1614         replace_rule = dyn_profile.preserve_rule;
1615     END IF;
1616
1617     UPDATE  authority.record_entry
1618       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1619       WHERE id = eg_id;
1620
1621     IF FOUND THEN
1622         UPDATE  vandelay.queued_authority_record
1623           SET   imported_as = eg_id,
1624                 import_time = NOW()
1625           WHERE id = import_id;
1626         RETURN TRUE;
1627     END IF;
1628
1629     -- RAISE NOTICE 'update of authority.record_entry failed';
1630
1631     RETURN FALSE;
1632
1633 END;
1634 $$ LANGUAGE PLPGSQL;
1635
1636 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1637 DECLARE
1638     eg_id           BIGINT;
1639     match_count     INT;
1640 BEGIN
1641     SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
1642
1643     IF match_count <> 1 THEN
1644         -- RAISE NOTICE 'not an exact match';
1645         RETURN FALSE;
1646     END IF;
1647
1648     SELECT  m.eg_record INTO eg_id
1649       FROM  vandelay.authority_match m
1650       WHERE m.queued_record = import_id
1651       LIMIT 1;
1652
1653     IF eg_id IS NULL THEN
1654         RETURN FALSE;
1655     END IF;
1656
1657     RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
1658 END;
1659 $$ LANGUAGE PLPGSQL;
1660
1661 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1662 DECLARE
1663     queued_record   vandelay.queued_authority_record%ROWTYPE;
1664 BEGIN
1665
1666     FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
1667
1668         IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
1669             RETURN NEXT queued_record.id;
1670         END IF;
1671
1672     END LOOP;
1673
1674     RETURN;
1675     
1676 END;
1677 $$ LANGUAGE PLPGSQL;
1678
1679 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1680     SELECT * FROM vandelay.auto_overlay_authority_queue( $1, NULL );
1681 $$ LANGUAGE SQL;
1682
1683
1684 -- Vandelay (for importing and exporting records) 012.schema.vandelay.sql 
1685 --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)]');
1686 --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)]');
1687 --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]');
1688 --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]');
1689 --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$);
1690 --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$);
1691 --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]');
1692 --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);
1693 --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);
1694 --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);
1695 --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);
1696 --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]');
1697 --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$);
1698 --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]');
1699 --
1700 --INSERT INTO vandelay.import_item_attr_definition (
1701 --    owner, name, tag, owning_lib, circ_lib, location,
1702 --    call_number, circ_modifier, barcode, price, copy_number,
1703 --    circulate, ref, holdable, opac_visible, status
1704 --) VALUES (
1705 --    1,
1706 --    'Evergreen 852 export format',
1707 --    '852',
1708 --    '[@code = "b"][1]',
1709 --    '[@code = "b"][2]',
1710 --    'c',
1711 --    'j',
1712 --    'g',
1713 --    'p',
1714 --    'y',
1715 --    't',
1716 --    '[@code = "x" and text() = "circulating"]',
1717 --    '[@code = "x" and text() = "reference"]',
1718 --    '[@code = "x" and text() = "holdable"]',
1719 --    '[@code = "x" and text() = "visible"]',
1720 --    'z'
1721 --);
1722 --
1723 --INSERT INTO vandelay.import_item_attr_definition (
1724 --    owner,
1725 --    name,
1726 --    tag,
1727 --    owning_lib,
1728 --    location,
1729 --    call_number,
1730 --    circ_modifier,
1731 --    barcode,
1732 --    price,
1733 --    status
1734 --) VALUES (
1735 --    1,
1736 --    'Unicorn Import format -- 999',
1737 --    '999',
1738 --    'm',
1739 --    'l',
1740 --    'a',
1741 --    't',
1742 --    'i',
1743 --    'p',
1744 --    'k'
1745 --);
1746 --
1747 --INSERT INTO vandelay.authority_attr_definition ( code, description, xpath, ident ) VALUES ('rec_identifier','Identifier','//*[@tag="001"]', TRUE);
1748
1749 COMMIT;
1750