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