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