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