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