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