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