]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/012.schema.vandelay.sql
Replace vandelay.match_bib_record() with the new tree-y version
[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 ' ||
668             (CASE WHEN node.negate THEN '' ELSE 'NOT ' END) ||  -- sic!
669             'NULL)';
670     END IF;
671 END;
672 $$ LANGUAGE PLPGSQL;
673
674 CREATE OR REPLACE FUNCTION vandelay.match_bib_record() RETURNS TRIGGER AS $func$
675 DECLARE
676     incoming_existing_id    TEXT;
677     my_bib_queue            vandelay.bib_queue%ROWTYPE;
678     test_result             vandelay.match_set_test_result%ROWTYPE;
679     tmp_rec                 BIGINT;
680 BEGIN
681     DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
682
683     -- Perfect matches on 901$c exit early with a match with high quality.
684     incoming_existing_id :=
685         oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
686
687     IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
688         SELECT id INTO tmp_rec FROM biblio.record_entry WHERE id = incoming_existing_id::bigint;
689         IF tmp_rec IS NOT NULL THEN
690             INSERT INTO vandelay.bib_match (queued_record, eg_record, quality) VALUES ( NEW.id, incoming_existing_id::bigint, 9999);
691             RETURN NEW;
692         END IF;
693     END IF;
694
695     SELECT * INTO my_bib_queue FROM vandelay.bib_queue WHERE id = NEW.queue;
696
697     FOR test_result IN SELECT * FROM
698         vandelay.match_set_test_marcxml(my_bib_queue.match_set, NEW.marc) LOOP
699
700         INSERT INTO vandelay.bib_match (
701             matched_set, queued_record, eg_record, quality
702         ) VALUES (
703             my_bib_queue.match_set, NEW.id, test_result.record,
704             test_result.quality
705         );
706
707     END LOOP;
708
709     RETURN NEW;
710 END;
711 $func$ LANGUAGE PLPGSQL;
712
713 CREATE OR REPLACE FUNCTION vandelay.incoming_record_quality ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
714 DECLARE
715     out_q   INT := 0;
716     rvalue  TEXT;
717     test    vandelay.match_set_quality%ROWTYPE;
718 BEGIN
719
720     FOR test IN SELECT * FROM vandelay.match_set_quality WHERE match_set = match_set_id LOOP
721         IF test.tag IS NOT NULL THEN
722             FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml ) WHERE tag = test.tag AND subfield = test.subfield LOOP
723                 IF test.value = rvalue THEN
724                     out_q := out_q + test.quality;
725                 END IF;
726             END LOOP;
727         ELSE
728             IF test.value = vandelay.extract_rec_attrs(xml, ARRAY[test.svf]) THEN
729                 out_q := out_q + test.quality;
730             END IF;
731         END IF;
732     END LOOP;
733
734     RETURN out_q;
735 END;
736 $_$ LANGUAGE PLPGSQL;
737
738 CREATE TYPE vandelay.tcn_data AS (tcn TEXT, tcn_source TEXT, used BOOL);
739 CREATE OR REPLACE FUNCTION vandelay.find_bib_tcn_data ( xml TEXT ) RETURNS SETOF vandelay.tcn_data AS $_$
740 DECLARE
741     eg_tcn          TEXT;
742     eg_tcn_source   TEXT;
743     output          vandelay.tcn_data%ROWTYPE;
744 BEGIN
745
746     -- 001/003
747     eg_tcn := BTRIM((oils_xpath('//*[@tag="001"]/text()',xml))[1]);
748     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
749
750         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="003"]/text()',xml))[1]);
751         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
752             eg_tcn_source := 'System Local';
753         END IF;
754
755         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
756
757         IF NOT FOUND THEN
758             output.used := FALSE;
759         ELSE
760             output.used := TRUE;
761         END IF;
762
763         output.tcn := eg_tcn;
764         output.tcn_source := eg_tcn_source;
765         RETURN NEXT output;
766
767     END IF;
768
769     -- 901 ab
770     eg_tcn := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="a"]/text()',xml))[1]);
771     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
772
773         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="b"]/text()',xml))[1]);
774         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
775             eg_tcn_source := 'System Local';
776         END IF;
777
778         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
779
780         IF NOT FOUND THEN
781             output.used := FALSE;
782         ELSE
783             output.used := TRUE;
784         END IF;
785
786         output.tcn := eg_tcn;
787         output.tcn_source := eg_tcn_source;
788         RETURN NEXT output;
789
790     END IF;
791
792     -- 039 ab
793     eg_tcn := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="a"]/text()',xml))[1]);
794     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
795
796         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="b"]/text()',xml))[1]);
797         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
798             eg_tcn_source := 'System Local';
799         END IF;
800
801         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
802
803         IF NOT FOUND THEN
804             output.used := FALSE;
805         ELSE
806             output.used := TRUE;
807         END IF;
808
809         output.tcn := eg_tcn;
810         output.tcn_source := eg_tcn_source;
811         RETURN NEXT output;
812
813     END IF;
814
815     -- 020 a
816     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="020"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
817     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
818
819         eg_tcn_source := 'ISBN';
820
821         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
822
823         IF NOT FOUND THEN
824             output.used := FALSE;
825         ELSE
826             output.used := TRUE;
827         END IF;
828
829         output.tcn := eg_tcn;
830         output.tcn_source := eg_tcn_source;
831         RETURN NEXT output;
832
833     END IF;
834
835     -- 022 a
836     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="022"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
837     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
838
839         eg_tcn_source := 'ISSN';
840
841         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
842
843         IF NOT FOUND THEN
844             output.used := FALSE;
845         ELSE
846             output.used := TRUE;
847         END IF;
848
849         output.tcn := eg_tcn;
850         output.tcn_source := eg_tcn_source;
851         RETURN NEXT output;
852
853     END IF;
854
855     -- 010 a
856     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="010"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
857     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
858
859         eg_tcn_source := 'LCCN';
860
861         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
862
863         IF NOT FOUND THEN
864             output.used := FALSE;
865         ELSE
866             output.used := TRUE;
867         END IF;
868
869         output.tcn := eg_tcn;
870         output.tcn_source := eg_tcn_source;
871         RETURN NEXT output;
872
873     END IF;
874
875     -- 035 a
876     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="035"]/*[@code="a"]/text()',xml))[1], $re$^.*?(\w+)$$re$, $re$\1$re$);
877     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
878
879         eg_tcn_source := 'System Legacy';
880
881         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
882
883         IF NOT FOUND THEN
884             output.used := FALSE;
885         ELSE
886             output.used := TRUE;
887         END IF;
888
889         output.tcn := eg_tcn;
890         output.tcn_source := eg_tcn_source;
891         RETURN NEXT output;
892
893     END IF;
894
895     RETURN;
896 END;
897 $_$ LANGUAGE PLPGSQL;
898
899 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT, force_add INT ) RETURNS TEXT AS $_$
900
901     use MARC::Record;
902     use MARC::File::XML (BinaryEncoding => 'UTF-8');
903     use MARC::Charset;
904     use strict;
905
906     MARC::Charset->assume_unicode(1);
907
908     my $target_xml = shift;
909     my $source_xml = shift;
910     my $field_spec = shift;
911     my $force_add = shift || 0;
912
913     my $target_r = MARC::Record->new_from_xml( $target_xml );
914     my $source_r = MARC::Record->new_from_xml( $source_xml );
915
916     return $target_xml unless ($target_r && $source_r);
917
918     my @field_list = split(',', $field_spec);
919
920     my %fields;
921     for my $f (@field_list) {
922         $f =~ s/^\s*//; $f =~ s/\s*$//;
923         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
924             my $field = $1;
925             $field =~ s/\s+//;
926             my $sf = $2;
927             $sf =~ s/\s+//;
928             my $match = $3;
929             $match =~ s/^\s*//; $match =~ s/\s*$//;
930             $fields{$field} = { sf => [ split('', $sf) ] };
931             if ($match) {
932                 my ($msf,$mre) = split('~', $match);
933                 if (length($msf) > 0 and length($mre) > 0) {
934                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
935                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
936                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
937                 }
938             }
939         }
940     }
941
942     for my $f ( keys %fields) {
943         if ( @{$fields{$f}{sf}} ) {
944             for my $from_field ($source_r->field( $f )) {
945                 my @tos = $target_r->field( $f );
946                 if (!@tos) {
947                     next if (exists($fields{$f}{match}) and !$force_add);
948                     my @new_fields = map { $_->clone } $source_r->field( $f );
949                     $target_r->insert_fields_ordered( @new_fields );
950                 } else {
951                     for my $to_field (@tos) {
952                         if (exists($fields{$f}{match})) {
953                             next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
954                         }
955                         my @new_sf = map { ($_ => $from_field->subfield($_)) } @{$fields{$f}{sf}};
956                         $to_field->add_subfields( @new_sf );
957                     }
958                 }
959             }
960         } else {
961             my @new_fields = map { $_->clone } $source_r->field( $f );
962             $target_r->insert_fields_ordered( @new_fields );
963         }
964     }
965
966     $target_xml = $target_r->as_xml_record;
967     $target_xml =~ s/^<\?.+?\?>$//mo;
968     $target_xml =~ s/\n//sgo;
969     $target_xml =~ s/>\s+</></sgo;
970
971     return $target_xml;
972
973 $_$ LANGUAGE PLPERLU;
974
975 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
976     SELECT vandelay.add_field( $1, $2, $3, 0 );
977 $_$ LANGUAGE SQL;
978
979 CREATE OR REPLACE FUNCTION vandelay.strip_field ( xml TEXT, field TEXT ) RETURNS TEXT AS $_$
980
981     use MARC::Record;
982     use MARC::File::XML (BinaryEncoding => 'UTF-8');
983     use MARC::Charset;
984     use strict;
985
986     MARC::Charset->assume_unicode(1);
987
988     my $xml = shift;
989     my $r = MARC::Record->new_from_xml( $xml );
990
991     return $xml unless ($r);
992
993     my $field_spec = shift;
994     my @field_list = split(',', $field_spec);
995
996     my %fields;
997     for my $f (@field_list) {
998         $f =~ s/^\s*//; $f =~ s/\s*$//;
999         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1000             my $field = $1;
1001             $field =~ s/\s+//;
1002             my $sf = $2;
1003             $sf =~ s/\s+//;
1004             my $match = $3;
1005             $match =~ s/^\s*//; $match =~ s/\s*$//;
1006             $fields{$field} = { sf => [ split('', $sf) ] };
1007             if ($match) {
1008                 my ($msf,$mre) = split('~', $match);
1009                 if (length($msf) > 0 and length($mre) > 0) {
1010                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1011                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1012                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1013                 }
1014             }
1015         }
1016     }
1017
1018     for my $f ( keys %fields) {
1019         for my $to_field ($r->field( $f )) {
1020             if (exists($fields{$f}{match})) {
1021                 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1022             }
1023
1024             if ( @{$fields{$f}{sf}} ) {
1025                 $to_field->delete_subfield(code => $fields{$f}{sf});
1026             } else {
1027                 $r->delete_field( $to_field );
1028             }
1029         }
1030     }
1031
1032     $xml = $r->as_xml_record;
1033     $xml =~ s/^<\?.+?\?>$//mo;
1034     $xml =~ s/\n//sgo;
1035     $xml =~ s/>\s+</></sgo;
1036
1037     return $xml;
1038
1039 $_$ LANGUAGE PLPERLU;
1040
1041 CREATE OR REPLACE FUNCTION vandelay.replace_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1042 DECLARE
1043     xml_output TEXT;
1044     parsed_target TEXT;
1045     curr_field TEXT;
1046 BEGIN
1047
1048     parsed_target := vandelay.strip_field( target_xml, ''); -- this dance normalizes the format of the xml for the IF below
1049
1050     FOR curr_field IN SELECT UNNEST( STRING_TO_ARRAY(field, ',') ) LOOP -- naive split, but it's the same we use in the perl
1051
1052         xml_output := vandelay.strip_field( parsed_target, curr_field);
1053
1054         IF xml_output <> parsed_target  AND curr_field ~ E'~' THEN
1055             -- we removed something, and there was a regexp restriction in the curr_field definition, so proceed
1056             xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 1 );
1057         ELSIF curr_field !~ E'~' THEN
1058             -- No regexp restriction, add the curr_field
1059             xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 0 );
1060         END IF;
1061
1062         parsed_target := xml_output; -- in prep for any following loop iterations
1063
1064     END LOOP;
1065
1066     RETURN xml_output;
1067 END;
1068 $_$ LANGUAGE PLPGSQL;
1069
1070 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_xml TEXT, source_xml TEXT, add_rule TEXT, replace_preserve_rule TEXT, strip_rule TEXT ) RETURNS TEXT AS $_$
1071     SELECT vandelay.replace_field( vandelay.add_field( vandelay.strip_field( $1, $5) , $2, $3 ), $2, $4);
1072 $_$ LANGUAGE SQL;
1073
1074 CREATE TYPE vandelay.compile_profile AS (add_rule TEXT, replace_rule TEXT, preserve_rule TEXT, strip_rule TEXT);
1075 CREATE OR REPLACE FUNCTION vandelay.compile_profile ( incoming_xml TEXT ) RETURNS vandelay.compile_profile AS $_$
1076 DECLARE
1077     output              vandelay.compile_profile%ROWTYPE;
1078     profile             vandelay.merge_profile%ROWTYPE;
1079     profile_tmpl        TEXT;
1080     profile_tmpl_owner  TEXT;
1081     add_rule            TEXT := '';
1082     strip_rule          TEXT := '';
1083     replace_rule        TEXT := '';
1084     preserve_rule       TEXT := '';
1085
1086 BEGIN
1087
1088     profile_tmpl := (oils_xpath('//*[@tag="905"]/*[@code="t"]/text()',incoming_xml))[1];
1089     profile_tmpl_owner := (oils_xpath('//*[@tag="905"]/*[@code="o"]/text()',incoming_xml))[1];
1090
1091     IF profile_tmpl IS NOT NULL AND profile_tmpl <> '' AND profile_tmpl_owner IS NOT NULL AND profile_tmpl_owner <> '' THEN
1092         SELECT  p.* INTO profile
1093           FROM  vandelay.merge_profile p
1094                 JOIN actor.org_unit u ON (u.id = p.owner)
1095           WHERE p.name = profile_tmpl
1096                 AND u.shortname = profile_tmpl_owner;
1097
1098         IF profile.id IS NOT NULL THEN
1099             add_rule := COALESCE(profile.add_spec,'');
1100             strip_rule := COALESCE(profile.strip_spec,'');
1101             replace_rule := COALESCE(profile.replace_spec,'');
1102             preserve_rule := COALESCE(profile.preserve_spec,'');
1103         END IF;
1104     END IF;
1105
1106     add_rule := add_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="a"]/text()',incoming_xml),','),'');
1107     strip_rule := strip_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="d"]/text()',incoming_xml),','),'');
1108     replace_rule := replace_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="r"]/text()',incoming_xml),','),'');
1109     preserve_rule := preserve_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="p"]/text()',incoming_xml),','),'');
1110
1111     output.add_rule := BTRIM(add_rule,',');
1112     output.replace_rule := BTRIM(replace_rule,',');
1113     output.strip_rule := BTRIM(strip_rule,',');
1114     output.preserve_rule := BTRIM(preserve_rule,',');
1115
1116     RETURN output;
1117 END;
1118 $_$ LANGUAGE PLPGSQL;
1119
1120 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1121 DECLARE
1122     merge_profile   vandelay.merge_profile%ROWTYPE;
1123     dyn_profile     vandelay.compile_profile%ROWTYPE;
1124     editor_string   TEXT;
1125     editor_id       INT;
1126     source_marc     TEXT;
1127     target_marc     TEXT;
1128     eg_marc         TEXT;
1129     replace_rule    TEXT;
1130     match_count     INT;
1131 BEGIN
1132
1133     SELECT  b.marc INTO eg_marc
1134       FROM  biblio.record_entry b
1135       WHERE b.id = eg_id
1136       LIMIT 1;
1137
1138     IF eg_marc IS NULL OR v_marc IS NULL THEN
1139         -- RAISE NOTICE 'no marc for template or bib record';
1140         RETURN FALSE;
1141     END IF;
1142
1143     dyn_profile := vandelay.compile_profile( v_marc );
1144
1145     IF merge_profile_id IS NOT NULL THEN
1146         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1147         IF FOUND THEN
1148             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1149             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1150             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1151             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1152         END IF;
1153     END IF;
1154
1155     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1156         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1157         RETURN FALSE;
1158     END IF;
1159
1160     IF dyn_profile.replace_rule <> '' THEN
1161         source_marc = v_marc;
1162         target_marc = eg_marc;
1163         replace_rule = dyn_profile.replace_rule;
1164     ELSE
1165         source_marc = eg_marc;
1166         target_marc = v_marc;
1167         replace_rule = dyn_profile.preserve_rule;
1168     END IF;
1169
1170     UPDATE  biblio.record_entry
1171       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1172       WHERE id = eg_id;
1173
1174     IF NOT FOUND THEN
1175         -- RAISE NOTICE 'update of biblio.record_entry failed';
1176         RETURN FALSE;
1177     END IF;
1178
1179     RETURN TRUE;
1180
1181 END;
1182 $$ LANGUAGE PLPGSQL;
1183
1184 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_marc TEXT, template_marc TEXT ) RETURNS TEXT AS $$
1185 DECLARE
1186     dyn_profile     vandelay.compile_profile%ROWTYPE;
1187     replace_rule    TEXT;
1188     tmp_marc        TEXT;
1189     trgt_marc        TEXT;
1190     tmpl_marc        TEXT;
1191     match_count     INT;
1192 BEGIN
1193
1194     IF target_marc IS NULL OR template_marc IS NULL THEN
1195         -- RAISE NOTICE 'no marc for target or template record';
1196         RETURN NULL;
1197     END IF;
1198
1199     dyn_profile := vandelay.compile_profile( template_marc );
1200
1201     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1202         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1203         RETURN NULL;
1204     END IF;
1205
1206     IF dyn_profile.replace_rule <> '' THEN
1207         trgt_marc = target_marc;
1208         tmpl_marc = template_marc;
1209         replace_rule = dyn_profile.replace_rule;
1210     ELSE
1211         tmp_marc = target_marc;
1212         trgt_marc = template_marc;
1213         tmpl_marc = tmp_marc;
1214         replace_rule = dyn_profile.preserve_rule;
1215     END IF;
1216
1217     RETURN vandelay.merge_record_xml( trgt_marc, tmpl_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
1218
1219 END;
1220 $$ LANGUAGE PLPGSQL;
1221
1222 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT) RETURNS BOOL AS $$
1223     SELECT vandelay.template_overlay_bib_record( $1, $2, NULL);
1224 $$ LANGUAGE SQL;
1225
1226 CREATE OR REPLACE FUNCTION vandelay.overlay_bib_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1227 DECLARE
1228     merge_profile   vandelay.merge_profile%ROWTYPE;
1229     dyn_profile     vandelay.compile_profile%ROWTYPE;
1230     editor_string   TEXT;
1231     editor_id       INT;
1232     source_marc     TEXT;
1233     target_marc     TEXT;
1234     eg_marc         TEXT;
1235     v_marc          TEXT;
1236     replace_rule    TEXT;
1237     match_count     INT;
1238 BEGIN
1239
1240     SELECT  q.marc INTO v_marc
1241       FROM  vandelay.queued_record q
1242             JOIN vandelay.bib_match m ON (m.queued_record = q.id AND q.id = import_id)
1243       LIMIT 1;
1244
1245     IF v_marc IS NULL THEN
1246         -- RAISE NOTICE 'no marc for vandelay or bib record';
1247         RETURN FALSE;
1248     END IF;
1249
1250     IF vandelay.template_overlay_bib_record( v_marc, eg_id, merge_profile_id) THEN
1251         UPDATE  vandelay.queued_bib_record
1252           SET   imported_as = eg_id,
1253                 import_time = NOW()
1254           WHERE id = import_id;
1255
1256         editor_string := (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
1257
1258         IF editor_string IS NOT NULL AND editor_string <> '' THEN
1259             SELECT usr INTO editor_id FROM actor.card WHERE barcode = editor_string;
1260
1261             IF editor_id IS NULL THEN
1262                 SELECT id INTO editor_id FROM actor.usr WHERE usrname = editor_string;
1263             END IF;
1264
1265             IF editor_id IS NOT NULL THEN
1266                 UPDATE biblio.record_entry SET editor = editor_id WHERE id = eg_id;
1267             END IF;
1268         END IF;
1269
1270         RETURN TRUE;
1271     END IF;
1272
1273     -- RAISE NOTICE 'update of biblio.record_entry failed';
1274
1275     RETURN FALSE;
1276
1277 END;
1278 $$ LANGUAGE PLPGSQL;
1279
1280 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1281 DECLARE
1282     eg_id           BIGINT;
1283     match_count     INT;
1284     match_attr      vandelay.bib_attr_definition%ROWTYPE;
1285 BEGIN
1286
1287     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1288
1289     IF FOUND THEN
1290         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1291         RETURN FALSE;
1292     END IF;
1293
1294     SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
1295
1296     IF match_count <> 1 THEN
1297         -- RAISE NOTICE 'not an exact match';
1298         RETURN FALSE;
1299     END IF;
1300
1301     -- Check that the one match is on the first 901c
1302     PERFORM *
1303       FROM  vandelay.queued_bib_record q
1304             JOIN vandelay.bib_match m ON (m.queued_record = q.id)
1305       WHERE q.id = import_id
1306             AND m.eg_record = oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]',marc)::BIGINT;
1307
1308     IF NOT FOUND THEN
1309         -- RAISE NOTICE 'not a 901c match: %', match_attr.xpath;
1310         RETURN FALSE;
1311     END IF;
1312
1313     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1314 END;
1315 $$ LANGUAGE PLPGSQL;
1316
1317 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1318 DECLARE
1319     queued_record   vandelay.queued_bib_record%ROWTYPE;
1320 BEGIN
1321
1322     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1323
1324         IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
1325             RETURN NEXT queued_record.id;
1326         END IF;
1327
1328     END LOOP;
1329
1330     RETURN;
1331     
1332 END;
1333 $$ LANGUAGE PLPGSQL;
1334
1335 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1336     SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
1337 $$ LANGUAGE SQL;
1338
1339 CREATE OR REPLACE FUNCTION vandelay.ingest_items ( import_id BIGINT, attr_def_id BIGINT ) RETURNS SETOF vandelay.import_item AS $$
1340 DECLARE
1341
1342     owning_lib      TEXT;
1343     circ_lib        TEXT;
1344     call_number     TEXT;
1345     copy_number     TEXT;
1346     status          TEXT;
1347     location        TEXT;
1348     circulate       TEXT;
1349     deposit         TEXT;
1350     deposit_amount  TEXT;
1351     ref             TEXT;
1352     holdable        TEXT;
1353     price           TEXT;
1354     barcode         TEXT;
1355     circ_modifier   TEXT;
1356     circ_as_type    TEXT;
1357     alert_message   TEXT;
1358     opac_visible    TEXT;
1359     pub_note        TEXT;
1360     priv_note       TEXT;
1361
1362     attr_def        RECORD;
1363     tmp_attr_set    RECORD;
1364     attr_set        vandelay.import_item%ROWTYPE;
1365
1366     xpath           TEXT;
1367
1368 BEGIN
1369
1370     SELECT * INTO attr_def FROM vandelay.import_item_attr_definition WHERE id = attr_def_id;
1371
1372     IF FOUND THEN
1373
1374         attr_set.definition := attr_def.id; 
1375     
1376         -- Build the combined XPath
1377     
1378         owning_lib :=
1379             CASE
1380                 WHEN attr_def.owning_lib IS NULL THEN 'null()'
1381                 WHEN LENGTH( attr_def.owning_lib ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.owning_lib || '"]'
1382                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.owning_lib
1383             END;
1384     
1385         circ_lib :=
1386             CASE
1387                 WHEN attr_def.circ_lib IS NULL THEN 'null()'
1388                 WHEN LENGTH( attr_def.circ_lib ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_lib || '"]'
1389                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_lib
1390             END;
1391     
1392         call_number :=
1393             CASE
1394                 WHEN attr_def.call_number IS NULL THEN 'null()'
1395                 WHEN LENGTH( attr_def.call_number ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.call_number || '"]'
1396                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.call_number
1397             END;
1398     
1399         copy_number :=
1400             CASE
1401                 WHEN attr_def.copy_number IS NULL THEN 'null()'
1402                 WHEN LENGTH( attr_def.copy_number ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.copy_number || '"]'
1403                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.copy_number
1404             END;
1405     
1406         status :=
1407             CASE
1408                 WHEN attr_def.status IS NULL THEN 'null()'
1409                 WHEN LENGTH( attr_def.status ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.status || '"]'
1410                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.status
1411             END;
1412     
1413         location :=
1414             CASE
1415                 WHEN attr_def.location IS NULL THEN 'null()'
1416                 WHEN LENGTH( attr_def.location ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.location || '"]'
1417                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.location
1418             END;
1419     
1420         circulate :=
1421             CASE
1422                 WHEN attr_def.circulate IS NULL THEN 'null()'
1423                 WHEN LENGTH( attr_def.circulate ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circulate || '"]'
1424                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circulate
1425             END;
1426     
1427         deposit :=
1428             CASE
1429                 WHEN attr_def.deposit IS NULL THEN 'null()'
1430                 WHEN LENGTH( attr_def.deposit ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.deposit || '"]'
1431                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.deposit
1432             END;
1433     
1434         deposit_amount :=
1435             CASE
1436                 WHEN attr_def.deposit_amount IS NULL THEN 'null()'
1437                 WHEN LENGTH( attr_def.deposit_amount ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.deposit_amount || '"]'
1438                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.deposit_amount
1439             END;
1440     
1441         ref :=
1442             CASE
1443                 WHEN attr_def.ref IS NULL THEN 'null()'
1444                 WHEN LENGTH( attr_def.ref ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.ref || '"]'
1445                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.ref
1446             END;
1447     
1448         holdable :=
1449             CASE
1450                 WHEN attr_def.holdable IS NULL THEN 'null()'
1451                 WHEN LENGTH( attr_def.holdable ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.holdable || '"]'
1452                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.holdable
1453             END;
1454     
1455         price :=
1456             CASE
1457                 WHEN attr_def.price IS NULL THEN 'null()'
1458                 WHEN LENGTH( attr_def.price ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.price || '"]'
1459                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.price
1460             END;
1461     
1462         barcode :=
1463             CASE
1464                 WHEN attr_def.barcode IS NULL THEN 'null()'
1465                 WHEN LENGTH( attr_def.barcode ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.barcode || '"]'
1466                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.barcode
1467             END;
1468     
1469         circ_modifier :=
1470             CASE
1471                 WHEN attr_def.circ_modifier IS NULL THEN 'null()'
1472                 WHEN LENGTH( attr_def.circ_modifier ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_modifier || '"]'
1473                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_modifier
1474             END;
1475     
1476         circ_as_type :=
1477             CASE
1478                 WHEN attr_def.circ_as_type IS NULL THEN 'null()'
1479                 WHEN LENGTH( attr_def.circ_as_type ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_as_type || '"]'
1480                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_as_type
1481             END;
1482     
1483         alert_message :=
1484             CASE
1485                 WHEN attr_def.alert_message IS NULL THEN 'null()'
1486                 WHEN LENGTH( attr_def.alert_message ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.alert_message || '"]'
1487                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.alert_message
1488             END;
1489     
1490         opac_visible :=
1491             CASE
1492                 WHEN attr_def.opac_visible IS NULL THEN 'null()'
1493                 WHEN LENGTH( attr_def.opac_visible ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.opac_visible || '"]'
1494                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.opac_visible
1495             END;
1496
1497         pub_note :=
1498             CASE
1499                 WHEN attr_def.pub_note IS NULL THEN 'null()'
1500                 WHEN LENGTH( attr_def.pub_note ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.pub_note || '"]'
1501                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.pub_note
1502             END;
1503         priv_note :=
1504             CASE
1505                 WHEN attr_def.priv_note IS NULL THEN 'null()'
1506                 WHEN LENGTH( attr_def.priv_note ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.priv_note || '"]'
1507                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.priv_note
1508             END;
1509     
1510     
1511         xpath := 
1512             owning_lib      || '|' || 
1513             circ_lib        || '|' || 
1514             call_number     || '|' || 
1515             copy_number     || '|' || 
1516             status          || '|' || 
1517             location        || '|' || 
1518             circulate       || '|' || 
1519             deposit         || '|' || 
1520             deposit_amount  || '|' || 
1521             ref             || '|' || 
1522             holdable        || '|' || 
1523             price           || '|' || 
1524             barcode         || '|' || 
1525             circ_modifier   || '|' || 
1526             circ_as_type    || '|' || 
1527             alert_message   || '|' || 
1528             pub_note        || '|' || 
1529             priv_note       || '|' || 
1530             opac_visible;
1531
1532         -- RAISE NOTICE 'XPath: %', xpath;
1533         
1534         FOR tmp_attr_set IN
1535                 SELECT  *
1536                   FROM  oils_xpath_table( 'id', 'marc', 'vandelay.queued_bib_record', xpath, 'id = ' || import_id )
1537                             AS t( id INT, ol TEXT, clib TEXT, cn TEXT, cnum TEXT, cs TEXT, cl TEXT, circ TEXT,
1538                                   dep TEXT, dep_amount TEXT, r TEXT, hold TEXT, pr TEXT, bc TEXT, circ_mod TEXT,
1539                                   circ_as TEXT, amessage TEXT, note TEXT, pnote TEXT, opac_vis TEXT )
1540         LOOP
1541     
1542             tmp_attr_set.pr = REGEXP_REPLACE(tmp_attr_set.pr, E'[^0-9\\.]', '', 'g');
1543             tmp_attr_set.dep_amount = REGEXP_REPLACE(tmp_attr_set.dep_amount, E'[^0-9\\.]', '', 'g');
1544
1545             tmp_attr_set.pr := NULLIF( tmp_attr_set.pr, '' );
1546             tmp_attr_set.dep_amount := NULLIF( tmp_attr_set.dep_amount, '' );
1547     
1548             SELECT id INTO attr_set.owning_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.ol); -- INT
1549             SELECT id INTO attr_set.circ_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.clib); -- INT
1550             SELECT id INTO attr_set.status FROM config.copy_status WHERE LOWER(name) = LOWER(tmp_attr_set.cs); -- INT
1551     
1552             SELECT  id INTO attr_set.location
1553               FROM  asset.copy_location
1554               WHERE LOWER(name) = LOWER(tmp_attr_set.cl)
1555                     AND asset.copy_location.owning_lib = COALESCE(attr_set.owning_lib, attr_set.circ_lib); -- INT
1556     
1557             attr_set.circulate      :=
1558                 LOWER( SUBSTRING( tmp_attr_set.circ, 1, 1)) IN ('t','y','1')
1559                 OR LOWER(tmp_attr_set.circ) = 'circulating'; -- BOOL
1560
1561             attr_set.deposit        :=
1562                 LOWER( SUBSTRING( tmp_attr_set.dep, 1, 1 ) ) IN ('t','y','1')
1563                 OR LOWER(tmp_attr_set.dep) = 'deposit'; -- BOOL
1564
1565             attr_set.holdable       :=
1566                 LOWER( SUBSTRING( tmp_attr_set.hold, 1, 1 ) ) IN ('t','y','1')
1567                 OR LOWER(tmp_attr_set.hold) = 'holdable'; -- BOOL
1568
1569             attr_set.opac_visible   :=
1570                 LOWER( SUBSTRING( tmp_attr_set.opac_vis, 1, 1 ) ) IN ('t','y','1')
1571                 OR LOWER(tmp_attr_set.opac_vis) = 'visible'; -- BOOL
1572
1573             attr_set.ref            :=
1574                 LOWER( SUBSTRING( tmp_attr_set.r, 1, 1 ) ) IN ('t','y','1')
1575                 OR LOWER(tmp_attr_set.r) = 'reference'; -- BOOL
1576     
1577             attr_set.copy_number    := tmp_attr_set.cnum::INT; -- INT,
1578             attr_set.deposit_amount := tmp_attr_set.dep_amount::NUMERIC(6,2); -- NUMERIC(6,2),
1579             attr_set.price          := tmp_attr_set.pr::NUMERIC(8,2); -- NUMERIC(8,2),
1580     
1581             attr_set.call_number    := tmp_attr_set.cn; -- TEXT
1582             attr_set.barcode        := tmp_attr_set.bc; -- TEXT,
1583             attr_set.circ_modifier  := tmp_attr_set.circ_mod; -- TEXT,
1584             attr_set.circ_as_type   := tmp_attr_set.circ_as; -- TEXT,
1585             attr_set.alert_message  := tmp_attr_set.amessage; -- TEXT,
1586             attr_set.pub_note       := tmp_attr_set.note; -- TEXT,
1587             attr_set.priv_note      := tmp_attr_set.pnote; -- TEXT,
1588             attr_set.alert_message  := tmp_attr_set.amessage; -- TEXT,
1589     
1590             RETURN NEXT attr_set;
1591     
1592         END LOOP;
1593     
1594     END IF;
1595
1596     RETURN;
1597
1598 END;
1599 $$ LANGUAGE PLPGSQL;
1600
1601
1602 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_marc ( ) RETURNS TRIGGER AS $$
1603 DECLARE
1604     value   TEXT;
1605     atype   TEXT;
1606     adef    RECORD;
1607 BEGIN
1608     FOR adef IN SELECT * FROM vandelay.bib_attr_definition LOOP
1609
1610         SELECT extract_marc_field('vandelay.queued_bib_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_bib_record WHERE id = NEW.id;
1611         IF (value IS NOT NULL AND value <> '') THEN
1612             INSERT INTO vandelay.queued_bib_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1613         END IF;
1614
1615     END LOOP;
1616
1617     RETURN NULL;
1618 END;
1619 $$ LANGUAGE PLPGSQL;
1620
1621 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_items ( ) RETURNS TRIGGER AS $func$
1622 DECLARE
1623     attr_def    BIGINT;
1624     item_data   vandelay.import_item%ROWTYPE;
1625 BEGIN
1626
1627     SELECT item_attr_def INTO attr_def FROM vandelay.bib_queue WHERE id = NEW.queue;
1628
1629     FOR item_data IN SELECT * FROM vandelay.ingest_items( NEW.id::BIGINT, attr_def ) LOOP
1630         INSERT INTO vandelay.import_item (
1631             record,
1632             definition,
1633             owning_lib,
1634             circ_lib,
1635             call_number,
1636             copy_number,
1637             status,
1638             location,
1639             circulate,
1640             deposit,
1641             deposit_amount,
1642             ref,
1643             holdable,
1644             price,
1645             barcode,
1646             circ_modifier,
1647             circ_as_type,
1648             alert_message,
1649             pub_note,
1650             priv_note,
1651             opac_visible
1652         ) VALUES (
1653             NEW.id,
1654             item_data.definition,
1655             item_data.owning_lib,
1656             item_data.circ_lib,
1657             item_data.call_number,
1658             item_data.copy_number,
1659             item_data.status,
1660             item_data.location,
1661             item_data.circulate,
1662             item_data.deposit,
1663             item_data.deposit_amount,
1664             item_data.ref,
1665             item_data.holdable,
1666             item_data.price,
1667             item_data.barcode,
1668             item_data.circ_modifier,
1669             item_data.circ_as_type,
1670             item_data.alert_message,
1671             item_data.pub_note,
1672             item_data.priv_note,
1673             item_data.opac_visible
1674         );
1675     END LOOP;
1676
1677     RETURN NULL;
1678 END;
1679 $func$ LANGUAGE PLPGSQL;
1680
1681 CREATE OR REPLACE FUNCTION vandelay.match_bib_record ( ) RETURNS TRIGGER AS $func$
1682 DECLARE
1683     attr        RECORD;
1684     attr_def    RECORD;
1685     eg_rec      RECORD;
1686     id_value    TEXT;
1687     exact_id    BIGINT;
1688 BEGIN
1689
1690     DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
1691
1692     SELECT * INTO attr_def FROM vandelay.bib_attr_definition WHERE xpath = '//*[@tag="901"]/*[@code="c"]' ORDER BY id LIMIT 1;
1693
1694     IF attr_def IS NOT NULL AND attr_def.id IS NOT NULL THEN
1695         id_value := extract_marc_field('vandelay.queued_bib_record', NEW.id, attr_def.xpath, attr_def.remove);
1696     
1697         IF id_value IS NOT NULL AND id_value <> '' AND id_value ~ $r$^\d+$$r$ THEN
1698             SELECT id INTO exact_id FROM biblio.record_entry WHERE id = id_value::BIGINT AND NOT deleted;
1699             SELECT * INTO attr FROM vandelay.queued_bib_record_attr WHERE record = NEW.id and field = attr_def.id LIMIT 1;
1700             IF exact_id IS NOT NULL THEN
1701                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, exact_id);
1702             END IF;
1703         END IF;
1704     END IF;
1705
1706     IF exact_id IS NULL THEN
1707         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
1708     
1709                 -- All numbers? check for an id match
1710                 IF (attr.attr_value ~ $r$^\d+$$r$) THEN
1711                 FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE id = attr.attr_value::BIGINT AND deleted IS FALSE LOOP
1712                         INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, eg_rec.id);
1713                         END LOOP;
1714                 END IF;
1715     
1716                 -- Looks like an ISBN? check for an isbn match
1717                 IF (attr.attr_value ~* $r$^[0-9x]+$$r$ AND character_length(attr.attr_value) IN (10,13)) THEN
1718                 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
1719                                 PERFORM id FROM biblio.record_entry WHERE id = eg_rec.record AND deleted IS FALSE;
1720                                 IF FOUND THEN
1721                                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('isbn', attr.id, NEW.id, eg_rec.record);
1722                                 END IF;
1723                         END LOOP;
1724     
1725                         -- subcheck for isbn-as-tcn
1726                     FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = 'i' || attr.attr_value AND deleted IS FALSE LOOP
1727                             INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
1728                 END LOOP;
1729                 END IF;
1730     
1731                 -- check for an OCLC tcn_value match
1732                 IF (attr.attr_value ~ $r$^o\d+$$r$) THEN
1733                     FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = regexp_replace(attr.attr_value,'^o','ocm') AND deleted IS FALSE LOOP
1734                             INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
1735                 END LOOP;
1736                 END IF;
1737     
1738                 -- check for a direct tcn_value match
1739             FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = attr.attr_value AND deleted IS FALSE LOOP
1740                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
1741             END LOOP;
1742     
1743                 -- check for a direct item barcode match
1744             FOR eg_rec IN
1745                     SELECT  DISTINCT b.*
1746                       FROM  biblio.record_entry b
1747                             JOIN asset.call_number cn ON (cn.record = b.id)
1748                             JOIN asset.copy cp ON (cp.call_number = cn.id)
1749                       WHERE cp.barcode = attr.attr_value AND cp.deleted IS FALSE
1750             LOOP
1751                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, eg_rec.id);
1752             END LOOP;
1753     
1754         END LOOP;
1755     END IF;
1756
1757     RETURN NULL;
1758 END;
1759 $func$ LANGUAGE PLPGSQL;
1760
1761 CREATE OR REPLACE FUNCTION vandelay.cleanup_bib_marc ( ) RETURNS TRIGGER AS $$
1762 BEGIN
1763     DELETE FROM vandelay.queued_bib_record_attr WHERE record = OLD.id;
1764     DELETE FROM vandelay.import_item WHERE record = OLD.id;
1765
1766     IF TG_OP = 'UPDATE' THEN
1767         RETURN NEW;
1768     END IF;
1769     RETURN OLD;
1770 END;
1771 $$ LANGUAGE PLPGSQL;
1772
1773 CREATE TRIGGER cleanup_bib_trigger
1774     BEFORE UPDATE OR DELETE ON vandelay.queued_bib_record
1775     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_bib_marc();
1776
1777 CREATE TRIGGER ingest_bib_trigger
1778     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1779     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_marc();
1780
1781 CREATE TRIGGER ingest_item_trigger
1782     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1783     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_items();
1784
1785 CREATE TRIGGER zz_match_bibs_trigger
1786     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1787     FOR EACH ROW EXECUTE PROCEDURE vandelay.match_bib_record();
1788
1789
1790 /* Authority stuff down here */
1791 ---------------------------------------
1792 CREATE TABLE vandelay.authority_attr_definition (
1793         id                      SERIAL  PRIMARY KEY,
1794         code            TEXT    UNIQUE NOT NULL,
1795         description     TEXT,
1796         xpath           TEXT    NOT NULL,
1797         remove          TEXT    NOT NULL DEFAULT ''
1798 );
1799
1800 CREATE TABLE vandelay.authority_queue (
1801         queue_type      TEXT            NOT NULL DEFAULT 'authority' CHECK (queue_type = 'authority'),
1802         CONSTRAINT vand_authority_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
1803 ) INHERITS (vandelay.queue);
1804 ALTER TABLE vandelay.authority_queue ADD PRIMARY KEY (id);
1805
1806 CREATE TABLE vandelay.queued_authority_record (
1807         queue           INT     NOT NULL REFERENCES vandelay.authority_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1808         imported_as     INT     REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1809         import_error    TEXT    REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
1810         error_detail    TEXT
1811 ) INHERITS (vandelay.queued_record);
1812 ALTER TABLE vandelay.queued_authority_record ADD PRIMARY KEY (id);
1813 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
1814
1815 CREATE TABLE vandelay.queued_authority_record_attr (
1816         id                      BIGSERIAL       PRIMARY KEY,
1817         record          BIGINT          NOT NULL REFERENCES vandelay.queued_authority_record (id) DEFERRABLE INITIALLY DEFERRED,
1818         field           INT                     NOT NULL REFERENCES vandelay.authority_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
1819         attr_value      TEXT            NOT NULL
1820 );
1821 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
1822
1823 CREATE TABLE vandelay.authority_match (
1824         id                              BIGSERIAL       PRIMARY KEY,
1825         matched_set     INT                     REFERENCES vandelay.match_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1826         queued_record   BIGINT          REFERENCES vandelay.queued_authority_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1827         eg_record               BIGINT          REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1828     quality         INT         NOT NULL DEFAULT 0
1829 );
1830
1831 CREATE OR REPLACE FUNCTION vandelay.ingest_authority_marc ( ) RETURNS TRIGGER AS $$
1832 DECLARE
1833     value   TEXT;
1834     atype   TEXT;
1835     adef    RECORD;
1836 BEGIN
1837     FOR adef IN SELECT * FROM vandelay.authority_attr_definition LOOP
1838
1839         SELECT extract_marc_field('vandelay.queued_authority_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_authority_record WHERE id = NEW.id;
1840         IF (value IS NOT NULL AND value <> '') THEN
1841             INSERT INTO vandelay.queued_authority_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1842         END IF;
1843
1844     END LOOP;
1845
1846     RETURN NULL;
1847 END;
1848 $$ LANGUAGE PLPGSQL;
1849
1850 CREATE OR REPLACE FUNCTION vandelay.cleanup_authority_marc ( ) RETURNS TRIGGER AS $$
1851 BEGIN
1852     DELETE FROM vandelay.queued_authority_record_attr WHERE record = OLD.id;
1853     IF TG_OP = 'UPDATE' THEN
1854         RETURN NEW;
1855     END IF;
1856     RETURN OLD;
1857 END;
1858 $$ LANGUAGE PLPGSQL;
1859
1860 CREATE TRIGGER cleanup_authority_trigger
1861     BEFORE UPDATE OR DELETE ON vandelay.queued_authority_record
1862     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_authority_marc();
1863
1864 CREATE TRIGGER ingest_authority_trigger
1865     AFTER INSERT OR UPDATE ON vandelay.queued_authority_record
1866     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_authority_marc();
1867
1868 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1869 DECLARE
1870     merge_profile   vandelay.merge_profile%ROWTYPE;
1871     dyn_profile     vandelay.compile_profile%ROWTYPE;
1872     source_marc     TEXT;
1873     target_marc     TEXT;
1874     eg_marc         TEXT;
1875     v_marc          TEXT;
1876     replace_rule    TEXT;
1877     match_count     INT;
1878 BEGIN
1879
1880     SELECT  b.marc INTO eg_marc
1881       FROM  authority.record_entry b
1882             JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
1883       LIMIT 1;
1884
1885     SELECT  q.marc INTO v_marc
1886       FROM  vandelay.queued_record q
1887             JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
1888       LIMIT 1;
1889
1890     IF eg_marc IS NULL OR v_marc IS NULL THEN
1891         -- RAISE NOTICE 'no marc for vandelay or authority record';
1892         RETURN FALSE;
1893     END IF;
1894
1895     dyn_profile := vandelay.compile_profile( v_marc );
1896
1897     IF merge_profile_id IS NOT NULL THEN
1898         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1899         IF FOUND THEN
1900             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1901             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1902             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1903             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1904         END IF;
1905     END IF;
1906
1907     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1908         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1909         RETURN FALSE;
1910     END IF;
1911
1912     IF dyn_profile.replace_rule <> '' THEN
1913         source_marc = v_marc;
1914         target_marc = eg_marc;
1915         replace_rule = dyn_profile.replace_rule;
1916     ELSE
1917         source_marc = eg_marc;
1918         target_marc = v_marc;
1919         replace_rule = dyn_profile.preserve_rule;
1920     END IF;
1921
1922     UPDATE  authority.record_entry
1923       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1924       WHERE id = eg_id;
1925
1926     IF FOUND THEN
1927         UPDATE  vandelay.queued_authority_record
1928           SET   imported_as = eg_id,
1929                 import_time = NOW()
1930           WHERE id = import_id;
1931         RETURN TRUE;
1932     END IF;
1933
1934     -- RAISE NOTICE 'update of authority.record_entry failed';
1935
1936     RETURN FALSE;
1937
1938 END;
1939 $$ LANGUAGE PLPGSQL;
1940
1941 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1942 DECLARE
1943     eg_id           BIGINT;
1944     match_count     INT;
1945 BEGIN
1946     SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
1947
1948     IF match_count <> 1 THEN
1949         -- RAISE NOTICE 'not an exact match';
1950         RETURN FALSE;
1951     END IF;
1952
1953     SELECT  m.eg_record INTO eg_id
1954       FROM  vandelay.authority_match m
1955       WHERE m.queued_record = import_id
1956       LIMIT 1;
1957
1958     IF eg_id IS NULL THEN
1959         RETURN FALSE;
1960     END IF;
1961
1962     RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
1963 END;
1964 $$ LANGUAGE PLPGSQL;
1965
1966 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1967 DECLARE
1968     queued_record   vandelay.queued_authority_record%ROWTYPE;
1969 BEGIN
1970
1971     FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
1972
1973         IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
1974             RETURN NEXT queued_record.id;
1975         END IF;
1976
1977     END LOOP;
1978
1979     RETURN;
1980     
1981 END;
1982 $$ LANGUAGE PLPGSQL;
1983
1984 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1985     SELECT * FROM vandelay.auto_overlay_authority_queue( $1, NULL );
1986 $$ LANGUAGE SQL;
1987
1988
1989 -- Vandelay (for importing and exporting records) 012.schema.vandelay.sql 
1990 --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)]');
1991 --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)]');
1992 --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]');
1993 --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]');
1994 --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$);
1995 --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$);
1996 --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]');
1997 --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);
1998 --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);
1999 --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);
2000 --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);
2001 --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]');
2002 --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$);
2003 --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]');
2004 --
2005 --INSERT INTO vandelay.import_item_attr_definition (
2006 --    owner, name, tag, owning_lib, circ_lib, location,
2007 --    call_number, circ_modifier, barcode, price, copy_number,
2008 --    circulate, ref, holdable, opac_visible, status
2009 --) VALUES (
2010 --    1,
2011 --    'Evergreen 852 export format',
2012 --    '852',
2013 --    '[@code = "b"][1]',
2014 --    '[@code = "b"][2]',
2015 --    'c',
2016 --    'j',
2017 --    'g',
2018 --    'p',
2019 --    'y',
2020 --    't',
2021 --    '[@code = "x" and text() = "circulating"]',
2022 --    '[@code = "x" and text() = "reference"]',
2023 --    '[@code = "x" and text() = "holdable"]',
2024 --    '[@code = "x" and text() = "visible"]',
2025 --    'z'
2026 --);
2027 --
2028 --INSERT INTO vandelay.import_item_attr_definition (
2029 --    owner,
2030 --    name,
2031 --    tag,
2032 --    owning_lib,
2033 --    location,
2034 --    call_number,
2035 --    circ_modifier,
2036 --    barcode,
2037 --    price,
2038 --    status
2039 --) VALUES (
2040 --    1,
2041 --    'Unicorn Import format -- 999',
2042 --    '999',
2043 --    'm',
2044 --    'l',
2045 --    'a',
2046 --    't',
2047 --    'i',
2048 --    'p',
2049 --    'k'
2050 --);
2051 --
2052 --INSERT INTO vandelay.authority_attr_definition ( code, description, xpath, ident ) VALUES ('rec_identifier','Identifier','//*[@tag="001"]', TRUE);
2053
2054 COMMIT;
2055