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