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