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