]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/012.schema.vandelay.sql
match_score column for recording matchiness; functions for auto-overlay based on...
[Evergreen.git] / Open-ILS / src / sql / Pg / 012.schema.vandelay.sql
1 DROP SCHEMA IF EXISTS vandelay CASCADE;
2
3 BEGIN;
4
5 CREATE SCHEMA vandelay;
6
7 CREATE TABLE vandelay.match_set (
8     id      SERIAL  PRIMARY KEY,
9     name    TEXT        NOT NULL,
10     owner   INT     NOT NULL REFERENCES actor.org_unit (id) ON DELETE CASCADE,
11     mtype   TEXT        NOT NULL DEFAULT 'biblio', -- 'biblio','authority','mfhd'?, others?
12     CONSTRAINT name_once_per_owner_mtype UNIQUE (name, owner, mtype)
13 );
14
15 -- Table to define match points, either FF via SVF or tag+subfield
16 CREATE TABLE vandelay.match_set_point (
17     id          SERIAL  PRIMARY KEY,
18     match_set   INT     REFERENCES vandelay.match_set (id),
19     parent      INT     REFERENCES vandelay.match_set_point (id),
20     bool_op     TEXT    CHECK (bool_op IS NULL OR (bool_op IN ('AND','OR','NOT'))),
21     svf         TEXT    REFERENCES config.record_attr_definition (name),
22     tag         TEXT,
23     subfield    TEXT,
24     negate      BOOL    DEFAULT FALSE,
25     quality     INT     NOT NULL DEFAULT 1, -- higher is better
26     CONSTRAINT vmsp_need_a_subfield_with_a_tag CHECK ((tag IS NOT NULL AND subfield IS NOT NULL) OR tag IS NULL),
27     CONSTRAINT vmsp_need_a_tag_or_a_ff_or_a_bo CHECK (
28         (tag IS NOT NULL AND svf IS NULL AND bool_op IS NULL) OR
29         (tag IS NULL AND svf IS NOT NULL AND bool_op IS NULL) OR
30         (tag IS NULL AND svf IS NULL AND bool_op IS NOT NULL)
31     )
32 );
33
34 CREATE TABLE vandelay.match_set_quality (
35     id          SERIAL  PRIMARY KEY,
36     match_set   INT     NOT NULL REFERENCES vandelay.match_set (id),
37     svf         TEXT    REFERENCES config.record_attr_definition,
38     tag         TEXT,
39     subfield    TEXT,
40     value       TEXT    NOT NULL,
41     quality     INT     NOT NULL DEFAULT 1, -- higher is better
42     CONSTRAINT vmsq_need_a_subfield_with_a_tag CHECK ((tag IS NOT NULL AND subfield IS NOT NULL) OR tag IS NULL),
43     CONSTRAINT vmsq_need_a_tag_or_a_ff CHECK ((tag IS NOT NULL AND svf IS NULL) OR (tag IS NULL AND svf IS NOT NULL))
44 );
45 CREATE UNIQUE INDEX vmsq_def_once_per_set ON vandelay.match_set_quality (match_set, COALESCE(tag,''), COALESCE(subfield,''), COALESCE(svf,''));
46
47
48 CREATE TABLE vandelay.queue (
49         id                              BIGSERIAL       PRIMARY KEY,
50         owner                   INT                     NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
51         name                    TEXT            NOT NULL,
52         complete                BOOL            NOT NULL DEFAULT FALSE,
53         queue_type              TEXT            NOT NULL DEFAULT 'bib' CHECK (queue_type IN ('bib','authority')),
54     match_set       INT         REFERENCES vandelay.match_set (id) ON UPDATE CASCADE ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
55         CONSTRAINT vand_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
56 );
57
58 CREATE TABLE vandelay.queued_record (
59     id                  BIGSERIAL                   PRIMARY KEY,
60     create_time TIMESTAMP WITH TIME ZONE    NOT NULL DEFAULT NOW(),
61     import_time TIMESTAMP WITH TIME ZONE,
62         purpose         TEXT                                            NOT NULL DEFAULT 'import' CHECK (purpose IN ('import','overlay')),
63     marc                TEXT                        NOT NULL,
64     quality     INT                         NOT NULL DEFAULT 0
65 );
66
67
68
69 /* Bib stuff at the top */
70 ----------------------------------------------------
71
72 CREATE TABLE vandelay.bib_attr_definition (
73         id                      SERIAL  PRIMARY KEY,
74         code            TEXT    UNIQUE NOT NULL,
75         description     TEXT,
76         xpath           TEXT    NOT NULL,
77         remove          TEXT    NOT NULL DEFAULT ''
78 );
79
80 -- Each TEXT field (other than 'name') should hold an XPath predicate for pulling the data needed
81 -- DROP TABLE vandelay.import_item_attr_definition CASCADE;
82 CREATE TABLE vandelay.import_item_attr_definition (
83     id              BIGSERIAL   PRIMARY KEY,
84     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
85     name            TEXT        NOT NULL,
86     tag             TEXT        NOT NULL,
87     keep            BOOL        NOT NULL DEFAULT FALSE,
88     owning_lib      TEXT,
89     circ_lib        TEXT,
90     call_number     TEXT,
91     copy_number     TEXT,
92     status          TEXT,
93     location        TEXT,
94     circulate       TEXT,
95     deposit         TEXT,
96     deposit_amount  TEXT,
97     ref             TEXT,
98     holdable        TEXT,
99     price           TEXT,
100     barcode         TEXT,
101     circ_modifier   TEXT,
102     circ_as_type    TEXT,
103     alert_message   TEXT,
104     opac_visible    TEXT,
105     pub_note_title  TEXT,
106     pub_note        TEXT,
107     priv_note_title TEXT,
108     priv_note       TEXT,
109         CONSTRAINT vand_import_item_attr_def_idx UNIQUE (owner,name)
110 );
111
112 CREATE TABLE vandelay.import_error (
113     code        TEXT    PRIMARY KEY,
114     description TEXT    NOT NULL -- i18n
115 );
116
117 CREATE TABLE vandelay.bib_queue (
118         queue_type          TEXT        NOT NULL DEFAULT 'bib' CHECK (queue_type = 'bib'),
119         item_attr_def   BIGINT REFERENCES vandelay.import_item_attr_definition (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
120         CONSTRAINT vand_bib_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
121 ) INHERITS (vandelay.queue);
122 ALTER TABLE vandelay.bib_queue ADD PRIMARY KEY (id);
123
124 CREATE TABLE vandelay.queued_bib_record (
125         queue               INT         NOT NULL REFERENCES vandelay.bib_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
126         bib_source          INT         REFERENCES config.bib_source (id) DEFERRABLE INITIALLY DEFERRED,
127         imported_as     BIGINT  REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
128         import_error    TEXT    REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
129         error_detail    TEXT
130 ) INHERITS (vandelay.queued_record);
131 ALTER TABLE vandelay.queued_bib_record ADD PRIMARY KEY (id);
132 CREATE INDEX queued_bib_record_queue_idx ON vandelay.queued_bib_record (queue);
133
134 CREATE TABLE vandelay.queued_bib_record_attr (
135         id                      BIGSERIAL       PRIMARY KEY,
136         record          BIGINT          NOT NULL REFERENCES vandelay.queued_bib_record (id) DEFERRABLE INITIALLY DEFERRED,
137         field           INT                     NOT NULL REFERENCES vandelay.bib_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
138         attr_value      TEXT            NOT NULL
139 );
140 CREATE INDEX queued_bib_record_attr_record_idx ON vandelay.queued_bib_record_attr (record);
141
142 CREATE TABLE vandelay.bib_match (
143         id                              BIGSERIAL       PRIMARY KEY,
144         matched_set     INT                     REFERENCES vandelay.match_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
145         queued_record   BIGINT          REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
146         eg_record               BIGINT          REFERENCES biblio.record_entry (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
147     quality         INT         NOT NULL DEFAULT 0,
148     match_score     INT         NOT NULL DEFAULT 0
149 );
150
151 CREATE TABLE vandelay.import_item (
152     id              BIGSERIAL   PRIMARY KEY,
153     record          BIGINT      NOT NULL REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
154     definition      BIGINT      NOT NULL REFERENCES vandelay.import_item_attr_definition (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
155         import_error    TEXT        REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
156         error_detail    TEXT,
157     owning_lib      INT,
158     circ_lib        INT,
159     call_number     TEXT,
160     copy_number     INT,
161     status          INT,
162     location        INT,
163     circulate       BOOL,
164     deposit         BOOL,
165     deposit_amount  NUMERIC(8,2),
166     ref             BOOL,
167     holdable        BOOL,
168     price           NUMERIC(8,2),
169     barcode         TEXT,
170     circ_modifier   TEXT,
171     circ_as_type    TEXT,
172     alert_message   TEXT,
173     pub_note        TEXT,
174     priv_note       TEXT,
175     opac_visible    BOOL
176 );
177  
178 CREATE TABLE vandelay.import_bib_trash_fields (
179     id              BIGSERIAL   PRIMARY KEY,
180     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
181     field           TEXT        NOT NULL,
182         CONSTRAINT vand_import_bib_trash_fields_idx UNIQUE (owner,field)
183 );
184
185 CREATE TABLE vandelay.merge_profile (
186     id              BIGSERIAL   PRIMARY KEY,
187     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
188     name            TEXT        NOT NULL,
189     add_spec        TEXT,
190     replace_spec    TEXT,
191     strip_spec      TEXT,
192     preserve_spec   TEXT,
193     lwm_ratio       NUMERIC,
194         CONSTRAINT vand_merge_prof_owner_name_idx UNIQUE (owner,name),
195         CONSTRAINT add_replace_strip_or_preserve CHECK ((preserve_spec IS NOT NULL OR replace_spec IS NOT NULL) OR (preserve_spec IS NULL AND replace_spec IS NULL))
196 );
197
198 CREATE OR REPLACE FUNCTION vandelay.marc21_record_type( marc TEXT ) RETURNS config.marc21_rec_type_map AS $func$
199 DECLARE
200     ldr         TEXT;
201     tval        TEXT;
202     tval_rec    RECORD;
203     bval        TEXT;
204     bval_rec    RECORD;
205     retval      config.marc21_rec_type_map%ROWTYPE;
206 BEGIN
207     ldr := oils_xpath_string( '//*[local-name()="leader"]', marc );
208
209     IF ldr IS NULL OR ldr = '' THEN
210         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
211         RETURN retval;
212     END IF;
213
214     SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
215     SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
216
217
218     tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
219     bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
220
221     -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
222
223     SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
224
225
226     IF retval.code IS NULL THEN
227         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
228     END IF;
229
230     RETURN retval;
231 END;
232 $func$ LANGUAGE PLPGSQL;
233
234 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field( marc TEXT, ff TEXT ) RETURNS TEXT AS $func$
235 DECLARE
236     rtype       TEXT;
237     ff_pos      RECORD;
238     tag_data    RECORD;
239     val         TEXT;
240 BEGIN
241     rtype := (vandelay.marc21_record_type( marc )).code;
242     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
243         FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
244             val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
245             RETURN val;
246         END LOOP;
247         val := REPEAT( ff_pos.default_val, ff_pos.length );
248         RETURN val;
249     END LOOP;
250
251     RETURN NULL;
252 END;
253 $func$ LANGUAGE PLPGSQL;
254
255 CREATE TYPE biblio.record_ff_map AS (record BIGINT, ff_name TEXT, ff_value TEXT);
256 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_all_fixed_fields( marc TEXT ) RETURNS SETOF biblio.record_ff_map AS $func$
257 DECLARE
258     tag_data    TEXT;
259     rtype       TEXT;
260     ff_pos      RECORD;
261     output      biblio.record_ff_map%ROWTYPE;
262 BEGIN
263     rtype := (vandelay.marc21_record_type( marc )).code;
264
265     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE rec_type = rtype ORDER BY tag DESC LOOP
266         output.ff_name  := ff_pos.fixed_field;
267         output.ff_value := NULL;
268
269         FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(tag) || '"]/text()', marc ) ) x(value) LOOP
270             output.ff_value := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
271             IF output.ff_value IS NULL THEN output.ff_value := REPEAT( ff_pos.default_val, ff_pos.length ); END IF;
272             RETURN NEXT output;
273             output.ff_value := NULL;
274         END LOOP;
275
276     END LOOP;
277
278     RETURN;
279 END;
280 $func$ LANGUAGE PLPGSQL;
281
282 CREATE TYPE biblio.marc21_physical_characteristics AS ( id INT, record BIGINT, ptype TEXT, subfield INT, value INT );
283 CREATE OR REPLACE FUNCTION vandelay.marc21_physical_characteristics( marc TEXT) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
284 DECLARE
285     rowid   INT := 0;
286     _007    TEXT;
287     ptype   config.marc21_physical_characteristic_type_map%ROWTYPE;
288     psf     config.marc21_physical_characteristic_subfield_map%ROWTYPE;
289     pval    config.marc21_physical_characteristic_value_map%ROWTYPE;
290     retval  biblio.marc21_physical_characteristics%ROWTYPE;
291 BEGIN
292
293     _007 := oils_xpath_string( '//*[@tag="007"]', marc );
294
295     IF _007 IS NOT NULL AND _007 <> '' THEN
296         SELECT * INTO ptype FROM config.marc21_physical_characteristic_type_map WHERE ptype_key = SUBSTRING( _007, 1, 1 );
297
298         IF ptype.ptype_key IS NOT NULL THEN
299             FOR psf IN SELECT * FROM config.marc21_physical_characteristic_subfield_map WHERE ptype_key = ptype.ptype_key LOOP
300                 SELECT * INTO pval FROM config.marc21_physical_characteristic_value_map WHERE ptype_subfield = psf.id AND value = SUBSTRING( _007, psf.start_pos + 1, psf.length );
301
302                 IF pval.id IS NOT NULL THEN
303                     rowid := rowid + 1;
304                     retval.id := rowid;
305                     retval.ptype := ptype.ptype_key;
306                     retval.subfield := psf.id;
307                     retval.value := pval.id;
308                     RETURN NEXT retval;
309                 END IF;
310
311             END LOOP;
312         END IF;
313     END IF;
314
315     RETURN;
316 END;
317 $func$ LANGUAGE PLPGSQL;
318
319 CREATE TYPE vandelay.flat_marc AS ( tag CHAR(3), ind1 TEXT, ind2 TEXT, subfield TEXT, value TEXT );
320 CREATE OR REPLACE FUNCTION vandelay.flay_marc ( TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
321
322 use MARC::Record;
323 use MARC::File::XML (BinaryEncoding => 'UTF-8');
324
325 my $xml = shift;
326 my $r = MARC::Record->new_from_xml( $xml );
327
328 return_next( { tag => 'LDR', value => $r->leader } );
329
330 for my $f ( $r->fields ) {
331     if ($f->is_control_field) {
332         return_next({ tag => $f->tag, value => $f->data });
333     } else {
334         for my $s ($f->subfields) {
335             return_next({
336                 tag      => $f->tag,
337                 ind1     => $f->indicator(1),
338                 ind2     => $f->indicator(2),
339                 subfield => $s->[0],
340                 value    => $s->[1]
341             });
342
343             if ( $f->tag eq '245' and $s->[0] eq 'a' ) {
344                 my $trim = $f->indicator(2) || 0;
345                 return_next({
346                     tag      => 'tnf',
347                     ind1     => $f->indicator(1),
348                     ind2     => $f->indicator(2),
349                     subfield => 'a',
350                     value    => substr( $s->[1], $trim )
351                 });
352             }
353         }
354     }
355 }
356
357 return undef;
358
359 $func$ LANGUAGE PLPERLU;
360
361 CREATE OR REPLACE FUNCTION vandelay.flatten_marc ( marc TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
362 DECLARE
363     output  vandelay.flat_marc%ROWTYPE;
364     field   RECORD;
365 BEGIN
366     FOR field IN SELECT * FROM vandelay.flay_marc( marc ) LOOP
367         output.ind1 := field.ind1;
368         output.ind2 := field.ind2;
369         output.tag := field.tag;
370         output.subfield := field.subfield;
371         IF field.subfield IS NOT NULL AND field.tag NOT IN ('020','022','024') THEN -- exclude standard numbers and control fields
372             output.value := naco_normalize(field.value, field.subfield);
373         ELSE
374             output.value := field.value;
375         END IF;
376
377         CONTINUE WHEN output.value IS NULL;
378
379         RETURN NEXT output;
380     END LOOP;
381 END;
382 $func$ LANGUAGE PLPGSQL;
383
384 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT, attr_defs TEXT[]) RETURNS hstore AS $_$
385 DECLARE
386     transformed_xml TEXT;
387     prev_xfrm       TEXT;
388     normalizer      RECORD;
389     xfrm            config.xml_transform%ROWTYPE;
390     attr_value      TEXT;
391     new_attrs       HSTORE := ''::HSTORE;
392     attr_def        config.record_attr_definition%ROWTYPE;
393 BEGIN
394
395     FOR attr_def IN SELECT * FROM config.record_attr_definition WHERE name IN (SELECT * FROM UNNEST(attr_defs)) ORDER BY format LOOP
396
397         IF attr_def.tag IS NOT NULL THEN -- tag (and optional subfield list) selection
398             SELECT  ARRAY_TO_STRING(ARRAY_ACCUM(x.value), COALESCE(attr_def.joiner,' ')) INTO attr_value
399               FROM  vandelay.flatten_marc(xml) AS x
400               WHERE x.tag LIKE attr_def.tag
401                     AND CASE
402                         WHEN attr_def.sf_list IS NOT NULL
403                             THEN POSITION(x.subfield IN attr_def.sf_list) > 0
404                         ELSE TRUE
405                         END
406               GROUP BY x.tag
407               ORDER BY x.tag
408               LIMIT 1;
409
410         ELSIF attr_def.fixed_field IS NOT NULL THEN -- a named fixed field, see config.marc21_ff_pos_map.fixed_field
411             attr_value := vandelay.marc21_extract_fixed_field(xml, attr_def.fixed_field);
412
413         ELSIF attr_def.xpath IS NOT NULL THEN -- and xpath expression
414
415             SELECT INTO xfrm * FROM config.xml_transform WHERE name = attr_def.format;
416
417             -- See if we can skip the XSLT ... it's expensive
418             IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
419                 -- Can't skip the transform
420                 IF xfrm.xslt <> '---' THEN
421                     transformed_xml := oils_xslt_process(xml,xfrm.xslt);
422                 ELSE
423                     transformed_xml := xml;
424                 END IF;
425
426                 prev_xfrm := xfrm.name;
427             END IF;
428
429             IF xfrm.name IS NULL THEN
430                 -- just grab the marcxml (empty) transform
431                 SELECT INTO xfrm * FROM config.xml_transform WHERE xslt = '---' LIMIT 1;
432                 prev_xfrm := xfrm.name;
433             END IF;
434
435             attr_value := oils_xpath_string(attr_def.xpath, transformed_xml, COALESCE(attr_def.joiner,' '), ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]);
436
437         ELSIF attr_def.phys_char_sf IS NOT NULL THEN -- a named Physical Characteristic, see config.marc21_physical_characteristic_*_map
438             SELECT  value::TEXT INTO attr_value
439               FROM  vandelay.marc21_physical_characteristics(xml)
440               WHERE subfield = attr_def.phys_char_sf
441               LIMIT 1; -- Just in case ...
442
443         END IF;
444
445         -- apply index normalizers to attr_value
446         FOR normalizer IN
447             SELECT  n.func AS func,
448                     n.param_count AS param_count,
449                     m.params AS params
450               FROM  config.index_normalizer n
451                     JOIN config.record_attr_index_norm_map m ON (m.norm = n.id)
452               WHERE attr = attr_def.name
453               ORDER BY m.pos LOOP
454                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
455                     quote_literal( attr_value ) ||
456                     CASE
457                         WHEN normalizer.param_count > 0
458                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
459                             ELSE ''
460                         END ||
461                     ')' INTO attr_value;
462
463         END LOOP;
464
465         -- Add the new value to the hstore
466         new_attrs := new_attrs || hstore( attr_def.name, attr_value );
467
468     END LOOP;
469
470     RETURN new_attrs;
471 END;
472 $_$ LANGUAGE PLPGSQL;
473
474 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT ) RETURNS hstore AS $_$
475     SELECT vandelay.extract_rec_attrs( $1, (SELECT ARRAY_ACCUM(name) FROM config.record_attr_definition));
476 $_$ LANGUAGE SQL;
477
478 -- Everything between this comment and the beginning of the definition of
479 -- vandelay.match_bib_record() is strictly in service of that function.
480 CREATE TYPE vandelay.match_set_test_result AS (record BIGINT, quality INTEGER);
481
482 CREATE OR REPLACE FUNCTION vandelay.match_set_test_marcxml(
483     match_set_id INTEGER, record_xml TEXT
484 ) RETURNS SETOF vandelay.match_set_test_result AS $$
485 DECLARE
486     tags_rstore HSTORE;
487     svf_rstore  HSTORE;
488     coal        TEXT;
489     joins       TEXT;
490     query_      TEXT;
491     wq          TEXT;
492     qvalue      INTEGER;
493     rec         RECORD;
494 BEGIN
495     tags_rstore := vandelay.flatten_marc_hstore(record_xml);
496     svf_rstore := vandelay.extract_rec_attrs(record_xml);
497
498     CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
499     CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
500
501     -- generate the where clause and return that directly (into wq), and as
502     -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
503     wq := vandelay.get_expr_from_match_set(match_set_id);
504
505     query_ := 'SELECT bre.id AS record, ';
506
507     -- qrows table is for the quality bits we add to the SELECT clause
508     SELECT ARRAY_TO_STRING(
509         ARRAY_ACCUM('COALESCE(n' || q::TEXT || '.quality, 0)'), ' + '
510     ) INTO coal FROM _vandelay_tmp_qrows;
511
512     -- our query string so far is the SELECT clause and the inital FROM.
513     -- no JOINs yet nor the WHERE clause
514     query_ := query_ || coal || ' AS quality ' || E'\n' ||
515         'FROM biblio.record_entry bre ';
516
517     -- jrows table is for the joins we must make (and the real text conditions)
518     SELECT ARRAY_TO_STRING(ARRAY_ACCUM(j), E'\n') INTO joins
519         FROM _vandelay_tmp_jrows;
520
521     -- add those joins and the where clause to our query.
522     query_ := query_ || joins || E'\n' || 'WHERE ' || wq;
523
524     -- this will return rows of record,quality
525     FOR rec IN EXECUTE query_ USING tags_rstore, svf_rstore LOOP
526         RETURN NEXT rec;
527     END LOOP;
528
529     DROP TABLE _vandelay_tmp_qrows;
530     DROP TABLE _vandelay_tmp_jrows;
531     RETURN;
532 END;
533
534 $$ LANGUAGE PLPGSQL;
535
536 CREATE OR REPLACE FUNCTION vandelay.flatten_marc_hstore(
537     record_xml TEXT
538 ) RETURNS HSTORE AS $$
539 BEGIN
540     RETURN (SELECT
541         HSTORE(
542             ARRAY_ACCUM(tag || (COALESCE(subfield, ''))),
543             ARRAY_ACCUM(value)
544         )
545         FROM (
546             SELECT tag, subfield, ARRAY_ACCUM(value)::TEXT AS value
547                 FROM vandelay.flatten_marc(record_xml)
548                 GROUP BY tag, subfield ORDER BY tag, subfield
549         ) subquery
550     );
551 END;
552 $$ LANGUAGE PLPGSQL;
553
554 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
555     match_set_id INTEGER
556 ) RETURNS TEXT AS $$
557 DECLARE
558     root    vandelay.match_set_point;
559 BEGIN
560     SELECT * INTO root FROM vandelay.match_set_point
561         WHERE parent IS NULL AND match_set = match_set_id;
562
563     RETURN vandelay.get_expr_from_match_set_point(root);
564 END;
565 $$  LANGUAGE PLPGSQL;
566
567 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set_point(
568     node vandelay.match_set_point
569 ) RETURNS TEXT AS $$
570 DECLARE
571     q           TEXT;
572     i           INTEGER;
573     this_op     TEXT;
574     children    INTEGER[];
575     child       vandelay.match_set_point;
576 BEGIN
577     SELECT ARRAY_ACCUM(id) INTO children FROM vandelay.match_set_point
578         WHERE parent = node.id;
579
580     IF ARRAY_LENGTH(children, 1) > 0 THEN
581         this_op := vandelay._get_expr_render_one(node);
582         q := '(';
583         i := 1;
584         WHILE children[i] IS NOT NULL LOOP
585             SELECT * INTO child FROM vandelay.match_set_point
586                 WHERE id = children[i];
587             IF i > 1 THEN
588                 q := q || ' ' || this_op || ' ';
589             END IF;
590             i := i + 1;
591             q := q || vandelay.get_expr_from_match_set_point(child);
592         END LOOP;
593         q := q || ')';
594         RETURN q;
595     ELSIF node.bool_op IS NULL THEN
596         PERFORM vandelay._get_expr_push_qrow(node);
597         PERFORM vandelay._get_expr_push_jrow(node);
598         RETURN vandelay._get_expr_render_one(node);
599     ELSE
600         RETURN '';
601     END IF;
602 END;
603 $$  LANGUAGE PLPGSQL;
604
605 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_qrow(
606     node vandelay.match_set_point
607 ) RETURNS VOID AS $$
608 DECLARE
609 BEGIN
610     INSERT INTO _vandelay_tmp_qrows (q) VALUES (node.id);
611 END;
612 $$ LANGUAGE PLPGSQL;
613
614 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_jrow(
615     node vandelay.match_set_point
616 ) RETURNS VOID AS $$
617 DECLARE
618     jrow        TEXT;
619     my_alias    TEXT;
620     op          TEXT;
621     tagkey      TEXT;
622 BEGIN
623     IF node.negate THEN
624         op := '<>';
625     ELSE
626         op := '=';
627     END IF;
628
629     IF node.tag IS NOT NULL THEN
630         tagkey := node.tag;
631         IF node.subfield IS NOT NULL THEN
632             tagkey := tagkey || node.subfield;
633         END IF;
634     END IF;
635
636     my_alias := 'n' || node.id::TEXT;
637
638     jrow := 'LEFT JOIN (SELECT *, ' || node.quality ||
639         ' AS quality FROM metabib.';
640     IF node.tag IS NOT NULL THEN
641         jrow := jrow || 'full_rec) ' || my_alias || ' ON (' ||
642             my_alias || '.record = bre.id AND ' || my_alias || '.tag = ''' ||
643             node.tag || '''';
644         IF node.subfield IS NOT NULL THEN
645             jrow := jrow || ' AND ' || my_alias || '.subfield = ''' ||
646                 node.subfield || '''';
647         END IF;
648         jrow := jrow || ' AND (' || my_alias || '.value ' || op ||
649             ' ANY(($1->''' || tagkey || ''')::TEXT[])))';
650     ELSE    -- svf
651         jrow := jrow || 'record_attr) ' || my_alias || ' ON (' ||
652             my_alias || '.id = bre.id AND (' ||
653             my_alias || '.attrs->''' || node.svf ||
654             ''' ' || op || ' $2->''' || node.svf || '''))';
655     END IF;
656     INSERT INTO _vandelay_tmp_jrows (j) VALUES (jrow);
657 END;
658 $$ LANGUAGE PLPGSQL;
659
660 CREATE OR REPLACE FUNCTION vandelay._get_expr_render_one(
661     node vandelay.match_set_point
662 ) RETURNS TEXT AS $$
663 DECLARE
664     s           TEXT;
665 BEGIN
666     IF node.bool_op IS NOT NULL THEN
667         RETURN node.bool_op;
668     ELSE
669         RETURN '(n' || node.id::TEXT || '.id IS NOT NULL)';
670     END IF;
671 END;
672 $$ LANGUAGE PLPGSQL;
673
674 CREATE OR REPLACE FUNCTION vandelay.match_bib_record() RETURNS TRIGGER AS $func$
675 DECLARE
676     incoming_existing_id    TEXT;
677     my_bib_queue            vandelay.bib_queue%ROWTYPE;
678     test_result             vandelay.match_set_test_result%ROWTYPE;
679     tmp_rec                 BIGINT;
680 BEGIN
681     DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
682
683     -- Perfect matches on 901$c exit early with a match with high quality.
684     incoming_existing_id :=
685         oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
686
687     IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
688         SELECT id INTO tmp_rec FROM biblio.record_entry WHERE id = incoming_existing_id::bigint;
689         IF tmp_rec IS NOT NULL THEN
690             INSERT INTO vandelay.bib_match (queued_record, eg_record, quality) VALUES ( NEW.id, incoming_existing_id::bigint, 9999);
691             RETURN NEW;
692         END IF;
693     END IF;
694
695     SELECT * INTO my_bib_queue FROM vandelay.bib_queue WHERE id = NEW.queue;
696
697     FOR test_result IN SELECT * FROM
698         vandelay.match_set_test_marcxml(my_bib_queue.match_set, NEW.marc) LOOP
699
700         INSERT INTO vandelay.bib_match (
701             matched_set, queued_record, eg_record, 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_with_best ( import_id BIGINT, merge_profile_id INT, lwm_ratio_value NUMERIC ) RETURNS BOOL AS $$
1281 DECLARE
1282     eg_id           BIGINT;
1283     match_count     INT;
1284     existing_qual   INT;
1285     match_attr      vandelay.bib_attr_definition%ROWTYPE;
1286 BEGIN
1287
1288     existing_qual := COALESCE(NULLIF(vandelay.incoming_record_quality(r.marc),0),1);
1289
1290     IF lwm_ratio_value IS NULL THEN
1291         lwm_ratio_value := 0.0;
1292     END IF;
1293
1294     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1295
1296     IF FOUND THEN
1297         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1298         RETURN FALSE;
1299     END IF;
1300
1301     SELECT  m.eg_record INTO eg_id
1302       FROM  vandelay.bib_match m
1303             JOIN biblio.record_entry r
1304       WHERE m.queued_record = import_id
1305             AND r.id = m.eg_record
1306             AND m.quality::NUMERIC / existing_qual::NUMERIC >= lwm_ratio_value
1307       ORDER BY m.match_score DESC, m.quality DESC, id limit 1;
1308
1309     IF eg_id IS NULL THEN
1310         -- RAISE NOTICE 'incoming record is not of hight enough quality';
1311         RETURN FALSE;
1312     END IF;
1313
1314     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1315 END;
1316 $$ LANGUAGE PLPGSQL;
1317
1318 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1319     SELECT vandelay.auto_overlay_bib_record_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1320 $$ LANGUAGE SQL;
1321
1322 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1323 DECLARE
1324     eg_id           BIGINT;
1325     match_count     INT;
1326     match_attr      vandelay.bib_attr_definition%ROWTYPE;
1327 BEGIN
1328
1329     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1330
1331     IF FOUND THEN
1332         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1333         RETURN FALSE;
1334     END IF;
1335
1336     SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
1337
1338     IF match_count <> 1 THEN
1339         -- RAISE NOTICE 'not an exact match';
1340         RETURN FALSE;
1341     END IF;
1342
1343     -- Check that the one match is on the first 901c
1344     PERFORM *
1345       FROM  vandelay.queued_bib_record q
1346             JOIN vandelay.bib_match m ON (m.queued_record = q.id)
1347       WHERE q.id = import_id
1348             AND m.eg_record = oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]',marc)::BIGINT;
1349
1350     IF NOT FOUND THEN
1351         -- RAISE NOTICE 'not a 901c match: %', match_attr.xpath;
1352         RETURN FALSE;
1353     END IF;
1354
1355     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1356 END;
1357 $$ LANGUAGE PLPGSQL;
1358
1359 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1360 DECLARE
1361     queued_record   vandelay.queued_bib_record%ROWTYPE;
1362 BEGIN
1363
1364     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1365
1366         IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
1367             RETURN NEXT queued_record.id;
1368         END IF;
1369
1370     END LOOP;
1371
1372     RETURN;
1373     
1374 END;
1375 $$ LANGUAGE PLPGSQL;
1376
1377 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1378     SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
1379 $$ LANGUAGE SQL;
1380
1381 CREATE OR REPLACE FUNCTION vandelay.ingest_items ( import_id BIGINT, attr_def_id BIGINT ) RETURNS SETOF vandelay.import_item AS $$
1382 DECLARE
1383
1384     owning_lib      TEXT;
1385     circ_lib        TEXT;
1386     call_number     TEXT;
1387     copy_number     TEXT;
1388     status          TEXT;
1389     location        TEXT;
1390     circulate       TEXT;
1391     deposit         TEXT;
1392     deposit_amount  TEXT;
1393     ref             TEXT;
1394     holdable        TEXT;
1395     price           TEXT;
1396     barcode         TEXT;
1397     circ_modifier   TEXT;
1398     circ_as_type    TEXT;
1399     alert_message   TEXT;
1400     opac_visible    TEXT;
1401     pub_note        TEXT;
1402     priv_note       TEXT;
1403
1404     attr_def        RECORD;
1405     tmp_attr_set    RECORD;
1406     attr_set        vandelay.import_item%ROWTYPE;
1407
1408     xpath           TEXT;
1409
1410 BEGIN
1411
1412     SELECT * INTO attr_def FROM vandelay.import_item_attr_definition WHERE id = attr_def_id;
1413
1414     IF FOUND THEN
1415
1416         attr_set.definition := attr_def.id; 
1417     
1418         -- Build the combined XPath
1419     
1420         owning_lib :=
1421             CASE
1422                 WHEN attr_def.owning_lib IS NULL THEN 'null()'
1423                 WHEN LENGTH( attr_def.owning_lib ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.owning_lib || '"]'
1424                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.owning_lib
1425             END;
1426     
1427         circ_lib :=
1428             CASE
1429                 WHEN attr_def.circ_lib IS NULL THEN 'null()'
1430                 WHEN LENGTH( attr_def.circ_lib ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_lib || '"]'
1431                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_lib
1432             END;
1433     
1434         call_number :=
1435             CASE
1436                 WHEN attr_def.call_number IS NULL THEN 'null()'
1437                 WHEN LENGTH( attr_def.call_number ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.call_number || '"]'
1438                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.call_number
1439             END;
1440     
1441         copy_number :=
1442             CASE
1443                 WHEN attr_def.copy_number IS NULL THEN 'null()'
1444                 WHEN LENGTH( attr_def.copy_number ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.copy_number || '"]'
1445                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.copy_number
1446             END;
1447     
1448         status :=
1449             CASE
1450                 WHEN attr_def.status IS NULL THEN 'null()'
1451                 WHEN LENGTH( attr_def.status ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.status || '"]'
1452                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.status
1453             END;
1454     
1455         location :=
1456             CASE
1457                 WHEN attr_def.location IS NULL THEN 'null()'
1458                 WHEN LENGTH( attr_def.location ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.location || '"]'
1459                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.location
1460             END;
1461     
1462         circulate :=
1463             CASE
1464                 WHEN attr_def.circulate IS NULL THEN 'null()'
1465                 WHEN LENGTH( attr_def.circulate ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circulate || '"]'
1466                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circulate
1467             END;
1468     
1469         deposit :=
1470             CASE
1471                 WHEN attr_def.deposit IS NULL THEN 'null()'
1472                 WHEN LENGTH( attr_def.deposit ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.deposit || '"]'
1473                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.deposit
1474             END;
1475     
1476         deposit_amount :=
1477             CASE
1478                 WHEN attr_def.deposit_amount IS NULL THEN 'null()'
1479                 WHEN LENGTH( attr_def.deposit_amount ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.deposit_amount || '"]'
1480                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.deposit_amount
1481             END;
1482     
1483         ref :=
1484             CASE
1485                 WHEN attr_def.ref IS NULL THEN 'null()'
1486                 WHEN LENGTH( attr_def.ref ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.ref || '"]'
1487                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.ref
1488             END;
1489     
1490         holdable :=
1491             CASE
1492                 WHEN attr_def.holdable IS NULL THEN 'null()'
1493                 WHEN LENGTH( attr_def.holdable ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.holdable || '"]'
1494                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.holdable
1495             END;
1496     
1497         price :=
1498             CASE
1499                 WHEN attr_def.price IS NULL THEN 'null()'
1500                 WHEN LENGTH( attr_def.price ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.price || '"]'
1501                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.price
1502             END;
1503     
1504         barcode :=
1505             CASE
1506                 WHEN attr_def.barcode IS NULL THEN 'null()'
1507                 WHEN LENGTH( attr_def.barcode ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.barcode || '"]'
1508                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.barcode
1509             END;
1510     
1511         circ_modifier :=
1512             CASE
1513                 WHEN attr_def.circ_modifier IS NULL THEN 'null()'
1514                 WHEN LENGTH( attr_def.circ_modifier ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_modifier || '"]'
1515                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_modifier
1516             END;
1517     
1518         circ_as_type :=
1519             CASE
1520                 WHEN attr_def.circ_as_type IS NULL THEN 'null()'
1521                 WHEN LENGTH( attr_def.circ_as_type ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_as_type || '"]'
1522                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_as_type
1523             END;
1524     
1525         alert_message :=
1526             CASE
1527                 WHEN attr_def.alert_message IS NULL THEN 'null()'
1528                 WHEN LENGTH( attr_def.alert_message ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.alert_message || '"]'
1529                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.alert_message
1530             END;
1531     
1532         opac_visible :=
1533             CASE
1534                 WHEN attr_def.opac_visible IS NULL THEN 'null()'
1535                 WHEN LENGTH( attr_def.opac_visible ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.opac_visible || '"]'
1536                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.opac_visible
1537             END;
1538
1539         pub_note :=
1540             CASE
1541                 WHEN attr_def.pub_note IS NULL THEN 'null()'
1542                 WHEN LENGTH( attr_def.pub_note ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.pub_note || '"]'
1543                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.pub_note
1544             END;
1545         priv_note :=
1546             CASE
1547                 WHEN attr_def.priv_note IS NULL THEN 'null()'
1548                 WHEN LENGTH( attr_def.priv_note ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.priv_note || '"]'
1549                 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.priv_note
1550             END;
1551     
1552     
1553         xpath := 
1554             owning_lib      || '|' || 
1555             circ_lib        || '|' || 
1556             call_number     || '|' || 
1557             copy_number     || '|' || 
1558             status          || '|' || 
1559             location        || '|' || 
1560             circulate       || '|' || 
1561             deposit         || '|' || 
1562             deposit_amount  || '|' || 
1563             ref             || '|' || 
1564             holdable        || '|' || 
1565             price           || '|' || 
1566             barcode         || '|' || 
1567             circ_modifier   || '|' || 
1568             circ_as_type    || '|' || 
1569             alert_message   || '|' || 
1570             pub_note        || '|' || 
1571             priv_note       || '|' || 
1572             opac_visible;
1573
1574         -- RAISE NOTICE 'XPath: %', xpath;
1575         
1576         FOR tmp_attr_set IN
1577                 SELECT  *
1578                   FROM  oils_xpath_table( 'id', 'marc', 'vandelay.queued_bib_record', xpath, 'id = ' || import_id )
1579                             AS t( id INT, ol TEXT, clib TEXT, cn TEXT, cnum TEXT, cs TEXT, cl TEXT, circ TEXT,
1580                                   dep TEXT, dep_amount TEXT, r TEXT, hold TEXT, pr TEXT, bc TEXT, circ_mod TEXT,
1581                                   circ_as TEXT, amessage TEXT, note TEXT, pnote TEXT, opac_vis TEXT )
1582         LOOP
1583     
1584             tmp_attr_set.pr = REGEXP_REPLACE(tmp_attr_set.pr, E'[^0-9\\.]', '', 'g');
1585             tmp_attr_set.dep_amount = REGEXP_REPLACE(tmp_attr_set.dep_amount, E'[^0-9\\.]', '', 'g');
1586
1587             tmp_attr_set.pr := NULLIF( tmp_attr_set.pr, '' );
1588             tmp_attr_set.dep_amount := NULLIF( tmp_attr_set.dep_amount, '' );
1589     
1590             SELECT id INTO attr_set.owning_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.ol); -- INT
1591             SELECT id INTO attr_set.circ_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.clib); -- INT
1592             SELECT id INTO attr_set.status FROM config.copy_status WHERE LOWER(name) = LOWER(tmp_attr_set.cs); -- INT
1593     
1594             SELECT  id INTO attr_set.location
1595               FROM  asset.copy_location
1596               WHERE LOWER(name) = LOWER(tmp_attr_set.cl)
1597                     AND asset.copy_location.owning_lib = COALESCE(attr_set.owning_lib, attr_set.circ_lib); -- INT
1598     
1599             attr_set.circulate      :=
1600                 LOWER( SUBSTRING( tmp_attr_set.circ, 1, 1)) IN ('t','y','1')
1601                 OR LOWER(tmp_attr_set.circ) = 'circulating'; -- BOOL
1602
1603             attr_set.deposit        :=
1604                 LOWER( SUBSTRING( tmp_attr_set.dep, 1, 1 ) ) IN ('t','y','1')
1605                 OR LOWER(tmp_attr_set.dep) = 'deposit'; -- BOOL
1606
1607             attr_set.holdable       :=
1608                 LOWER( SUBSTRING( tmp_attr_set.hold, 1, 1 ) ) IN ('t','y','1')
1609                 OR LOWER(tmp_attr_set.hold) = 'holdable'; -- BOOL
1610
1611             attr_set.opac_visible   :=
1612                 LOWER( SUBSTRING( tmp_attr_set.opac_vis, 1, 1 ) ) IN ('t','y','1')
1613                 OR LOWER(tmp_attr_set.opac_vis) = 'visible'; -- BOOL
1614
1615             attr_set.ref            :=
1616                 LOWER( SUBSTRING( tmp_attr_set.r, 1, 1 ) ) IN ('t','y','1')
1617                 OR LOWER(tmp_attr_set.r) = 'reference'; -- BOOL
1618     
1619             attr_set.copy_number    := tmp_attr_set.cnum::INT; -- INT,
1620             attr_set.deposit_amount := tmp_attr_set.dep_amount::NUMERIC(6,2); -- NUMERIC(6,2),
1621             attr_set.price          := tmp_attr_set.pr::NUMERIC(8,2); -- NUMERIC(8,2),
1622     
1623             attr_set.call_number    := tmp_attr_set.cn; -- TEXT
1624             attr_set.barcode        := tmp_attr_set.bc; -- TEXT,
1625             attr_set.circ_modifier  := tmp_attr_set.circ_mod; -- TEXT,
1626             attr_set.circ_as_type   := tmp_attr_set.circ_as; -- TEXT,
1627             attr_set.alert_message  := tmp_attr_set.amessage; -- TEXT,
1628             attr_set.pub_note       := tmp_attr_set.note; -- TEXT,
1629             attr_set.priv_note      := tmp_attr_set.pnote; -- TEXT,
1630             attr_set.alert_message  := tmp_attr_set.amessage; -- TEXT,
1631     
1632             RETURN NEXT attr_set;
1633     
1634         END LOOP;
1635     
1636     END IF;
1637
1638     RETURN;
1639
1640 END;
1641 $$ LANGUAGE PLPGSQL;
1642
1643
1644 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_marc ( ) RETURNS TRIGGER AS $$
1645 DECLARE
1646     value   TEXT;
1647     atype   TEXT;
1648     adef    RECORD;
1649 BEGIN
1650     FOR adef IN SELECT * FROM vandelay.bib_attr_definition LOOP
1651
1652         SELECT extract_marc_field('vandelay.queued_bib_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_bib_record WHERE id = NEW.id;
1653         IF (value IS NOT NULL AND value <> '') THEN
1654             INSERT INTO vandelay.queued_bib_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1655         END IF;
1656
1657     END LOOP;
1658
1659     RETURN NULL;
1660 END;
1661 $$ LANGUAGE PLPGSQL;
1662
1663 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_items ( ) RETURNS TRIGGER AS $func$
1664 DECLARE
1665     attr_def    BIGINT;
1666     item_data   vandelay.import_item%ROWTYPE;
1667 BEGIN
1668
1669     SELECT item_attr_def INTO attr_def FROM vandelay.bib_queue WHERE id = NEW.queue;
1670
1671     FOR item_data IN SELECT * FROM vandelay.ingest_items( NEW.id::BIGINT, attr_def ) LOOP
1672         INSERT INTO vandelay.import_item (
1673             record,
1674             definition,
1675             owning_lib,
1676             circ_lib,
1677             call_number,
1678             copy_number,
1679             status,
1680             location,
1681             circulate,
1682             deposit,
1683             deposit_amount,
1684             ref,
1685             holdable,
1686             price,
1687             barcode,
1688             circ_modifier,
1689             circ_as_type,
1690             alert_message,
1691             pub_note,
1692             priv_note,
1693             opac_visible
1694         ) VALUES (
1695             NEW.id,
1696             item_data.definition,
1697             item_data.owning_lib,
1698             item_data.circ_lib,
1699             item_data.call_number,
1700             item_data.copy_number,
1701             item_data.status,
1702             item_data.location,
1703             item_data.circulate,
1704             item_data.deposit,
1705             item_data.deposit_amount,
1706             item_data.ref,
1707             item_data.holdable,
1708             item_data.price,
1709             item_data.barcode,
1710             item_data.circ_modifier,
1711             item_data.circ_as_type,
1712             item_data.alert_message,
1713             item_data.pub_note,
1714             item_data.priv_note,
1715             item_data.opac_visible
1716         );
1717     END LOOP;
1718
1719     RETURN NULL;
1720 END;
1721 $func$ LANGUAGE PLPGSQL;
1722
1723 CREATE OR REPLACE FUNCTION vandelay.match_bib_record ( ) RETURNS TRIGGER AS $func$
1724 DECLARE
1725     attr        RECORD;
1726     attr_def    RECORD;
1727     eg_rec      RECORD;
1728     id_value    TEXT;
1729     exact_id    BIGINT;
1730 BEGIN
1731
1732     DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
1733
1734     SELECT * INTO attr_def FROM vandelay.bib_attr_definition WHERE xpath = '//*[@tag="901"]/*[@code="c"]' ORDER BY id LIMIT 1;
1735
1736     IF attr_def IS NOT NULL AND attr_def.id IS NOT NULL THEN
1737         id_value := extract_marc_field('vandelay.queued_bib_record', NEW.id, attr_def.xpath, attr_def.remove);
1738     
1739         IF id_value IS NOT NULL AND id_value <> '' AND id_value ~ $r$^\d+$$r$ THEN
1740             SELECT id INTO exact_id FROM biblio.record_entry WHERE id = id_value::BIGINT AND NOT deleted;
1741             SELECT * INTO attr FROM vandelay.queued_bib_record_attr WHERE record = NEW.id and field = attr_def.id LIMIT 1;
1742             IF exact_id IS NOT NULL THEN
1743                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, exact_id);
1744             END IF;
1745         END IF;
1746     END IF;
1747
1748     IF exact_id IS NULL THEN
1749         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
1750     
1751                 -- All numbers? check for an id match
1752                 IF (attr.attr_value ~ $r$^\d+$$r$) THEN
1753                 FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE id = attr.attr_value::BIGINT AND deleted IS FALSE LOOP
1754                         INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, eg_rec.id);
1755                         END LOOP;
1756                 END IF;
1757     
1758                 -- Looks like an ISBN? check for an isbn match
1759                 IF (attr.attr_value ~* $r$^[0-9x]+$$r$ AND character_length(attr.attr_value) IN (10,13)) THEN
1760                 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
1761                                 PERFORM id FROM biblio.record_entry WHERE id = eg_rec.record AND deleted IS FALSE;
1762                                 IF FOUND THEN
1763                                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('isbn', attr.id, NEW.id, eg_rec.record);
1764                                 END IF;
1765                         END LOOP;
1766     
1767                         -- subcheck for isbn-as-tcn
1768                     FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = 'i' || attr.attr_value AND deleted IS FALSE LOOP
1769                             INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
1770                 END LOOP;
1771                 END IF;
1772     
1773                 -- check for an OCLC tcn_value match
1774                 IF (attr.attr_value ~ $r$^o\d+$$r$) THEN
1775                     FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = regexp_replace(attr.attr_value,'^o','ocm') AND deleted IS FALSE LOOP
1776                             INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
1777                 END LOOP;
1778                 END IF;
1779     
1780                 -- check for a direct tcn_value match
1781             FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = attr.attr_value AND deleted IS FALSE LOOP
1782                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
1783             END LOOP;
1784     
1785                 -- check for a direct item barcode match
1786             FOR eg_rec IN
1787                     SELECT  DISTINCT b.*
1788                       FROM  biblio.record_entry b
1789                             JOIN asset.call_number cn ON (cn.record = b.id)
1790                             JOIN asset.copy cp ON (cp.call_number = cn.id)
1791                       WHERE cp.barcode = attr.attr_value AND cp.deleted IS FALSE
1792             LOOP
1793                 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, eg_rec.id);
1794             END LOOP;
1795     
1796         END LOOP;
1797     END IF;
1798
1799     RETURN NULL;
1800 END;
1801 $func$ LANGUAGE PLPGSQL;
1802
1803 CREATE OR REPLACE FUNCTION vandelay.cleanup_bib_marc ( ) RETURNS TRIGGER AS $$
1804 BEGIN
1805     DELETE FROM vandelay.queued_bib_record_attr WHERE record = OLD.id;
1806     DELETE FROM vandelay.import_item WHERE record = OLD.id;
1807
1808     IF TG_OP = 'UPDATE' THEN
1809         RETURN NEW;
1810     END IF;
1811     RETURN OLD;
1812 END;
1813 $$ LANGUAGE PLPGSQL;
1814
1815 CREATE TRIGGER cleanup_bib_trigger
1816     BEFORE UPDATE OR DELETE ON vandelay.queued_bib_record
1817     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_bib_marc();
1818
1819 CREATE TRIGGER ingest_bib_trigger
1820     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1821     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_marc();
1822
1823 CREATE TRIGGER ingest_item_trigger
1824     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1825     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_items();
1826
1827 CREATE TRIGGER zz_match_bibs_trigger
1828     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1829     FOR EACH ROW EXECUTE PROCEDURE vandelay.match_bib_record();
1830
1831
1832 /* Authority stuff down here */
1833 ---------------------------------------
1834 CREATE TABLE vandelay.authority_attr_definition (
1835         id                      SERIAL  PRIMARY KEY,
1836         code            TEXT    UNIQUE NOT NULL,
1837         description     TEXT,
1838         xpath           TEXT    NOT NULL,
1839         remove          TEXT    NOT NULL DEFAULT ''
1840 );
1841
1842 CREATE TABLE vandelay.authority_queue (
1843         queue_type      TEXT            NOT NULL DEFAULT 'authority' CHECK (queue_type = 'authority'),
1844         CONSTRAINT vand_authority_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
1845 ) INHERITS (vandelay.queue);
1846 ALTER TABLE vandelay.authority_queue ADD PRIMARY KEY (id);
1847
1848 CREATE TABLE vandelay.queued_authority_record (
1849         queue           INT     NOT NULL REFERENCES vandelay.authority_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1850         imported_as     INT     REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1851         import_error    TEXT    REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
1852         error_detail    TEXT
1853 ) INHERITS (vandelay.queued_record);
1854 ALTER TABLE vandelay.queued_authority_record ADD PRIMARY KEY (id);
1855 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
1856
1857 CREATE TABLE vandelay.queued_authority_record_attr (
1858         id                      BIGSERIAL       PRIMARY KEY,
1859         record          BIGINT          NOT NULL REFERENCES vandelay.queued_authority_record (id) DEFERRABLE INITIALLY DEFERRED,
1860         field           INT                     NOT NULL REFERENCES vandelay.authority_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
1861         attr_value      TEXT            NOT NULL
1862 );
1863 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
1864
1865 CREATE TABLE vandelay.authority_match (
1866         id                              BIGSERIAL       PRIMARY KEY,
1867         matched_set     INT                     REFERENCES vandelay.match_set (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1868         queued_record   BIGINT          REFERENCES vandelay.queued_authority_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1869         eg_record               BIGINT          REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1870     quality         INT         NOT NULL DEFAULT 0
1871 );
1872
1873 CREATE OR REPLACE FUNCTION vandelay.ingest_authority_marc ( ) RETURNS TRIGGER AS $$
1874 DECLARE
1875     value   TEXT;
1876     atype   TEXT;
1877     adef    RECORD;
1878 BEGIN
1879     FOR adef IN SELECT * FROM vandelay.authority_attr_definition LOOP
1880
1881         SELECT extract_marc_field('vandelay.queued_authority_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_authority_record WHERE id = NEW.id;
1882         IF (value IS NOT NULL AND value <> '') THEN
1883             INSERT INTO vandelay.queued_authority_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1884         END IF;
1885
1886     END LOOP;
1887
1888     RETURN NULL;
1889 END;
1890 $$ LANGUAGE PLPGSQL;
1891
1892 CREATE OR REPLACE FUNCTION vandelay.cleanup_authority_marc ( ) RETURNS TRIGGER AS $$
1893 BEGIN
1894     DELETE FROM vandelay.queued_authority_record_attr WHERE record = OLD.id;
1895     IF TG_OP = 'UPDATE' THEN
1896         RETURN NEW;
1897     END IF;
1898     RETURN OLD;
1899 END;
1900 $$ LANGUAGE PLPGSQL;
1901
1902 CREATE TRIGGER cleanup_authority_trigger
1903     BEFORE UPDATE OR DELETE ON vandelay.queued_authority_record
1904     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_authority_marc();
1905
1906 CREATE TRIGGER ingest_authority_trigger
1907     AFTER INSERT OR UPDATE ON vandelay.queued_authority_record
1908     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_authority_marc();
1909
1910 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1911 DECLARE
1912     merge_profile   vandelay.merge_profile%ROWTYPE;
1913     dyn_profile     vandelay.compile_profile%ROWTYPE;
1914     source_marc     TEXT;
1915     target_marc     TEXT;
1916     eg_marc         TEXT;
1917     v_marc          TEXT;
1918     replace_rule    TEXT;
1919     match_count     INT;
1920 BEGIN
1921
1922     SELECT  b.marc INTO eg_marc
1923       FROM  authority.record_entry b
1924             JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
1925       LIMIT 1;
1926
1927     SELECT  q.marc INTO v_marc
1928       FROM  vandelay.queued_record q
1929             JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
1930       LIMIT 1;
1931
1932     IF eg_marc IS NULL OR v_marc IS NULL THEN
1933         -- RAISE NOTICE 'no marc for vandelay or authority record';
1934         RETURN FALSE;
1935     END IF;
1936
1937     dyn_profile := vandelay.compile_profile( v_marc );
1938
1939     IF merge_profile_id IS NOT NULL THEN
1940         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1941         IF FOUND THEN
1942             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1943             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1944             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1945             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1946         END IF;
1947     END IF;
1948
1949     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1950         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1951         RETURN FALSE;
1952     END IF;
1953
1954     IF dyn_profile.replace_rule <> '' THEN
1955         source_marc = v_marc;
1956         target_marc = eg_marc;
1957         replace_rule = dyn_profile.replace_rule;
1958     ELSE
1959         source_marc = eg_marc;
1960         target_marc = v_marc;
1961         replace_rule = dyn_profile.preserve_rule;
1962     END IF;
1963
1964     UPDATE  authority.record_entry
1965       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1966       WHERE id = eg_id;
1967
1968     IF FOUND THEN
1969         UPDATE  vandelay.queued_authority_record
1970           SET   imported_as = eg_id,
1971                 import_time = NOW()
1972           WHERE id = import_id;
1973         RETURN TRUE;
1974     END IF;
1975
1976     -- RAISE NOTICE 'update of authority.record_entry failed';
1977
1978     RETURN FALSE;
1979
1980 END;
1981 $$ LANGUAGE PLPGSQL;
1982
1983 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1984 DECLARE
1985     eg_id           BIGINT;
1986     match_count     INT;
1987 BEGIN
1988     SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
1989
1990     IF match_count <> 1 THEN
1991         -- RAISE NOTICE 'not an exact match';
1992         RETURN FALSE;
1993     END IF;
1994
1995     SELECT  m.eg_record INTO eg_id
1996       FROM  vandelay.authority_match m
1997       WHERE m.queued_record = import_id
1998       LIMIT 1;
1999
2000     IF eg_id IS NULL THEN
2001         RETURN FALSE;
2002     END IF;
2003
2004     RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
2005 END;
2006 $$ LANGUAGE PLPGSQL;
2007
2008 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
2009 DECLARE
2010     queued_record   vandelay.queued_authority_record%ROWTYPE;
2011 BEGIN
2012
2013     FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
2014
2015         IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
2016             RETURN NEXT queued_record.id;
2017         END IF;
2018
2019     END LOOP;
2020
2021     RETURN;
2022     
2023 END;
2024 $$ LANGUAGE PLPGSQL;
2025
2026 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
2027     SELECT * FROM vandelay.auto_overlay_authority_queue( $1, NULL );
2028 $$ LANGUAGE SQL;
2029
2030
2031 -- Vandelay (for importing and exporting records) 012.schema.vandelay.sql 
2032 --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)]');
2033 --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)]');
2034 --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]');
2035 --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]');
2036 --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$);
2037 --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$);
2038 --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]');
2039 --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);
2040 --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);
2041 --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);
2042 --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);
2043 --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]');
2044 --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$);
2045 --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]');
2046 --
2047 --INSERT INTO vandelay.import_item_attr_definition (
2048 --    owner, name, tag, owning_lib, circ_lib, location,
2049 --    call_number, circ_modifier, barcode, price, copy_number,
2050 --    circulate, ref, holdable, opac_visible, status
2051 --) VALUES (
2052 --    1,
2053 --    'Evergreen 852 export format',
2054 --    '852',
2055 --    '[@code = "b"][1]',
2056 --    '[@code = "b"][2]',
2057 --    'c',
2058 --    'j',
2059 --    'g',
2060 --    'p',
2061 --    'y',
2062 --    't',
2063 --    '[@code = "x" and text() = "circulating"]',
2064 --    '[@code = "x" and text() = "reference"]',
2065 --    '[@code = "x" and text() = "holdable"]',
2066 --    '[@code = "x" and text() = "visible"]',
2067 --    'z'
2068 --);
2069 --
2070 --INSERT INTO vandelay.import_item_attr_definition (
2071 --    owner,
2072 --    name,
2073 --    tag,
2074 --    owning_lib,
2075 --    location,
2076 --    call_number,
2077 --    circ_modifier,
2078 --    barcode,
2079 --    price,
2080 --    status
2081 --) VALUES (
2082 --    1,
2083 --    'Unicorn Import format -- 999',
2084 --    '999',
2085 --    'm',
2086 --    'l',
2087 --    'a',
2088 --    't',
2089 --    'i',
2090 --    'p',
2091 --    'k'
2092 --);
2093 --
2094 --INSERT INTO vandelay.authority_attr_definition ( code, description, xpath, ident ) VALUES ('rec_identifier','Identifier','//*[@tag="001"]', TRUE);
2095
2096 COMMIT;
2097