1 DROP SCHEMA IF EXISTS vandelay CASCADE;
5 CREATE SCHEMA vandelay;
7 CREATE TABLE vandelay.match_set (
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)
15 -- Table to define match points, either FF via SVF or tag+subfield
16 CREATE TABLE vandelay.match_set_point (
17 id SERIAL PRIMARY KEY,
18 match_set INT REFERENCES vandelay.match_set (id) ON DELETE CASCADE,
19 parent INT REFERENCES vandelay.match_set_point (id),
20 bool_op TEXT CHECK (bool_op IS NULL OR (bool_op IN ('AND','OR','NOT'))),
21 svf TEXT REFERENCES config.record_attr_definition (name),
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)
34 CREATE TABLE vandelay.match_set_quality (
35 id SERIAL PRIMARY KEY,
36 match_set INT NOT NULL REFERENCES vandelay.match_set (id) ON DELETE CASCADE,
37 svf TEXT REFERENCES config.record_attr_definition,
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))
45 CREATE UNIQUE INDEX vmsq_def_once_per_set ON vandelay.match_set_quality (match_set, COALESCE(tag,''), COALESCE(subfield,''), COALESCE(svf,''), value);
48 CREATE TABLE vandelay.queue (
49 id BIGSERIAL PRIMARY KEY,
50 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
52 complete BOOL NOT NULL DEFAULT FALSE,
53 match_set INT REFERENCES vandelay.match_set (id) ON UPDATE CASCADE ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED
56 CREATE TABLE vandelay.queued_record (
57 id BIGSERIAL PRIMARY KEY,
58 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
59 import_time TIMESTAMP WITH TIME ZONE,
60 purpose TEXT NOT NULL DEFAULT 'import' CHECK (purpose IN ('import','overlay')),
62 quality INT NOT NULL DEFAULT 0
67 /* Bib stuff at the top */
68 ----------------------------------------------------
70 CREATE TABLE vandelay.bib_attr_definition (
71 id SERIAL PRIMARY KEY,
72 code TEXT UNIQUE NOT NULL,
75 remove TEXT NOT NULL DEFAULT ''
78 -- Each TEXT field (other than 'name') should hold an XPath predicate for pulling the data needed
79 -- DROP TABLE vandelay.import_item_attr_definition CASCADE;
80 CREATE TABLE vandelay.import_item_attr_definition (
81 id BIGSERIAL PRIMARY KEY,
82 owner INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
85 keep BOOL NOT NULL DEFAULT FALSE,
105 priv_note_title TEXT,
108 CONSTRAINT vand_import_item_attr_def_idx UNIQUE (owner,name)
111 CREATE TABLE vandelay.import_error (
112 code TEXT PRIMARY KEY,
113 description TEXT NOT NULL -- i18n
116 CREATE TYPE vandelay.bib_queue_queue_type AS ENUM ('bib', 'acq');
118 CREATE TABLE vandelay.bib_queue (
119 queue_type vandelay.bib_queue_queue_type NOT NULL DEFAULT 'bib',
120 item_attr_def BIGINT REFERENCES vandelay.import_item_attr_definition (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
121 match_bucket INTEGER, -- REFERENCES container.biblio_record_entry_bucket(id);
122 CONSTRAINT vand_bib_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
123 ) INHERITS (vandelay.queue);
124 ALTER TABLE vandelay.bib_queue ADD PRIMARY KEY (id);
126 CREATE TABLE vandelay.queued_bib_record (
127 queue INT NOT NULL REFERENCES vandelay.bib_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
128 bib_source INT REFERENCES config.bib_source (id) DEFERRABLE INITIALLY DEFERRED,
129 imported_as BIGINT REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
130 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
132 ) INHERITS (vandelay.queued_record);
133 ALTER TABLE vandelay.queued_bib_record ADD PRIMARY KEY (id);
134 CREATE INDEX queued_bib_record_queue_idx ON vandelay.queued_bib_record (queue);
136 CREATE TABLE vandelay.queued_bib_record_attr (
137 id BIGSERIAL PRIMARY KEY,
138 record BIGINT NOT NULL REFERENCES vandelay.queued_bib_record (id) DEFERRABLE INITIALLY DEFERRED,
139 field INT NOT NULL REFERENCES vandelay.bib_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
140 attr_value TEXT NOT NULL
142 CREATE INDEX queued_bib_record_attr_record_idx ON vandelay.queued_bib_record_attr (record);
144 CREATE TABLE vandelay.bib_match (
145 id BIGSERIAL PRIMARY KEY,
146 queued_record BIGINT REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
147 eg_record BIGINT REFERENCES biblio.record_entry (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
148 quality INT NOT NULL DEFAULT 1,
149 match_score INT NOT NULL DEFAULT 0
152 CREATE TABLE vandelay.import_item (
153 id BIGSERIAL PRIMARY KEY,
154 record BIGINT NOT NULL REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
155 definition BIGINT NOT NULL REFERENCES vandelay.import_item_attr_definition (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
156 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
159 import_time TIMESTAMP WITH TIME ZONE,
168 deposit_amount NUMERIC(8,2),
179 internal_id BIGINT -- queue_type == 'acq' ? acq.lineitem_detail.id : asset.copy.id
182 CREATE TABLE vandelay.import_bib_trash_group(
183 id SERIAL PRIMARY KEY,
184 owner INTEGER NOT NULL REFERENCES actor.org_unit(id),
185 label TEXT NOT NULL, --i18n
186 always_apply BOOLEAN NOT NULL DEFAULT FALSE,
187 CONSTRAINT vand_import_bib_trash_grp_owner_label UNIQUE (owner, label)
190 CREATE TABLE vandelay.import_bib_trash_fields (
191 id BIGSERIAL PRIMARY KEY,
192 grp INTEGER NOT NULL REFERENCES vandelay.import_bib_trash_group,
194 CONSTRAINT vand_import_bib_trash_fields_once_per UNIQUE (grp, field)
197 CREATE TABLE vandelay.merge_profile (
198 id BIGSERIAL PRIMARY KEY,
199 owner INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
206 CONSTRAINT vand_merge_prof_owner_name_idx UNIQUE (owner,name),
207 CONSTRAINT add_replace_strip_or_preserve CHECK ((preserve_spec IS NOT NULL OR replace_spec IS NOT NULL) OR (preserve_spec IS NULL AND replace_spec IS NULL))
210 CREATE OR REPLACE FUNCTION vandelay.marc21_record_type( marc TEXT ) RETURNS config.marc21_rec_type_map AS $func$
217 retval config.marc21_rec_type_map%ROWTYPE;
219 ldr := oils_xpath_string( '//*[local-name()="leader"]', marc );
221 IF ldr IS NULL OR ldr = '' THEN
222 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
226 SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
227 SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
230 tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
231 bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
233 -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
235 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
238 IF retval.code IS NULL THEN
239 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
244 $func$ LANGUAGE PLPGSQL;
246 CREATE TYPE biblio.record_ff_map AS (record BIGINT, ff_name TEXT, ff_value TEXT);
247 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_all_fixed_fields( marc TEXT, use_default BOOL DEFAULT FALSE ) RETURNS SETOF biblio.record_ff_map AS $func$
252 output biblio.record_ff_map%ROWTYPE;
254 rtype := (vandelay.marc21_record_type( marc )).code;
256 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE rec_type = rtype ORDER BY tag DESC LOOP
257 output.ff_name := ff_pos.fixed_field;
258 output.ff_value := NULL;
260 IF ff_pos.tag = 'ldr' THEN
261 output.ff_value := oils_xpath_string('//*[local-name()="leader"]', marc);
262 IF output.ff_value IS NOT NULL THEN
263 output.ff_value := SUBSTRING( output.ff_value, ff_pos.start_pos + 1, ff_pos.length );
265 output.ff_value := NULL;
268 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
269 output.ff_value := SUBSTRING( tag_data, ff_pos.start_pos + 1, ff_pos.length );
270 CONTINUE WHEN output.ff_value IS NULL AND NOT use_default;
271 IF output.ff_value IS NULL THEN output.ff_value := REPEAT( ff_pos.default_val, ff_pos.length ); END IF;
273 output.ff_value := NULL;
281 $func$ LANGUAGE PLPGSQL;
283 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field_list( marc TEXT, ff TEXT, use_default BOOL DEFAULT FALSE ) RETURNS TEXT[] AS $func$
289 collection TEXT[] := '{}'::TEXT[];
291 rtype := (vandelay.marc21_record_type( marc )).code;
292 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
293 IF ff_pos.tag = 'ldr' THEN
294 val := oils_xpath_string('//*[local-name()="leader"]', marc);
295 IF val IS NOT NULL THEN
296 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
297 collection := collection || val;
300 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
301 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
302 collection := collection || val;
305 CONTINUE WHEN NOT use_default;
306 CONTINUE WHEN ARRAY_UPPER(collection, 1) > 0;
307 val := REPEAT( ff_pos.default_val, ff_pos.length );
308 collection := collection || val;
313 $func$ LANGUAGE PLPGSQL;
315 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field( marc TEXT, ff TEXT, use_default BOOL DEFAULT FALSE ) RETURNS TEXT AS $func$
322 rtype := (vandelay.marc21_record_type( marc )).code;
323 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
324 IF ff_pos.tag = 'ldr' THEN
325 val := oils_xpath_string('//*[local-name()="leader"]', marc);
326 IF val IS NOT NULL THEN
327 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
331 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
332 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
336 CONTINUE WHEN NOT use_default;
337 val := REPEAT( ff_pos.default_val, ff_pos.length );
343 $func$ LANGUAGE PLPGSQL;
345 CREATE TYPE biblio.marc21_physical_characteristics AS ( id INT, record BIGINT, ptype TEXT, subfield INT, value INT );
346 CREATE OR REPLACE FUNCTION vandelay.marc21_physical_characteristics( marc TEXT) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
350 ptype config.marc21_physical_characteristic_type_map%ROWTYPE;
351 psf config.marc21_physical_characteristic_subfield_map%ROWTYPE;
352 pval config.marc21_physical_characteristic_value_map%ROWTYPE;
353 retval biblio.marc21_physical_characteristics%ROWTYPE;
356 FOR _007 IN SELECT oils_xpath_string('//*', value) FROM UNNEST(oils_xpath('//*[@tag="007"]', marc)) x(value) LOOP
357 IF _007 IS NOT NULL AND _007 <> '' THEN
358 SELECT * INTO ptype FROM config.marc21_physical_characteristic_type_map WHERE ptype_key = SUBSTRING( _007, 1, 1 );
360 IF ptype.ptype_key IS NOT NULL THEN
361 FOR psf IN SELECT * FROM config.marc21_physical_characteristic_subfield_map WHERE ptype_key = ptype.ptype_key LOOP
362 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 );
364 IF pval.id IS NOT NULL THEN
367 retval.ptype := ptype.ptype_key;
368 retval.subfield := psf.id;
369 retval.value := pval.id;
380 $func$ LANGUAGE PLPGSQL;
382 CREATE TYPE vandelay.flat_marc AS ( tag CHAR(3), ind1 TEXT, ind2 TEXT, subfield TEXT, value TEXT );
383 CREATE OR REPLACE FUNCTION vandelay.flay_marc ( TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
386 use MARC::File::XML (BinaryEncoding => 'UTF-8');
390 MARC::Charset->assume_unicode(1);
393 my $r = MARC::Record->new_from_xml( $xml );
395 return_next( { tag => 'LDR', value => $r->leader } );
397 for my $f ( $r->fields ) {
398 if ($f->is_control_field) {
399 return_next({ tag => $f->tag, value => $f->data });
401 for my $s ($f->subfields) {
404 ind1 => $f->indicator(1),
405 ind2 => $f->indicator(2),
410 if ( $f->tag eq '245' and $s->[0] eq 'a' ) {
411 my $trim = $f->indicator(2) || 0;
414 ind1 => $f->indicator(1),
415 ind2 => $f->indicator(2),
417 value => substr( $s->[1], $trim )
426 $func$ LANGUAGE PLPERLU;
428 CREATE OR REPLACE FUNCTION vandelay.flatten_marc ( marc TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
430 output vandelay.flat_marc%ROWTYPE;
433 FOR field IN SELECT * FROM vandelay.flay_marc( marc ) LOOP
434 output.ind1 := field.ind1;
435 output.ind2 := field.ind2;
436 output.tag := field.tag;
437 output.subfield := field.subfield;
438 IF field.subfield IS NOT NULL AND field.tag NOT IN ('020','022','024') THEN -- exclude standard numbers and control fields
439 output.value := naco_normalize(field.value, field.subfield);
441 output.value := field.value;
444 CONTINUE WHEN output.value IS NULL;
449 $func$ LANGUAGE PLPGSQL;
451 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT, attr_defs TEXT[]) RETURNS hstore AS $_$
453 transformed_xml TEXT;
456 xfrm config.xml_transform%ROWTYPE;
458 new_attrs HSTORE := ''::HSTORE;
459 attr_def config.record_attr_definition%ROWTYPE;
462 FOR attr_def IN SELECT * FROM config.record_attr_definition WHERE name IN (SELECT * FROM UNNEST(attr_defs)) ORDER BY format LOOP
464 IF attr_def.tag IS NOT NULL THEN -- tag (and optional subfield list) selection
465 SELECT STRING_AGG(x.value, COALESCE(attr_def.joiner,' ')) INTO attr_value
466 FROM vandelay.flatten_marc(xml) AS x
467 WHERE x.tag LIKE attr_def.tag
469 WHEN attr_def.sf_list IS NOT NULL
470 THEN POSITION(x.subfield IN attr_def.sf_list) > 0
477 ELSIF attr_def.fixed_field IS NOT NULL THEN -- a named fixed field, see config.marc21_ff_pos_map.fixed_field
478 attr_value := vandelay.marc21_extract_fixed_field(xml, attr_def.fixed_field);
480 ELSIF attr_def.xpath IS NOT NULL THEN -- and xpath expression
482 SELECT INTO xfrm * FROM config.xml_transform WHERE name = attr_def.format;
484 -- See if we can skip the XSLT ... it's expensive
485 IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
486 -- Can't skip the transform
487 IF xfrm.xslt <> '---' THEN
488 transformed_xml := oils_xslt_process(xml,xfrm.xslt);
490 transformed_xml := xml;
493 prev_xfrm := xfrm.name;
496 IF xfrm.name IS NULL THEN
497 -- just grab the marcxml (empty) transform
498 SELECT INTO xfrm * FROM config.xml_transform WHERE xslt = '---' LIMIT 1;
499 prev_xfrm := xfrm.name;
502 attr_value := oils_xpath_string(attr_def.xpath, transformed_xml, COALESCE(attr_def.joiner,' '), ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]);
504 ELSIF attr_def.phys_char_sf IS NOT NULL THEN -- a named Physical Characteristic, see config.marc21_physical_characteristic_*_map
505 SELECT m.value::TEXT INTO attr_value
506 FROM vandelay.marc21_physical_characteristics(xml) v
507 JOIN config.marc21_physical_characteristic_value_map m ON (m.id = v.value)
508 WHERE v.subfield = attr_def.phys_char_sf
509 LIMIT 1; -- Just in case ...
513 -- apply index normalizers to attr_value
515 SELECT n.func AS func,
516 n.param_count AS param_count,
518 FROM config.index_normalizer n
519 JOIN config.record_attr_index_norm_map m ON (m.norm = n.id)
520 WHERE attr = attr_def.name
522 EXECUTE 'SELECT ' || normalizer.func || '(' ||
523 quote_nullable( attr_value ) ||
525 WHEN normalizer.param_count > 0
526 THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
533 -- Add the new value to the hstore
534 new_attrs := new_attrs || hstore( attr_def.name, attr_value );
540 $_$ LANGUAGE PLPGSQL;
542 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT ) RETURNS hstore AS $_$
543 SELECT vandelay.extract_rec_attrs( $1, (SELECT ARRAY_AGG(name) FROM config.record_attr_definition));
546 -- Everything between this comment and the beginning of the definition of
547 -- vandelay.match_bib_record() is strictly in service of that function.
548 CREATE TYPE vandelay.match_set_test_result AS (record BIGINT, quality INTEGER);
550 CREATE OR REPLACE FUNCTION vandelay.match_set_test_marcxml(
551 match_set_id INTEGER, record_xml TEXT, bucket_id INTEGER
552 ) RETURNS SETOF vandelay.match_set_test_result AS $$
563 tags_rstore := vandelay.flatten_marc_hstore(record_xml);
564 svf_rstore := vandelay.extract_rec_attrs(record_xml);
566 CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
567 CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
569 -- generate the where clause and return that directly (into wq), and as
570 -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
571 wq := vandelay.get_expr_from_match_set(match_set_id, tags_rstore);
573 query_ := 'SELECT DISTINCT(record), ';
575 -- qrows table is for the quality bits we add to the SELECT clause
577 'COALESCE(n' || q::TEXT || '.quality, 0)', ' + '
578 ) INTO coal FROM _vandelay_tmp_qrows;
580 -- our query string so far is the SELECT clause and the inital FROM.
581 -- no JOINs yet nor the WHERE clause
582 query_ := query_ || coal || ' AS quality ' || E'\n';
584 -- jrows table is for the joins we must make (and the real text conditions)
585 SELECT STRING_AGG(j, E'\n') INTO joins
586 FROM _vandelay_tmp_jrows;
588 -- add those joins and the where clause to our query.
589 query_ := query_ || joins || E'\n';
591 -- join the record bucket
592 IF bucket_id IS NOT NULL THEN
593 query_ := query_ || 'JOIN container.biblio_record_entry_bucket_item ' ||
594 'brebi ON (brebi.target_biblio_record_entry = record ' ||
595 'AND brebi.bucket = ' || bucket_id || E')\n';
598 query_ := query_ || 'JOIN biblio.record_entry bre ON (bre.id = record) ' || 'WHERE ' || wq || ' AND not bre.deleted';
600 -- this will return rows of record,quality
601 FOR rec IN EXECUTE query_ USING tags_rstore, svf_rstore LOOP
605 DROP TABLE _vandelay_tmp_qrows;
606 DROP TABLE _vandelay_tmp_jrows;
612 CREATE OR REPLACE FUNCTION vandelay.flatten_marc_hstore(
614 ) RETURNS HSTORE AS $func$
618 ARRAY_AGG(tag || (COALESCE(subfield, ''))),
622 SELECT tag, subfield, ARRAY_AGG(value)::TEXT AS value
625 CASE WHEN tag = '020' THEN -- caseless -- isbn
626 LOWER((REGEXP_MATCHES(value,$$^(\S{10,17})$$))[1] || '%')
627 WHEN tag = '022' THEN -- caseless -- issn
628 LOWER((REGEXP_MATCHES(value,$$^(\S{4}[- ]?\S{4})$$))[1] || '%')
629 WHEN tag = '024' THEN -- caseless -- upc (other)
634 FROM vandelay.flatten_marc(record_xml)) x
635 GROUP BY tag, subfield ORDER BY tag, subfield
639 $func$ LANGUAGE PLPGSQL;
641 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
642 match_set_id INTEGER,
646 root vandelay.match_set_point;
648 SELECT * INTO root FROM vandelay.match_set_point
649 WHERE parent IS NULL AND match_set = match_set_id;
651 RETURN vandelay.get_expr_from_match_set_point(root, tags_rstore);
655 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set_point(
656 node vandelay.match_set_point,
664 child vandelay.match_set_point;
666 SELECT ARRAY_AGG(id) INTO children FROM vandelay.match_set_point
667 WHERE parent = node.id;
669 IF ARRAY_LENGTH(children, 1) > 0 THEN
670 this_op := vandelay._get_expr_render_one(node);
673 WHILE children[i] IS NOT NULL LOOP
674 SELECT * INTO child FROM vandelay.match_set_point
675 WHERE id = children[i];
677 q := q || ' ' || this_op || ' ';
680 q := q || vandelay.get_expr_from_match_set_point(child, tags_rstore);
684 ELSIF node.bool_op IS NULL THEN
685 PERFORM vandelay._get_expr_push_qrow(node);
686 PERFORM vandelay._get_expr_push_jrow(node, tags_rstore);
687 RETURN vandelay._get_expr_render_one(node);
694 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_qrow(
695 node vandelay.match_set_point
699 INSERT INTO _vandelay_tmp_qrows (q) VALUES (node.id);
703 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_jrow(
704 node vandelay.match_set_point,
717 -- remember $1 is tags_rstore, and $2 is svf_rstore
720 SELECT COUNT(*) INTO jrow_count FROM _vandelay_tmp_jrows;
721 IF jrow_count > 0 THEN
722 my_using := ' USING (record)';
723 my_join := 'FULL OUTER JOIN';
729 IF node.tag IS NOT NULL THEN
730 caseless := (node.tag IN ('020', '022', '024'));
732 IF node.subfield IS NOT NULL THEN
733 tagkey := tagkey || node.subfield;
751 my_alias := 'n' || node.id::TEXT;
753 jrow := my_join || ' (SELECT *, ';
754 IF node.tag IS NOT NULL THEN
755 jrow := jrow || node.quality ||
756 ' AS quality FROM metabib.full_rec mfr WHERE mfr.tag = ''' ||
758 IF node.subfield IS NOT NULL THEN
759 jrow := jrow || ' AND mfr.subfield = ''' ||
760 node.subfield || '''';
762 jrow := jrow || ' AND (';
763 jrow := jrow || vandelay._node_tag_comparisons(caseless, op, tags_rstore, tagkey);
764 jrow := jrow || ')) ' || my_alias || my_using || E'\n';
766 jrow := jrow || 'id AS record, ' || node.quality ||
767 ' AS quality FROM metabib.record_attr_flat mraf WHERE mraf.attr = ''' ||
768 node.svf || ''' AND mraf.value ' || op || ' $2->''' || node.svf || ''') ' ||
769 my_alias || my_using || E'\n';
771 INSERT INTO _vandelay_tmp_jrows (j) VALUES (jrow);
775 CREATE OR REPLACE FUNCTION vandelay._node_tag_comparisons(
787 vals := tags_rstore->tagkey;
792 IF vals[i] IS NULL THEN
795 result := result || ' OR ';
800 result := result || 'LOWER(mfr.value) ' || op;
802 result := result || 'mfr.value ' || op;
805 result := result || ' ' || COALESCE('''' || vals[i] || '''', 'NULL');
807 IF vals[i] IS NULL THEN
818 CREATE OR REPLACE FUNCTION vandelay._get_expr_render_one(
819 node vandelay.match_set_point
824 IF node.bool_op IS NOT NULL THEN
827 RETURN '(n' || node.id::TEXT || '.id IS NOT NULL)';
832 CREATE OR REPLACE FUNCTION vandelay.match_bib_record() RETURNS TRIGGER AS $func$
834 incoming_existing_id TEXT;
835 test_result vandelay.match_set_test_result%ROWTYPE;
840 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
844 DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
846 SELECT q.match_set INTO match_set FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
848 IF match_set IS NOT NULL THEN
849 NEW.quality := vandelay.measure_record_quality( NEW.marc, match_set );
852 -- Perfect matches on 901$c exit early with a match with high quality.
853 incoming_existing_id :=
854 oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
856 IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
857 SELECT id INTO tmp_rec FROM biblio.record_entry WHERE id = incoming_existing_id::bigint;
858 IF tmp_rec IS NOT NULL THEN
859 INSERT INTO vandelay.bib_match (queued_record, eg_record, match_score, quality)
864 -- note: no match_set means quality==0
865 vandelay.measure_record_quality( b.marc, match_set )
866 FROM biblio.record_entry b
867 WHERE id = incoming_existing_id::bigint;
871 IF match_set IS NULL THEN
875 SELECT q.match_bucket INTO match_bucket FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
877 FOR test_result IN SELECT * FROM
878 vandelay.match_set_test_marcxml(match_set, NEW.marc, match_bucket) LOOP
880 INSERT INTO vandelay.bib_match ( queued_record, eg_record, match_score, quality )
885 vandelay.measure_record_quality( b.marc, match_set )
886 FROM biblio.record_entry b
887 WHERE id = test_result.record;
893 $func$ LANGUAGE PLPGSQL;
895 CREATE OR REPLACE FUNCTION vandelay.measure_record_quality ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
899 test vandelay.match_set_quality%ROWTYPE;
902 FOR test IN SELECT * FROM vandelay.match_set_quality WHERE match_set = match_set_id LOOP
903 IF test.tag IS NOT NULL THEN
904 FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml ) WHERE tag = test.tag AND subfield = test.subfield LOOP
905 IF test.value = rvalue THEN
906 out_q := out_q + test.quality;
910 IF test.value = vandelay.extract_rec_attrs(xml, ARRAY[test.svf]) -> test.svf THEN
911 out_q := out_q + test.quality;
918 $_$ LANGUAGE PLPGSQL;
920 CREATE TYPE vandelay.tcn_data AS (tcn TEXT, tcn_source TEXT, used BOOL);
921 CREATE OR REPLACE FUNCTION vandelay.find_bib_tcn_data ( xml TEXT ) RETURNS SETOF vandelay.tcn_data AS $_$
925 output vandelay.tcn_data%ROWTYPE;
929 eg_tcn := BTRIM((oils_xpath('//*[@tag="001"]/text()',xml))[1]);
930 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
932 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="003"]/text()',xml))[1]);
933 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
934 eg_tcn_source := 'System Local';
937 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
940 output.used := FALSE;
945 output.tcn := eg_tcn;
946 output.tcn_source := eg_tcn_source;
952 eg_tcn := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="a"]/text()',xml))[1]);
953 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
955 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="b"]/text()',xml))[1]);
956 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
957 eg_tcn_source := 'System Local';
960 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
963 output.used := FALSE;
968 output.tcn := eg_tcn;
969 output.tcn_source := eg_tcn_source;
975 eg_tcn := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="a"]/text()',xml))[1]);
976 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
978 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="b"]/text()',xml))[1]);
979 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
980 eg_tcn_source := 'System Local';
983 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
986 output.used := FALSE;
991 output.tcn := eg_tcn;
992 output.tcn_source := eg_tcn_source;
998 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="020"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
999 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1001 eg_tcn_source := 'ISBN';
1003 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1006 output.used := FALSE;
1008 output.used := TRUE;
1011 output.tcn := eg_tcn;
1012 output.tcn_source := eg_tcn_source;
1018 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="022"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1019 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1021 eg_tcn_source := 'ISSN';
1023 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1026 output.used := FALSE;
1028 output.used := TRUE;
1031 output.tcn := eg_tcn;
1032 output.tcn_source := eg_tcn_source;
1038 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="010"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1039 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1041 eg_tcn_source := 'LCCN';
1043 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1046 output.used := FALSE;
1048 output.used := TRUE;
1051 output.tcn := eg_tcn;
1052 output.tcn_source := eg_tcn_source;
1058 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="035"]/*[@code="a"]/text()',xml))[1], $re$^.*?(\w+)$$re$, $re$\1$re$);
1059 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1061 eg_tcn_source := 'System Legacy';
1063 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1066 output.used := FALSE;
1068 output.used := TRUE;
1071 output.tcn := eg_tcn;
1072 output.tcn_source := eg_tcn_source;
1079 $_$ LANGUAGE PLPGSQL;
1081 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT, force_add INT ) RETURNS TEXT AS $_$
1084 use MARC::File::XML (BinaryEncoding => 'UTF-8');
1088 MARC::Charset->assume_unicode(1);
1090 my $target_xml = shift;
1091 my $source_xml = shift;
1092 my $field_spec = shift;
1093 my $force_add = shift || 0;
1095 my $target_r = MARC::Record->new_from_xml( $target_xml );
1096 my $source_r = MARC::Record->new_from_xml( $source_xml );
1098 return $target_xml unless ($target_r && $source_r);
1100 my @field_list = split(',', $field_spec);
1103 for my $f (@field_list) {
1104 $f =~ s/^\s*//; $f =~ s/\s*$//;
1105 if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1111 $match =~ s/^\s*//; $match =~ s/\s*$//;
1112 $fields{$field} = { sf => [ split('', $sf) ] };
1114 my ($msf,$mre) = split('~', $match);
1115 if (length($msf) > 0 and length($mre) > 0) {
1116 $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1117 $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1118 $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1124 for my $f ( keys %fields) {
1125 if ( @{$fields{$f}{sf}} ) {
1126 for my $from_field ($source_r->field( $f )) {
1127 my @tos = $target_r->field( $f );
1129 next if (exists($fields{$f}{match}) and !$force_add);
1130 my @new_fields = map { $_->clone } $source_r->field( $f );
1131 $target_r->insert_fields_ordered( @new_fields );
1133 for my $to_field (@tos) {
1134 if (exists($fields{$f}{match})) {
1135 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1137 for my $old_sf ($from_field->subfields) {
1138 $to_field->add_subfields( @$old_sf ) if grep(/$$old_sf[0]/,@{$fields{$f}{sf}});
1144 my @new_fields = map { $_->clone } $source_r->field( $f );
1145 $target_r->insert_fields_ordered( @new_fields );
1149 $target_xml = $target_r->as_xml_record;
1150 $target_xml =~ s/^<\?.+?\?>$//mo;
1151 $target_xml =~ s/\n//sgo;
1152 $target_xml =~ s/>\s+</></sgo;
1156 $_$ LANGUAGE PLPERLU;
1158 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1159 SELECT vandelay.add_field( $1, $2, $3, 0 );
1162 CREATE OR REPLACE FUNCTION vandelay.strip_field ( xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1165 use MARC::File::XML (BinaryEncoding => 'UTF-8');
1169 MARC::Charset->assume_unicode(1);
1172 my $r = MARC::Record->new_from_xml( $xml );
1174 return $xml unless ($r);
1176 my $field_spec = shift;
1177 my @field_list = split(',', $field_spec);
1180 for my $f (@field_list) {
1181 $f =~ s/^\s*//; $f =~ s/\s*$//;
1182 if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1188 $match =~ s/^\s*//; $match =~ s/\s*$//;
1189 $fields{$field} = { sf => [ split('', $sf) ] };
1191 my ($msf,$mre) = split('~', $match);
1192 if (length($msf) > 0 and length($mre) > 0) {
1193 $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1194 $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1195 $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1201 for my $f ( keys %fields) {
1202 for my $to_field ($r->field( $f )) {
1203 if (exists($fields{$f}{match})) {
1204 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1207 if ( @{$fields{$f}{sf}} ) {
1208 $to_field->delete_subfield(code => $fields{$f}{sf});
1210 $r->delete_field( $to_field );
1215 $xml = $r->as_xml_record;
1216 $xml =~ s/^<\?.+?\?>$//mo;
1218 $xml =~ s/>\s+</></sgo;
1222 $_$ LANGUAGE PLPERLU;
1224 CREATE OR REPLACE FUNCTION vandelay.replace_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1231 parsed_target := vandelay.strip_field( target_xml, ''); -- this dance normalizes the format of the xml for the IF below
1232 xml_output := parsed_target; -- if there are no replace rules, just return the input
1234 FOR curr_field IN SELECT UNNEST( STRING_TO_ARRAY(field, ',') ) LOOP -- naive split, but it's the same we use in the perl
1236 xml_output := vandelay.strip_field( parsed_target, curr_field);
1238 IF xml_output <> parsed_target AND curr_field ~ E'~' THEN
1239 -- we removed something, and there was a regexp restriction in the curr_field definition, so proceed
1240 xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 1 );
1241 ELSIF curr_field !~ E'~' THEN
1242 -- No regexp restriction, add the curr_field
1243 xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 0 );
1246 parsed_target := xml_output; -- in prep for any following loop iterations
1252 $_$ LANGUAGE PLPGSQL;
1254 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 $_$
1255 SELECT vandelay.replace_field( vandelay.add_field( vandelay.strip_field( $1, $5) , $2, $3 ), $2, $4);
1258 CREATE TYPE vandelay.compile_profile AS (add_rule TEXT, replace_rule TEXT, preserve_rule TEXT, strip_rule TEXT);
1259 CREATE OR REPLACE FUNCTION vandelay.compile_profile ( incoming_xml TEXT ) RETURNS vandelay.compile_profile AS $_$
1261 output vandelay.compile_profile%ROWTYPE;
1262 profile vandelay.merge_profile%ROWTYPE;
1264 profile_tmpl_owner TEXT;
1265 add_rule TEXT := '';
1266 strip_rule TEXT := '';
1267 replace_rule TEXT := '';
1268 preserve_rule TEXT := '';
1272 profile_tmpl := (oils_xpath('//*[@tag="905"]/*[@code="t"]/text()',incoming_xml))[1];
1273 profile_tmpl_owner := (oils_xpath('//*[@tag="905"]/*[@code="o"]/text()',incoming_xml))[1];
1275 IF profile_tmpl IS NOT NULL AND profile_tmpl <> '' AND profile_tmpl_owner IS NOT NULL AND profile_tmpl_owner <> '' THEN
1276 SELECT p.* INTO profile
1277 FROM vandelay.merge_profile p
1278 JOIN actor.org_unit u ON (u.id = p.owner)
1279 WHERE p.name = profile_tmpl
1280 AND u.shortname = profile_tmpl_owner;
1282 IF profile.id IS NOT NULL THEN
1283 add_rule := COALESCE(profile.add_spec,'');
1284 strip_rule := COALESCE(profile.strip_spec,'');
1285 replace_rule := COALESCE(profile.replace_spec,'');
1286 preserve_rule := COALESCE(profile.preserve_spec,'');
1290 add_rule := add_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="a"]/text()',incoming_xml),','),'');
1291 strip_rule := strip_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="d"]/text()',incoming_xml),','),'');
1292 replace_rule := replace_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="r"]/text()',incoming_xml),','),'');
1293 preserve_rule := preserve_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="p"]/text()',incoming_xml),','),'');
1295 output.add_rule := BTRIM(add_rule,',');
1296 output.replace_rule := BTRIM(replace_rule,',');
1297 output.strip_rule := BTRIM(strip_rule,',');
1298 output.preserve_rule := BTRIM(preserve_rule,',');
1302 $_$ LANGUAGE PLPGSQL;
1304 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1306 merge_profile vandelay.merge_profile%ROWTYPE;
1307 dyn_profile vandelay.compile_profile%ROWTYPE;
1317 SELECT b.marc INTO eg_marc
1318 FROM biblio.record_entry b
1322 IF eg_marc IS NULL OR v_marc IS NULL THEN
1323 -- RAISE NOTICE 'no marc for template or bib record';
1327 dyn_profile := vandelay.compile_profile( v_marc );
1329 IF merge_profile_id IS NOT NULL THEN
1330 SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1332 dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1333 dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1334 dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1335 dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1339 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1340 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1344 IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1345 --Since we have nothing to do, just return a NOOP "we did it"
1347 ELSIF dyn_profile.replace_rule <> '' THEN
1348 source_marc = v_marc;
1349 target_marc = eg_marc;
1350 replace_rule = dyn_profile.replace_rule;
1352 source_marc = eg_marc;
1353 target_marc = v_marc;
1354 replace_rule = dyn_profile.preserve_rule;
1357 UPDATE biblio.record_entry
1358 SET marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1362 -- RAISE NOTICE 'update of biblio.record_entry failed';
1369 $$ LANGUAGE PLPGSQL;
1371 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_marc TEXT, template_marc TEXT ) RETURNS TEXT AS $$
1373 dyn_profile vandelay.compile_profile%ROWTYPE;
1381 IF target_marc IS NULL OR template_marc IS NULL THEN
1382 -- RAISE NOTICE 'no marc for target or template record';
1386 dyn_profile := vandelay.compile_profile( template_marc );
1388 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1389 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1393 IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1394 --Since we have nothing to do, just return what we were given.
1396 ELSIF dyn_profile.replace_rule <> '' THEN
1397 trgt_marc = target_marc;
1398 tmpl_marc = template_marc;
1399 replace_rule = dyn_profile.replace_rule;
1401 tmp_marc = target_marc;
1402 trgt_marc = template_marc;
1403 tmpl_marc = tmp_marc;
1404 replace_rule = dyn_profile.preserve_rule;
1407 RETURN vandelay.merge_record_xml( trgt_marc, tmpl_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
1410 $$ LANGUAGE PLPGSQL;
1412 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT) RETURNS BOOL AS $$
1413 SELECT vandelay.template_overlay_bib_record( $1, $2, NULL);
1416 CREATE OR REPLACE FUNCTION vandelay.overlay_bib_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1418 merge_profile vandelay.merge_profile%ROWTYPE;
1419 dyn_profile vandelay.compile_profile%ROWTYPE;
1429 SELECT q.marc INTO v_marc
1430 FROM vandelay.queued_record q
1431 JOIN vandelay.bib_match m ON (m.queued_record = q.id AND q.id = import_id)
1434 IF v_marc IS NULL THEN
1435 -- RAISE NOTICE 'no marc for vandelay or bib record';
1439 IF vandelay.template_overlay_bib_record( v_marc, eg_id, merge_profile_id) THEN
1440 UPDATE vandelay.queued_bib_record
1441 SET imported_as = eg_id,
1443 WHERE id = import_id;
1445 editor_string := (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
1447 IF editor_string IS NOT NULL AND editor_string <> '' THEN
1448 SELECT usr INTO editor_id FROM actor.card WHERE barcode = editor_string;
1450 IF editor_id IS NULL THEN
1451 SELECT id INTO editor_id FROM actor.usr WHERE usrname = editor_string;
1454 IF editor_id IS NOT NULL THEN
1455 UPDATE biblio.record_entry SET editor = editor_id WHERE id = eg_id;
1462 -- RAISE NOTICE 'update of biblio.record_entry failed';
1467 $$ LANGUAGE PLPGSQL;
1469 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT, lwm_ratio_value_p NUMERIC ) RETURNS BOOL AS $$
1472 lwm_ratio_value NUMERIC;
1475 lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
1477 PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1480 -- RAISE NOTICE 'already imported, cannot auto-overlay'
1484 SELECT m.eg_record INTO eg_id
1485 FROM vandelay.bib_match m
1486 JOIN vandelay.queued_bib_record qr ON (m.queued_record = qr.id)
1487 JOIN vandelay.bib_queue q ON (qr.queue = q.id)
1488 JOIN biblio.record_entry r ON (r.id = m.eg_record)
1489 WHERE m.queued_record = import_id
1490 AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
1491 ORDER BY m.match_score DESC, -- required match score
1492 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
1493 m.id -- when in doubt, use the first match
1496 IF eg_id IS NULL THEN
1497 -- RAISE NOTICE 'incoming record is not of high enough quality';
1501 RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1503 $$ LANGUAGE PLPGSQL;
1505 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1506 SELECT vandelay.auto_overlay_bib_record_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1509 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1515 PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1518 -- RAISE NOTICE 'already imported, cannot auto-overlay'
1522 SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
1524 IF match_count <> 1 THEN
1525 -- RAISE NOTICE 'not an exact match';
1529 -- Check that the one match is on the first 901c
1530 SELECT m.eg_record INTO eg_id
1531 FROM vandelay.queued_bib_record q
1532 JOIN vandelay.bib_match m ON (m.queued_record = q.id)
1533 WHERE q.id = import_id
1534 AND m.eg_record = oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]',marc)::BIGINT;
1537 -- RAISE NOTICE 'not a 901c match';
1541 RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1543 $$ LANGUAGE PLPGSQL;
1545 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1547 queued_record vandelay.queued_bib_record%ROWTYPE;
1550 FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1552 IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
1553 RETURN NEXT queued_record.id;
1561 $$ LANGUAGE PLPGSQL;
1563 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( queue_id BIGINT, merge_profile_id INT, lwm_ratio_value NUMERIC ) RETURNS SETOF BIGINT AS $$
1565 queued_record vandelay.queued_bib_record%ROWTYPE;
1568 FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1570 IF vandelay.auto_overlay_bib_record_with_best( queued_record.id, merge_profile_id, lwm_ratio_value ) THEN
1571 RETURN NEXT queued_record.id;
1579 $$ LANGUAGE PLPGSQL;
1581 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1582 SELECT vandelay.auto_overlay_bib_queue_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1585 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1586 SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
1589 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_marc ( ) RETURNS TRIGGER AS $$
1595 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1599 FOR adef IN SELECT * FROM vandelay.bib_attr_definition LOOP
1601 SELECT extract_marc_field('vandelay.queued_bib_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_bib_record WHERE id = NEW.id;
1602 IF (value IS NOT NULL AND value <> '') THEN
1603 INSERT INTO vandelay.queued_bib_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1610 $$ LANGUAGE PLPGSQL;
1612 CREATE OR REPLACE FUNCTION vandelay.cleanup_bib_marc ( ) RETURNS TRIGGER AS $$
1614 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1618 DELETE FROM vandelay.queued_bib_record_attr WHERE record = OLD.id;
1619 DELETE FROM vandelay.import_item WHERE record = OLD.id;
1621 IF TG_OP = 'UPDATE' THEN
1626 $$ LANGUAGE PLPGSQL;
1628 CREATE TRIGGER cleanup_bib_trigger
1629 BEFORE UPDATE OR DELETE ON vandelay.queued_bib_record
1630 FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_bib_marc();
1632 CREATE TRIGGER ingest_bib_trigger
1633 AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1634 FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_marc();
1636 CREATE TRIGGER zz_match_bibs_trigger
1637 BEFORE INSERT OR UPDATE ON vandelay.queued_bib_record
1638 FOR EACH ROW EXECUTE PROCEDURE vandelay.match_bib_record();
1641 /* Authority stuff down here */
1642 ---------------------------------------
1643 CREATE TABLE vandelay.authority_attr_definition (
1644 id SERIAL PRIMARY KEY,
1645 code TEXT UNIQUE NOT NULL,
1647 xpath TEXT NOT NULL,
1648 remove TEXT NOT NULL DEFAULT ''
1651 CREATE TYPE vandelay.authority_queue_queue_type AS ENUM ('authority');
1652 CREATE TABLE vandelay.authority_queue (
1653 queue_type vandelay.authority_queue_queue_type NOT NULL DEFAULT 'authority',
1654 CONSTRAINT vand_authority_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
1655 ) INHERITS (vandelay.queue);
1656 ALTER TABLE vandelay.authority_queue ADD PRIMARY KEY (id);
1658 CREATE TABLE vandelay.queued_authority_record (
1659 queue INT NOT NULL REFERENCES vandelay.authority_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1660 imported_as INT REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1661 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
1663 ) INHERITS (vandelay.queued_record);
1664 ALTER TABLE vandelay.queued_authority_record ADD PRIMARY KEY (id);
1665 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
1667 CREATE TABLE vandelay.queued_authority_record_attr (
1668 id BIGSERIAL PRIMARY KEY,
1669 record BIGINT NOT NULL REFERENCES vandelay.queued_authority_record (id) DEFERRABLE INITIALLY DEFERRED,
1670 field INT NOT NULL REFERENCES vandelay.authority_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
1671 attr_value TEXT NOT NULL
1673 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
1675 CREATE TABLE vandelay.authority_match (
1676 id BIGSERIAL PRIMARY KEY,
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
1682 CREATE OR REPLACE FUNCTION vandelay.ingest_authority_marc ( ) RETURNS TRIGGER AS $$
1688 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1692 FOR adef IN SELECT * FROM vandelay.authority_attr_definition LOOP
1694 SELECT extract_marc_field('vandelay.queued_authority_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_authority_record WHERE id = NEW.id;
1695 IF (value IS NOT NULL AND value <> '') THEN
1696 INSERT INTO vandelay.queued_authority_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1703 $$ LANGUAGE PLPGSQL;
1705 CREATE OR REPLACE FUNCTION vandelay.cleanup_authority_marc ( ) RETURNS TRIGGER AS $$
1707 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1711 DELETE FROM vandelay.queued_authority_record_attr WHERE record = OLD.id;
1712 IF TG_OP = 'UPDATE' THEN
1717 $$ LANGUAGE PLPGSQL;
1719 CREATE TRIGGER cleanup_authority_trigger
1720 BEFORE UPDATE OR DELETE ON vandelay.queued_authority_record
1721 FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_authority_marc();
1723 CREATE TRIGGER ingest_authority_trigger
1724 AFTER INSERT OR UPDATE ON vandelay.queued_authority_record
1725 FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_authority_marc();
1727 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1729 merge_profile vandelay.merge_profile%ROWTYPE;
1730 dyn_profile vandelay.compile_profile%ROWTYPE;
1739 SELECT b.marc INTO eg_marc
1740 FROM authority.record_entry b
1741 JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
1744 SELECT q.marc INTO v_marc
1745 FROM vandelay.queued_record q
1746 JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
1749 IF eg_marc IS NULL OR v_marc IS NULL THEN
1750 -- RAISE NOTICE 'no marc for vandelay or authority record';
1754 dyn_profile := vandelay.compile_profile( v_marc );
1756 IF merge_profile_id IS NOT NULL THEN
1757 SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1759 dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1760 dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1761 dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1762 dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1766 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1767 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1771 IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1772 --Since we have nothing to do, just return a NOOP "we did it"
1774 ELSIF dyn_profile.replace_rule <> '' THEN
1775 source_marc = v_marc;
1776 target_marc = eg_marc;
1777 replace_rule = dyn_profile.replace_rule;
1779 source_marc = eg_marc;
1780 target_marc = v_marc;
1781 replace_rule = dyn_profile.preserve_rule;
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 )
1789 UPDATE vandelay.queued_authority_record
1790 SET imported_as = eg_id,
1792 WHERE id = import_id;
1796 -- RAISE NOTICE 'update of authority.record_entry failed';
1801 $$ LANGUAGE PLPGSQL;
1803 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1808 SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
1810 IF match_count <> 1 THEN
1811 -- RAISE NOTICE 'not an exact match';
1815 SELECT m.eg_record INTO eg_id
1816 FROM vandelay.authority_match m
1817 WHERE m.queued_record = import_id
1820 IF eg_id IS NULL THEN
1824 RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
1826 $$ LANGUAGE PLPGSQL;
1828 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1830 queued_record vandelay.queued_authority_record%ROWTYPE;
1833 FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
1835 IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
1836 RETURN NEXT queued_record.id;
1844 $$ LANGUAGE PLPGSQL;
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 );
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]');
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
1873 -- 'Evergreen 852 export format',
1875 -- '[@code = "b"][1]',
1876 -- '[@code = "b"][2]',
1883 -- '[@code = "x" and text() = "circulating"]',
1884 -- '[@code = "x" and text() = "reference"]',
1885 -- '[@code = "x" and text() = "holdable"]',
1886 -- '[@code = "x" and text() = "visible"]',
1890 --INSERT INTO vandelay.import_item_attr_definition (
1903 -- 'Unicorn Import format -- 999',
1914 --INSERT INTO vandelay.authority_attr_definition ( code, description, xpath, ident ) VALUES ('rec_identifier','Identifier','//*[@tag="001"]', TRUE);