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 queue_type TEXT NOT NULL DEFAULT 'bib' CHECK (queue_type IN ('bib','authority')),
54 match_set INT REFERENCES vandelay.match_set (id) ON UPDATE CASCADE ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
55 CONSTRAINT vand_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
58 CREATE TABLE vandelay.queued_record (
59 id BIGSERIAL PRIMARY KEY,
60 create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
61 import_time TIMESTAMP WITH TIME ZONE,
62 purpose TEXT NOT NULL DEFAULT 'import' CHECK (purpose IN ('import','overlay')),
64 quality INT NOT NULL DEFAULT 0
69 /* Bib stuff at the top */
70 ----------------------------------------------------
72 CREATE TABLE vandelay.bib_attr_definition (
73 id SERIAL PRIMARY KEY,
74 code TEXT UNIQUE NOT NULL,
77 remove TEXT NOT NULL DEFAULT ''
80 -- Each TEXT field (other than 'name') should hold an XPath predicate for pulling the data needed
81 -- DROP TABLE vandelay.import_item_attr_definition CASCADE;
82 CREATE TABLE vandelay.import_item_attr_definition (
83 id BIGSERIAL PRIMARY KEY,
84 owner INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
87 keep BOOL NOT NULL DEFAULT FALSE,
107 priv_note_title TEXT,
109 CONSTRAINT vand_import_item_attr_def_idx UNIQUE (owner,name)
112 CREATE TABLE vandelay.import_error (
113 code TEXT PRIMARY KEY,
114 description TEXT NOT NULL -- i18n
117 CREATE TABLE vandelay.bib_queue (
118 queue_type TEXT NOT NULL DEFAULT 'bib' CHECK (queue_type = 'bib'),
119 item_attr_def BIGINT REFERENCES vandelay.import_item_attr_definition (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
120 CONSTRAINT vand_bib_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
121 ) INHERITS (vandelay.queue);
122 ALTER TABLE vandelay.bib_queue ADD PRIMARY KEY (id);
124 CREATE TABLE vandelay.queued_bib_record (
125 queue INT NOT NULL REFERENCES vandelay.bib_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
126 bib_source INT REFERENCES config.bib_source (id) DEFERRABLE INITIALLY DEFERRED,
127 imported_as BIGINT REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
128 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
130 ) INHERITS (vandelay.queued_record);
131 ALTER TABLE vandelay.queued_bib_record ADD PRIMARY KEY (id);
132 CREATE INDEX queued_bib_record_queue_idx ON vandelay.queued_bib_record (queue);
134 CREATE TABLE vandelay.queued_bib_record_attr (
135 id BIGSERIAL PRIMARY KEY,
136 record BIGINT NOT NULL REFERENCES vandelay.queued_bib_record (id) DEFERRABLE INITIALLY DEFERRED,
137 field INT NOT NULL REFERENCES vandelay.bib_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
138 attr_value TEXT NOT NULL
140 CREATE INDEX queued_bib_record_attr_record_idx ON vandelay.queued_bib_record_attr (record);
142 CREATE TABLE vandelay.bib_match (
143 id BIGSERIAL PRIMARY KEY,
144 queued_record BIGINT REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
145 eg_record BIGINT REFERENCES biblio.record_entry (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
146 quality INT NOT NULL DEFAULT 1,
147 match_score INT NOT NULL DEFAULT 0
150 CREATE TABLE vandelay.import_item (
151 id BIGSERIAL PRIMARY KEY,
152 record BIGINT NOT NULL REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
153 definition BIGINT NOT NULL REFERENCES vandelay.import_item_attr_definition (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
154 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
164 deposit_amount NUMERIC(8,2),
177 CREATE TABLE vandelay.import_bib_trash_fields (
178 id BIGSERIAL PRIMARY KEY,
179 owner INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
181 CONSTRAINT vand_import_bib_trash_fields_idx UNIQUE (owner,field)
184 CREATE TABLE vandelay.merge_profile (
185 id BIGSERIAL PRIMARY KEY,
186 owner INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
193 CONSTRAINT vand_merge_prof_owner_name_idx UNIQUE (owner,name),
194 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))
197 CREATE OR REPLACE FUNCTION vandelay.marc21_record_type( marc TEXT ) RETURNS config.marc21_rec_type_map AS $func$
204 retval config.marc21_rec_type_map%ROWTYPE;
206 ldr := oils_xpath_string( '//*[local-name()="leader"]', marc );
208 IF ldr IS NULL OR ldr = '' THEN
209 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
213 SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
214 SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
217 tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
218 bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
220 -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
222 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
225 IF retval.code IS NULL THEN
226 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
231 $func$ LANGUAGE PLPGSQL;
233 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field( marc TEXT, ff TEXT ) RETURNS TEXT AS $func$
240 rtype := (vandelay.marc21_record_type( marc )).code;
241 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
242 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
243 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
246 val := REPEAT( ff_pos.default_val, ff_pos.length );
252 $func$ LANGUAGE PLPGSQL;
254 CREATE TYPE biblio.record_ff_map AS (record BIGINT, ff_name TEXT, ff_value TEXT);
255 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_all_fixed_fields( marc TEXT ) RETURNS SETOF biblio.record_ff_map AS $func$
260 output biblio.record_ff_map%ROWTYPE;
262 rtype := (vandelay.marc21_record_type( marc )).code;
264 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE rec_type = rtype ORDER BY tag DESC LOOP
265 output.ff_name := ff_pos.fixed_field;
266 output.ff_value := NULL;
268 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(tag) || '"]/text()', marc ) ) x(value) LOOP
269 output.ff_value := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
270 IF output.ff_value IS NULL THEN output.ff_value := REPEAT( ff_pos.default_val, ff_pos.length ); END IF;
272 output.ff_value := NULL;
279 $func$ LANGUAGE PLPGSQL;
281 CREATE TYPE biblio.marc21_physical_characteristics AS ( id INT, record BIGINT, ptype TEXT, subfield INT, value INT );
282 CREATE OR REPLACE FUNCTION vandelay.marc21_physical_characteristics( marc TEXT) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
286 ptype config.marc21_physical_characteristic_type_map%ROWTYPE;
287 psf config.marc21_physical_characteristic_subfield_map%ROWTYPE;
288 pval config.marc21_physical_characteristic_value_map%ROWTYPE;
289 retval biblio.marc21_physical_characteristics%ROWTYPE;
292 _007 := oils_xpath_string( '//*[@tag="007"]', marc );
294 IF _007 IS NOT NULL AND _007 <> '' THEN
295 SELECT * INTO ptype FROM config.marc21_physical_characteristic_type_map WHERE ptype_key = SUBSTRING( _007, 1, 1 );
297 IF ptype.ptype_key IS NOT NULL THEN
298 FOR psf IN SELECT * FROM config.marc21_physical_characteristic_subfield_map WHERE ptype_key = ptype.ptype_key LOOP
299 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 );
301 IF pval.id IS NOT NULL THEN
304 retval.ptype := ptype.ptype_key;
305 retval.subfield := psf.id;
306 retval.value := pval.id;
316 $func$ LANGUAGE PLPGSQL;
318 CREATE TYPE vandelay.flat_marc AS ( tag CHAR(3), ind1 TEXT, ind2 TEXT, subfield TEXT, value TEXT );
319 CREATE OR REPLACE FUNCTION vandelay.flay_marc ( TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
322 use MARC::File::XML (BinaryEncoding => 'UTF-8');
326 MARC::Charset->assume_unicode(1);
329 my $r = MARC::Record->new_from_xml( $xml );
331 return_next( { tag => 'LDR', value => $r->leader } );
333 for my $f ( $r->fields ) {
334 if ($f->is_control_field) {
335 return_next({ tag => $f->tag, value => $f->data });
337 for my $s ($f->subfields) {
340 ind1 => $f->indicator(1),
341 ind2 => $f->indicator(2),
346 if ( $f->tag eq '245' and $s->[0] eq 'a' ) {
347 my $trim = $f->indicator(2) || 0;
350 ind1 => $f->indicator(1),
351 ind2 => $f->indicator(2),
353 value => substr( $s->[1], $trim )
362 $func$ LANGUAGE PLPERLU;
364 CREATE OR REPLACE FUNCTION vandelay.flatten_marc ( marc TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
366 output vandelay.flat_marc%ROWTYPE;
369 FOR field IN SELECT * FROM vandelay.flay_marc( marc ) LOOP
370 output.ind1 := field.ind1;
371 output.ind2 := field.ind2;
372 output.tag := field.tag;
373 output.subfield := field.subfield;
374 IF field.subfield IS NOT NULL AND field.tag NOT IN ('020','022','024') THEN -- exclude standard numbers and control fields
375 output.value := naco_normalize(field.value, field.subfield);
377 output.value := field.value;
380 CONTINUE WHEN output.value IS NULL;
385 $func$ LANGUAGE PLPGSQL;
387 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT, attr_defs TEXT[]) RETURNS hstore AS $_$
389 transformed_xml TEXT;
392 xfrm config.xml_transform%ROWTYPE;
394 new_attrs HSTORE := ''::HSTORE;
395 attr_def config.record_attr_definition%ROWTYPE;
398 FOR attr_def IN SELECT * FROM config.record_attr_definition WHERE name IN (SELECT * FROM UNNEST(attr_defs)) ORDER BY format LOOP
400 IF attr_def.tag IS NOT NULL THEN -- tag (and optional subfield list) selection
401 SELECT ARRAY_TO_STRING(ARRAY_ACCUM(x.value), COALESCE(attr_def.joiner,' ')) INTO attr_value
402 FROM vandelay.flatten_marc(xml) AS x
403 WHERE x.tag LIKE attr_def.tag
405 WHEN attr_def.sf_list IS NOT NULL
406 THEN POSITION(x.subfield IN attr_def.sf_list) > 0
413 ELSIF attr_def.fixed_field IS NOT NULL THEN -- a named fixed field, see config.marc21_ff_pos_map.fixed_field
414 attr_value := vandelay.marc21_extract_fixed_field(xml, attr_def.fixed_field);
416 ELSIF attr_def.xpath IS NOT NULL THEN -- and xpath expression
418 SELECT INTO xfrm * FROM config.xml_transform WHERE name = attr_def.format;
420 -- See if we can skip the XSLT ... it's expensive
421 IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
422 -- Can't skip the transform
423 IF xfrm.xslt <> '---' THEN
424 transformed_xml := oils_xslt_process(xml,xfrm.xslt);
426 transformed_xml := xml;
429 prev_xfrm := xfrm.name;
432 IF xfrm.name IS NULL THEN
433 -- just grab the marcxml (empty) transform
434 SELECT INTO xfrm * FROM config.xml_transform WHERE xslt = '---' LIMIT 1;
435 prev_xfrm := xfrm.name;
438 attr_value := oils_xpath_string(attr_def.xpath, transformed_xml, COALESCE(attr_def.joiner,' '), ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]);
440 ELSIF attr_def.phys_char_sf IS NOT NULL THEN -- a named Physical Characteristic, see config.marc21_physical_characteristic_*_map
441 SELECT value::TEXT INTO attr_value
442 FROM vandelay.marc21_physical_characteristics(xml)
443 WHERE subfield = attr_def.phys_char_sf
444 LIMIT 1; -- Just in case ...
448 -- apply index normalizers to attr_value
450 SELECT n.func AS func,
451 n.param_count AS param_count,
453 FROM config.index_normalizer n
454 JOIN config.record_attr_index_norm_map m ON (m.norm = n.id)
455 WHERE attr = attr_def.name
457 EXECUTE 'SELECT ' || normalizer.func || '(' ||
458 quote_literal( attr_value ) ||
460 WHEN normalizer.param_count > 0
461 THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
468 -- Add the new value to the hstore
469 new_attrs := new_attrs || hstore( attr_def.name, attr_value );
475 $_$ LANGUAGE PLPGSQL;
477 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT ) RETURNS hstore AS $_$
478 SELECT vandelay.extract_rec_attrs( $1, (SELECT ARRAY_ACCUM(name) FROM config.record_attr_definition));
481 -- Everything between this comment and the beginning of the definition of
482 -- vandelay.match_bib_record() is strictly in service of that function.
483 CREATE TYPE vandelay.match_set_test_result AS (record BIGINT, quality INTEGER);
485 CREATE OR REPLACE FUNCTION vandelay.match_set_test_marcxml(
486 match_set_id INTEGER, record_xml TEXT
487 ) RETURNS SETOF vandelay.match_set_test_result AS $$
498 tags_rstore := vandelay.flatten_marc_hstore(record_xml);
499 svf_rstore := vandelay.extract_rec_attrs(record_xml);
501 CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
502 CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
504 -- generate the where clause and return that directly (into wq), and as
505 -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
506 wq := vandelay.get_expr_from_match_set(match_set_id);
508 query_ := 'SELECT bre.id AS record, ';
510 -- qrows table is for the quality bits we add to the SELECT clause
511 SELECT ARRAY_TO_STRING(
512 ARRAY_ACCUM('COALESCE(n' || q::TEXT || '.quality, 0)'), ' + '
513 ) INTO coal FROM _vandelay_tmp_qrows;
515 -- our query string so far is the SELECT clause and the inital FROM.
516 -- no JOINs yet nor the WHERE clause
517 query_ := query_ || coal || ' AS quality ' || E'\n' ||
518 'FROM biblio.record_entry bre ';
520 -- jrows table is for the joins we must make (and the real text conditions)
521 SELECT ARRAY_TO_STRING(ARRAY_ACCUM(j), E'\n') INTO joins
522 FROM _vandelay_tmp_jrows;
524 -- add those joins and the where clause to our query.
525 query_ := query_ || joins || E'\n' || 'WHERE ' || wq || ' AND not bre.deleted';
527 -- this will return rows of record,quality
528 FOR rec IN EXECUTE query_ USING tags_rstore, svf_rstore LOOP
532 DROP TABLE _vandelay_tmp_qrows;
533 DROP TABLE _vandelay_tmp_jrows;
539 CREATE OR REPLACE FUNCTION vandelay.flatten_marc_hstore(
541 ) RETURNS HSTORE AS $$
545 ARRAY_ACCUM(tag || (COALESCE(subfield, ''))),
549 SELECT tag, subfield, ARRAY_ACCUM(value)::TEXT AS value
550 FROM vandelay.flatten_marc(record_xml)
551 GROUP BY tag, subfield ORDER BY tag, subfield
557 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
561 root vandelay.match_set_point;
563 SELECT * INTO root FROM vandelay.match_set_point
564 WHERE parent IS NULL AND match_set = match_set_id;
566 RETURN vandelay.get_expr_from_match_set_point(root);
570 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set_point(
571 node vandelay.match_set_point
578 child vandelay.match_set_point;
580 SELECT ARRAY_ACCUM(id) INTO children FROM vandelay.match_set_point
581 WHERE parent = node.id;
583 IF ARRAY_LENGTH(children, 1) > 0 THEN
584 this_op := vandelay._get_expr_render_one(node);
587 WHILE children[i] IS NOT NULL LOOP
588 SELECT * INTO child FROM vandelay.match_set_point
589 WHERE id = children[i];
591 q := q || ' ' || this_op || ' ';
594 q := q || vandelay.get_expr_from_match_set_point(child);
598 ELSIF node.bool_op IS NULL THEN
599 PERFORM vandelay._get_expr_push_qrow(node);
600 PERFORM vandelay._get_expr_push_jrow(node);
601 RETURN vandelay._get_expr_render_one(node);
608 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_qrow(
609 node vandelay.match_set_point
613 INSERT INTO _vandelay_tmp_qrows (q) VALUES (node.id);
617 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_jrow(
618 node vandelay.match_set_point
632 IF node.tag IS NOT NULL THEN
634 IF node.subfield IS NOT NULL THEN
635 tagkey := tagkey || node.subfield;
639 my_alias := 'n' || node.id::TEXT;
641 jrow := 'LEFT JOIN (SELECT *, ' || node.quality ||
642 ' AS quality FROM metabib.';
643 IF node.tag IS NOT NULL THEN
644 jrow := jrow || 'full_rec) ' || my_alias || ' ON (' ||
645 my_alias || '.record = bre.id AND ' || my_alias || '.tag = ''' ||
647 IF node.subfield IS NOT NULL THEN
648 jrow := jrow || ' AND ' || my_alias || '.subfield = ''' ||
649 node.subfield || '''';
651 jrow := jrow || ' AND (' || my_alias || '.value ' || op ||
652 ' ANY(($1->''' || tagkey || ''')::TEXT[])))';
654 jrow := jrow || 'record_attr) ' || my_alias || ' ON (' ||
655 my_alias || '.id = bre.id AND (' ||
656 my_alias || '.attrs->''' || node.svf ||
657 ''' ' || op || ' $2->''' || node.svf || '''))';
659 INSERT INTO _vandelay_tmp_jrows (j) VALUES (jrow);
663 CREATE OR REPLACE FUNCTION vandelay._get_expr_render_one(
664 node vandelay.match_set_point
669 IF node.bool_op IS NOT NULL THEN
672 RETURN '(n' || node.id::TEXT || '.id IS NOT NULL)';
677 CREATE OR REPLACE FUNCTION vandelay.match_bib_record() RETURNS TRIGGER AS $func$
679 incoming_existing_id TEXT;
680 test_result vandelay.match_set_test_result%ROWTYPE;
684 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
688 DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
690 SELECT q.match_set INTO match_set FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
692 IF match_set IS NOT NULL THEN
693 NEW.quality := vandelay.measure_record_quality( NEW.marc, match_set );
696 -- Perfect matches on 901$c exit early with a match with high quality.
697 incoming_existing_id :=
698 oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
700 IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
701 SELECT id INTO tmp_rec FROM biblio.record_entry WHERE id = incoming_existing_id::bigint;
702 IF tmp_rec IS NOT NULL THEN
703 INSERT INTO vandelay.bib_match (queued_record, eg_record, match_score, quality)
708 -- note: no match_set means quality==0
709 vandelay.measure_record_quality( b.marc, match_set )
710 FROM biblio.record_entry b
711 WHERE id = incoming_existing_id::bigint;
715 IF match_set IS NULL THEN
719 FOR test_result IN SELECT * FROM
720 vandelay.match_set_test_marcxml(match_set, NEW.marc) LOOP
722 INSERT INTO vandelay.bib_match ( queued_record, eg_record, match_score, quality )
727 vandelay.measure_record_quality( b.marc, match_set )
728 FROM biblio.record_entry b
729 WHERE id = test_result.record;
735 $func$ LANGUAGE PLPGSQL;
737 CREATE OR REPLACE FUNCTION vandelay.measure_record_quality ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
741 test vandelay.match_set_quality%ROWTYPE;
744 FOR test IN SELECT * FROM vandelay.match_set_quality WHERE match_set = match_set_id LOOP
745 IF test.tag IS NOT NULL THEN
746 FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml ) WHERE tag = test.tag AND subfield = test.subfield LOOP
747 IF test.value = rvalue THEN
748 out_q := out_q + test.quality;
752 IF test.value = vandelay.extract_rec_attrs(xml, ARRAY[test.svf]) -> test.svf THEN
753 out_q := out_q + test.quality;
760 $_$ LANGUAGE PLPGSQL;
762 CREATE TYPE vandelay.tcn_data AS (tcn TEXT, tcn_source TEXT, used BOOL);
763 CREATE OR REPLACE FUNCTION vandelay.find_bib_tcn_data ( xml TEXT ) RETURNS SETOF vandelay.tcn_data AS $_$
767 output vandelay.tcn_data%ROWTYPE;
771 eg_tcn := BTRIM((oils_xpath('//*[@tag="001"]/text()',xml))[1]);
772 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
774 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="003"]/text()',xml))[1]);
775 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
776 eg_tcn_source := 'System Local';
779 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
782 output.used := FALSE;
787 output.tcn := eg_tcn;
788 output.tcn_source := eg_tcn_source;
794 eg_tcn := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="a"]/text()',xml))[1]);
795 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
797 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="b"]/text()',xml))[1]);
798 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
799 eg_tcn_source := 'System Local';
802 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
805 output.used := FALSE;
810 output.tcn := eg_tcn;
811 output.tcn_source := eg_tcn_source;
817 eg_tcn := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="a"]/text()',xml))[1]);
818 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
820 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="b"]/text()',xml))[1]);
821 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
822 eg_tcn_source := 'System Local';
825 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
828 output.used := FALSE;
833 output.tcn := eg_tcn;
834 output.tcn_source := eg_tcn_source;
840 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="020"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
841 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
843 eg_tcn_source := 'ISBN';
845 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
848 output.used := FALSE;
853 output.tcn := eg_tcn;
854 output.tcn_source := eg_tcn_source;
860 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="022"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
861 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
863 eg_tcn_source := 'ISSN';
865 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
868 output.used := FALSE;
873 output.tcn := eg_tcn;
874 output.tcn_source := eg_tcn_source;
880 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="010"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
881 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
883 eg_tcn_source := 'LCCN';
885 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
888 output.used := FALSE;
893 output.tcn := eg_tcn;
894 output.tcn_source := eg_tcn_source;
900 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="035"]/*[@code="a"]/text()',xml))[1], $re$^.*?(\w+)$$re$, $re$\1$re$);
901 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
903 eg_tcn_source := 'System Legacy';
905 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
908 output.used := FALSE;
913 output.tcn := eg_tcn;
914 output.tcn_source := eg_tcn_source;
921 $_$ LANGUAGE PLPGSQL;
923 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT, force_add INT ) RETURNS TEXT AS $_$
926 use MARC::File::XML (BinaryEncoding => 'UTF-8');
930 MARC::Charset->assume_unicode(1);
932 my $target_xml = shift;
933 my $source_xml = shift;
934 my $field_spec = shift;
935 my $force_add = shift || 0;
937 my $target_r = MARC::Record->new_from_xml( $target_xml );
938 my $source_r = MARC::Record->new_from_xml( $source_xml );
940 return $target_xml unless ($target_r && $source_r);
942 my @field_list = split(',', $field_spec);
945 for my $f (@field_list) {
946 $f =~ s/^\s*//; $f =~ s/\s*$//;
947 if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
953 $match =~ s/^\s*//; $match =~ s/\s*$//;
954 $fields{$field} = { sf => [ split('', $sf) ] };
956 my ($msf,$mre) = split('~', $match);
957 if (length($msf) > 0 and length($mre) > 0) {
958 $msf =~ s/^\s*//; $msf =~ s/\s*$//;
959 $mre =~ s/^\s*//; $mre =~ s/\s*$//;
960 $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
966 for my $f ( keys %fields) {
967 if ( @{$fields{$f}{sf}} ) {
968 for my $from_field ($source_r->field( $f )) {
969 my @tos = $target_r->field( $f );
971 next if (exists($fields{$f}{match}) and !$force_add);
972 my @new_fields = map { $_->clone } $source_r->field( $f );
973 $target_r->insert_fields_ordered( @new_fields );
975 for my $to_field (@tos) {
976 if (exists($fields{$f}{match})) {
977 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
979 my @new_sf = map { ($_ => $from_field->subfield($_)) } @{$fields{$f}{sf}};
980 $to_field->add_subfields( @new_sf );
985 my @new_fields = map { $_->clone } $source_r->field( $f );
986 $target_r->insert_fields_ordered( @new_fields );
990 $target_xml = $target_r->as_xml_record;
991 $target_xml =~ s/^<\?.+?\?>$//mo;
992 $target_xml =~ s/\n//sgo;
993 $target_xml =~ s/>\s+</></sgo;
997 $_$ LANGUAGE PLPERLU;
999 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1000 SELECT vandelay.add_field( $1, $2, $3, 0 );
1003 CREATE OR REPLACE FUNCTION vandelay.strip_field ( xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1006 use MARC::File::XML (BinaryEncoding => 'UTF-8');
1010 MARC::Charset->assume_unicode(1);
1013 my $r = MARC::Record->new_from_xml( $xml );
1015 return $xml unless ($r);
1017 my $field_spec = shift;
1018 my @field_list = split(',', $field_spec);
1021 for my $f (@field_list) {
1022 $f =~ s/^\s*//; $f =~ s/\s*$//;
1023 if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1029 $match =~ s/^\s*//; $match =~ s/\s*$//;
1030 $fields{$field} = { sf => [ split('', $sf) ] };
1032 my ($msf,$mre) = split('~', $match);
1033 if (length($msf) > 0 and length($mre) > 0) {
1034 $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1035 $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1036 $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1042 for my $f ( keys %fields) {
1043 for my $to_field ($r->field( $f )) {
1044 if (exists($fields{$f}{match})) {
1045 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1048 if ( @{$fields{$f}{sf}} ) {
1049 $to_field->delete_subfield(code => $fields{$f}{sf});
1051 $r->delete_field( $to_field );
1056 $xml = $r->as_xml_record;
1057 $xml =~ s/^<\?.+?\?>$//mo;
1059 $xml =~ s/>\s+</></sgo;
1063 $_$ LANGUAGE PLPERLU;
1065 CREATE OR REPLACE FUNCTION vandelay.replace_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1072 parsed_target := vandelay.strip_field( target_xml, ''); -- this dance normalizes the format of the xml for the IF below
1074 FOR curr_field IN SELECT UNNEST( STRING_TO_ARRAY(field, ',') ) LOOP -- naive split, but it's the same we use in the perl
1076 xml_output := vandelay.strip_field( parsed_target, curr_field);
1078 IF xml_output <> parsed_target AND curr_field ~ E'~' THEN
1079 -- we removed something, and there was a regexp restriction in the curr_field definition, so proceed
1080 xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 1 );
1081 ELSIF curr_field !~ E'~' THEN
1082 -- No regexp restriction, add the curr_field
1083 xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 0 );
1086 parsed_target := xml_output; -- in prep for any following loop iterations
1092 $_$ LANGUAGE PLPGSQL;
1094 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 $_$
1095 SELECT vandelay.replace_field( vandelay.add_field( vandelay.strip_field( $1, $5) , $2, $3 ), $2, $4);
1098 CREATE TYPE vandelay.compile_profile AS (add_rule TEXT, replace_rule TEXT, preserve_rule TEXT, strip_rule TEXT);
1099 CREATE OR REPLACE FUNCTION vandelay.compile_profile ( incoming_xml TEXT ) RETURNS vandelay.compile_profile AS $_$
1101 output vandelay.compile_profile%ROWTYPE;
1102 profile vandelay.merge_profile%ROWTYPE;
1104 profile_tmpl_owner TEXT;
1105 add_rule TEXT := '';
1106 strip_rule TEXT := '';
1107 replace_rule TEXT := '';
1108 preserve_rule TEXT := '';
1112 profile_tmpl := (oils_xpath('//*[@tag="905"]/*[@code="t"]/text()',incoming_xml))[1];
1113 profile_tmpl_owner := (oils_xpath('//*[@tag="905"]/*[@code="o"]/text()',incoming_xml))[1];
1115 IF profile_tmpl IS NOT NULL AND profile_tmpl <> '' AND profile_tmpl_owner IS NOT NULL AND profile_tmpl_owner <> '' THEN
1116 SELECT p.* INTO profile
1117 FROM vandelay.merge_profile p
1118 JOIN actor.org_unit u ON (u.id = p.owner)
1119 WHERE p.name = profile_tmpl
1120 AND u.shortname = profile_tmpl_owner;
1122 IF profile.id IS NOT NULL THEN
1123 add_rule := COALESCE(profile.add_spec,'');
1124 strip_rule := COALESCE(profile.strip_spec,'');
1125 replace_rule := COALESCE(profile.replace_spec,'');
1126 preserve_rule := COALESCE(profile.preserve_spec,'');
1130 add_rule := add_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="a"]/text()',incoming_xml),','),'');
1131 strip_rule := strip_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="d"]/text()',incoming_xml),','),'');
1132 replace_rule := replace_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="r"]/text()',incoming_xml),','),'');
1133 preserve_rule := preserve_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="p"]/text()',incoming_xml),','),'');
1135 output.add_rule := BTRIM(add_rule,',');
1136 output.replace_rule := BTRIM(replace_rule,',');
1137 output.strip_rule := BTRIM(strip_rule,',');
1138 output.preserve_rule := BTRIM(preserve_rule,',');
1142 $_$ LANGUAGE PLPGSQL;
1144 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1146 merge_profile vandelay.merge_profile%ROWTYPE;
1147 dyn_profile vandelay.compile_profile%ROWTYPE;
1157 SELECT b.marc INTO eg_marc
1158 FROM biblio.record_entry b
1162 IF eg_marc IS NULL OR v_marc IS NULL THEN
1163 -- RAISE NOTICE 'no marc for template or bib record';
1167 dyn_profile := vandelay.compile_profile( v_marc );
1169 IF merge_profile_id IS NOT NULL THEN
1170 SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1172 dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1173 dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1174 dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1175 dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1179 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1180 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1184 IF dyn_profile.replace_rule <> '' THEN
1185 source_marc = v_marc;
1186 target_marc = eg_marc;
1187 replace_rule = dyn_profile.replace_rule;
1189 source_marc = eg_marc;
1190 target_marc = v_marc;
1191 replace_rule = dyn_profile.preserve_rule;
1194 UPDATE biblio.record_entry
1195 SET marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1199 -- RAISE NOTICE 'update of biblio.record_entry failed';
1206 $$ LANGUAGE PLPGSQL;
1208 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_marc TEXT, template_marc TEXT ) RETURNS TEXT AS $$
1210 dyn_profile vandelay.compile_profile%ROWTYPE;
1218 IF target_marc IS NULL OR template_marc IS NULL THEN
1219 -- RAISE NOTICE 'no marc for target or template record';
1223 dyn_profile := vandelay.compile_profile( template_marc );
1225 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1226 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1230 IF dyn_profile.replace_rule <> '' THEN
1231 trgt_marc = target_marc;
1232 tmpl_marc = template_marc;
1233 replace_rule = dyn_profile.replace_rule;
1235 tmp_marc = target_marc;
1236 trgt_marc = template_marc;
1237 tmpl_marc = tmp_marc;
1238 replace_rule = dyn_profile.preserve_rule;
1241 RETURN vandelay.merge_record_xml( trgt_marc, tmpl_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
1244 $$ LANGUAGE PLPGSQL;
1246 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT) RETURNS BOOL AS $$
1247 SELECT vandelay.template_overlay_bib_record( $1, $2, NULL);
1250 CREATE OR REPLACE FUNCTION vandelay.overlay_bib_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1252 merge_profile vandelay.merge_profile%ROWTYPE;
1253 dyn_profile vandelay.compile_profile%ROWTYPE;
1263 SELECT q.marc INTO v_marc
1264 FROM vandelay.queued_record q
1265 JOIN vandelay.bib_match m ON (m.queued_record = q.id AND q.id = import_id)
1268 IF v_marc IS NULL THEN
1269 -- RAISE NOTICE 'no marc for vandelay or bib record';
1273 IF vandelay.template_overlay_bib_record( v_marc, eg_id, merge_profile_id) THEN
1274 UPDATE vandelay.queued_bib_record
1275 SET imported_as = eg_id,
1277 WHERE id = import_id;
1279 editor_string := (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
1281 IF editor_string IS NOT NULL AND editor_string <> '' THEN
1282 SELECT usr INTO editor_id FROM actor.card WHERE barcode = editor_string;
1284 IF editor_id IS NULL THEN
1285 SELECT id INTO editor_id FROM actor.usr WHERE usrname = editor_string;
1288 IF editor_id IS NOT NULL THEN
1289 UPDATE biblio.record_entry SET editor = editor_id WHERE id = eg_id;
1296 -- RAISE NOTICE 'update of biblio.record_entry failed';
1301 $$ LANGUAGE PLPGSQL;
1303 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 $$
1306 lwm_ratio_value NUMERIC;
1309 lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
1311 PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1314 -- RAISE NOTICE 'already imported, cannot auto-overlay'
1318 SELECT m.eg_record INTO eg_id
1319 FROM vandelay.bib_match m
1320 JOIN vandelay.queued_bib_record qr ON (m.queued_record = qr.id)
1321 JOIN vandelay.bib_queue q ON (qr.queue = q.id)
1322 JOIN biblio.record_entry r ON (r.id = m.eg_record)
1323 WHERE m.queued_record = import_id
1324 AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
1325 ORDER BY m.match_score DESC, -- required match score
1326 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
1327 m.id -- when in doubt, use the first match
1330 IF eg_id IS NULL THEN
1331 -- RAISE NOTICE 'incoming record is not of high enough quality';
1335 RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1337 $$ LANGUAGE PLPGSQL;
1339 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1340 SELECT vandelay.auto_overlay_bib_record_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1343 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1349 PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1352 -- RAISE NOTICE 'already imported, cannot auto-overlay'
1356 SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
1358 IF match_count <> 1 THEN
1359 -- RAISE NOTICE 'not an exact match';
1363 -- Check that the one match is on the first 901c
1364 SELECT m.eg_record INTO eg_id
1365 FROM vandelay.queued_bib_record q
1366 JOIN vandelay.bib_match m ON (m.queued_record = q.id)
1367 WHERE q.id = import_id
1368 AND m.eg_record = oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]',marc)::BIGINT;
1371 -- RAISE NOTICE 'not a 901c match';
1375 RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1377 $$ LANGUAGE PLPGSQL;
1379 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1381 queued_record vandelay.queued_bib_record%ROWTYPE;
1384 FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1386 IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
1387 RETURN NEXT queued_record.id;
1395 $$ LANGUAGE PLPGSQL;
1397 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 $$
1399 queued_record vandelay.queued_bib_record%ROWTYPE;
1402 FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1404 IF vandelay.auto_overlay_bib_record_with_best( queued_record.id, merge_profile_id, lwm_ratio_value ) THEN
1405 RETURN NEXT queued_record.id;
1413 $$ LANGUAGE PLPGSQL;
1415 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1416 SELECT vandelay.auto_overlay_bib_queue_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1419 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1420 SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
1423 CREATE OR REPLACE FUNCTION vandelay.ingest_items ( import_id BIGINT, attr_def_id BIGINT ) RETURNS SETOF vandelay.import_item AS $$
1434 deposit_amount TEXT;
1447 tmp_attr_set RECORD;
1448 attr_set vandelay.import_item%ROWTYPE;
1454 SELECT * INTO attr_def FROM vandelay.import_item_attr_definition WHERE id = attr_def_id;
1458 attr_set.definition := attr_def.id;
1460 -- Build the combined XPath
1464 WHEN attr_def.owning_lib IS NULL THEN 'null()'
1465 WHEN LENGTH( attr_def.owning_lib ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.owning_lib || '"]'
1466 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.owning_lib
1471 WHEN attr_def.circ_lib IS NULL THEN 'null()'
1472 WHEN LENGTH( attr_def.circ_lib ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_lib || '"]'
1473 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_lib
1478 WHEN attr_def.call_number IS NULL THEN 'null()'
1479 WHEN LENGTH( attr_def.call_number ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.call_number || '"]'
1480 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.call_number
1485 WHEN attr_def.copy_number IS NULL THEN 'null()'
1486 WHEN LENGTH( attr_def.copy_number ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.copy_number || '"]'
1487 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.copy_number
1492 WHEN attr_def.status IS NULL THEN 'null()'
1493 WHEN LENGTH( attr_def.status ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.status || '"]'
1494 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.status
1499 WHEN attr_def.location IS NULL THEN 'null()'
1500 WHEN LENGTH( attr_def.location ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.location || '"]'
1501 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.location
1506 WHEN attr_def.circulate IS NULL THEN 'null()'
1507 WHEN LENGTH( attr_def.circulate ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circulate || '"]'
1508 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circulate
1513 WHEN attr_def.deposit IS NULL THEN 'null()'
1514 WHEN LENGTH( attr_def.deposit ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.deposit || '"]'
1515 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.deposit
1520 WHEN attr_def.deposit_amount IS NULL THEN 'null()'
1521 WHEN LENGTH( attr_def.deposit_amount ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.deposit_amount || '"]'
1522 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.deposit_amount
1527 WHEN attr_def.ref IS NULL THEN 'null()'
1528 WHEN LENGTH( attr_def.ref ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.ref || '"]'
1529 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.ref
1534 WHEN attr_def.holdable IS NULL THEN 'null()'
1535 WHEN LENGTH( attr_def.holdable ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.holdable || '"]'
1536 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.holdable
1541 WHEN attr_def.price IS NULL THEN 'null()'
1542 WHEN LENGTH( attr_def.price ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.price || '"]'
1543 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.price
1548 WHEN attr_def.barcode IS NULL THEN 'null()'
1549 WHEN LENGTH( attr_def.barcode ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.barcode || '"]'
1550 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.barcode
1555 WHEN attr_def.circ_modifier IS NULL THEN 'null()'
1556 WHEN LENGTH( attr_def.circ_modifier ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_modifier || '"]'
1557 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_modifier
1562 WHEN attr_def.circ_as_type IS NULL THEN 'null()'
1563 WHEN LENGTH( attr_def.circ_as_type ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.circ_as_type || '"]'
1564 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.circ_as_type
1569 WHEN attr_def.alert_message IS NULL THEN 'null()'
1570 WHEN LENGTH( attr_def.alert_message ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.alert_message || '"]'
1571 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.alert_message
1576 WHEN attr_def.opac_visible IS NULL THEN 'null()'
1577 WHEN LENGTH( attr_def.opac_visible ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.opac_visible || '"]'
1578 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.opac_visible
1583 WHEN attr_def.pub_note IS NULL THEN 'null()'
1584 WHEN LENGTH( attr_def.pub_note ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.pub_note || '"]'
1585 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.pub_note
1589 WHEN attr_def.priv_note IS NULL THEN 'null()'
1590 WHEN LENGTH( attr_def.priv_note ) = 1 THEN '//*[@tag="' || attr_def.tag || '"]/*[@code="' || attr_def.priv_note || '"]'
1591 ELSE '//*[@tag="' || attr_def.tag || '"]/*' || attr_def.priv_note
1596 owning_lib || '|' ||
1598 call_number || '|' ||
1599 copy_number || '|' ||
1604 deposit_amount || '|' ||
1609 circ_modifier || '|' ||
1610 circ_as_type || '|' ||
1611 alert_message || '|' ||
1616 -- RAISE NOTICE 'XPath: %', xpath;
1620 FROM oils_xpath_table( 'id', 'marc', 'vandelay.queued_bib_record', xpath, 'id = ' || import_id )
1621 AS t( id INT, ol TEXT, clib TEXT, cn TEXT, cnum TEXT, cs TEXT, cl TEXT, circ TEXT,
1622 dep TEXT, dep_amount TEXT, r TEXT, hold TEXT, pr TEXT, bc TEXT, circ_mod TEXT,
1623 circ_as TEXT, amessage TEXT, note TEXT, pnote TEXT, opac_vis TEXT )
1626 tmp_attr_set.pr = REGEXP_REPLACE(tmp_attr_set.pr, E'[^0-9\\.]', '', 'g');
1627 tmp_attr_set.dep_amount = REGEXP_REPLACE(tmp_attr_set.dep_amount, E'[^0-9\\.]', '', 'g');
1629 tmp_attr_set.pr := NULLIF( tmp_attr_set.pr, '' );
1630 tmp_attr_set.dep_amount := NULLIF( tmp_attr_set.dep_amount, '' );
1632 SELECT id INTO attr_set.owning_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.ol); -- INT
1633 SELECT id INTO attr_set.circ_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.clib); -- INT
1634 SELECT id INTO attr_set.status FROM config.copy_status WHERE LOWER(name) = LOWER(tmp_attr_set.cs); -- INT
1636 SELECT id INTO attr_set.location
1637 FROM asset.copy_location
1638 WHERE LOWER(name) = LOWER(tmp_attr_set.cl)
1639 AND asset.copy_location.owning_lib = COALESCE(attr_set.owning_lib, attr_set.circ_lib); -- INT
1641 attr_set.circulate :=
1642 LOWER( SUBSTRING( tmp_attr_set.circ, 1, 1)) IN ('t','y','1')
1643 OR LOWER(tmp_attr_set.circ) = 'circulating'; -- BOOL
1646 LOWER( SUBSTRING( tmp_attr_set.dep, 1, 1 ) ) IN ('t','y','1')
1647 OR LOWER(tmp_attr_set.dep) = 'deposit'; -- BOOL
1649 attr_set.holdable :=
1650 LOWER( SUBSTRING( tmp_attr_set.hold, 1, 1 ) ) IN ('t','y','1')
1651 OR LOWER(tmp_attr_set.hold) = 'holdable'; -- BOOL
1653 attr_set.opac_visible :=
1654 LOWER( SUBSTRING( tmp_attr_set.opac_vis, 1, 1 ) ) IN ('t','y','1')
1655 OR LOWER(tmp_attr_set.opac_vis) = 'visible'; -- BOOL
1658 LOWER( SUBSTRING( tmp_attr_set.r, 1, 1 ) ) IN ('t','y','1')
1659 OR LOWER(tmp_attr_set.r) = 'reference'; -- BOOL
1661 attr_set.copy_number := tmp_attr_set.cnum::INT; -- INT,
1662 attr_set.deposit_amount := tmp_attr_set.dep_amount::NUMERIC(6,2); -- NUMERIC(6,2),
1663 attr_set.price := tmp_attr_set.pr::NUMERIC(8,2); -- NUMERIC(8,2),
1665 attr_set.call_number := tmp_attr_set.cn; -- TEXT
1666 attr_set.barcode := tmp_attr_set.bc; -- TEXT,
1667 attr_set.circ_modifier := tmp_attr_set.circ_mod; -- TEXT,
1668 attr_set.circ_as_type := tmp_attr_set.circ_as; -- TEXT,
1669 attr_set.alert_message := tmp_attr_set.amessage; -- TEXT,
1670 attr_set.pub_note := tmp_attr_set.note; -- TEXT,
1671 attr_set.priv_note := tmp_attr_set.pnote; -- TEXT,
1672 attr_set.alert_message := tmp_attr_set.amessage; -- TEXT,
1674 RETURN NEXT attr_set;
1683 $$ LANGUAGE PLPGSQL;
1686 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_marc ( ) RETURNS TRIGGER AS $$
1692 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1696 FOR adef IN SELECT * FROM vandelay.bib_attr_definition LOOP
1698 SELECT extract_marc_field('vandelay.queued_bib_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_bib_record WHERE id = NEW.id;
1699 IF (value IS NOT NULL AND value <> '') THEN
1700 INSERT INTO vandelay.queued_bib_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1707 $$ LANGUAGE PLPGSQL;
1709 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_items ( ) RETURNS TRIGGER AS $func$
1712 item_data vandelay.import_item%ROWTYPE;
1715 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1719 SELECT item_attr_def INTO attr_def FROM vandelay.bib_queue WHERE id = NEW.queue;
1721 FOR item_data IN SELECT * FROM vandelay.ingest_items( NEW.id::BIGINT, attr_def ) LOOP
1722 INSERT INTO vandelay.import_item (
1746 item_data.definition,
1747 item_data.owning_lib,
1749 item_data.call_number,
1750 item_data.copy_number,
1753 item_data.circulate,
1755 item_data.deposit_amount,
1760 item_data.circ_modifier,
1761 item_data.circ_as_type,
1762 item_data.alert_message,
1764 item_data.priv_note,
1765 item_data.opac_visible
1771 $func$ LANGUAGE PLPGSQL;
1773 CREATE OR REPLACE FUNCTION vandelay.match_bib_record ( ) RETURNS TRIGGER AS $func$
1782 DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
1784 SELECT * INTO attr_def FROM vandelay.bib_attr_definition WHERE xpath = '//*[@tag="901"]/*[@code="c"]' ORDER BY id LIMIT 1;
1786 IF attr_def IS NOT NULL AND attr_def.id IS NOT NULL THEN
1787 id_value := extract_marc_field('vandelay.queued_bib_record', NEW.id, attr_def.xpath, attr_def.remove);
1789 IF id_value IS NOT NULL AND id_value <> '' AND id_value ~ $r$^\d+$$r$ THEN
1790 SELECT id INTO exact_id FROM biblio.record_entry WHERE id = id_value::BIGINT AND NOT deleted;
1791 SELECT * INTO attr FROM vandelay.queued_bib_record_attr WHERE record = NEW.id and field = attr_def.id LIMIT 1;
1792 IF exact_id IS NOT NULL THEN
1793 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, exact_id);
1798 IF exact_id IS NULL THEN
1799 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
1801 -- All numbers? check for an id match
1802 IF (attr.attr_value ~ $r$^\d+$$r$) THEN
1803 FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE id = attr.attr_value::BIGINT AND deleted IS FALSE LOOP
1804 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, eg_rec.id);
1808 -- Looks like an ISBN? check for an isbn match
1809 IF (attr.attr_value ~* $r$^[0-9x]+$$r$ AND character_length(attr.attr_value) IN (10,13)) THEN
1810 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
1811 PERFORM id FROM biblio.record_entry WHERE id = eg_rec.record AND deleted IS FALSE;
1813 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('isbn', attr.id, NEW.id, eg_rec.record);
1817 -- subcheck for isbn-as-tcn
1818 FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = 'i' || attr.attr_value AND deleted IS FALSE LOOP
1819 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
1823 -- check for an OCLC tcn_value match
1824 IF (attr.attr_value ~ $r$^o\d+$$r$) THEN
1825 FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = regexp_replace(attr.attr_value,'^o','ocm') AND deleted IS FALSE LOOP
1826 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
1830 -- check for a direct tcn_value match
1831 FOR eg_rec IN SELECT * FROM biblio.record_entry WHERE tcn_value = attr.attr_value AND deleted IS FALSE LOOP
1832 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('tcn_value', attr.id, NEW.id, eg_rec.id);
1835 -- check for a direct item barcode match
1838 FROM biblio.record_entry b
1839 JOIN asset.call_number cn ON (cn.record = b.id)
1840 JOIN asset.copy cp ON (cp.call_number = cn.id)
1841 WHERE cp.barcode = attr.attr_value AND cp.deleted IS FALSE
1843 INSERT INTO vandelay.bib_match (field_type, matched_attr, queued_record, eg_record) VALUES ('id', attr.id, NEW.id, eg_rec.id);
1851 $func$ LANGUAGE PLPGSQL;
1853 CREATE OR REPLACE FUNCTION vandelay.cleanup_bib_marc ( ) RETURNS TRIGGER AS $$
1855 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1859 DELETE FROM vandelay.queued_bib_record_attr WHERE record = OLD.id;
1860 DELETE FROM vandelay.import_item WHERE record = OLD.id;
1862 IF TG_OP = 'UPDATE' THEN
1867 $$ LANGUAGE PLPGSQL;
1869 CREATE TRIGGER cleanup_bib_trigger
1870 BEFORE UPDATE OR DELETE ON vandelay.queued_bib_record
1871 FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_bib_marc();
1873 CREATE TRIGGER ingest_bib_trigger
1874 AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1875 FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_marc();
1877 CREATE TRIGGER ingest_item_trigger
1878 AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1879 FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_items();
1881 CREATE TRIGGER zz_match_bibs_trigger
1882 BEFORE INSERT OR UPDATE ON vandelay.queued_bib_record
1883 FOR EACH ROW EXECUTE PROCEDURE vandelay.match_bib_record();
1886 /* Authority stuff down here */
1887 ---------------------------------------
1888 CREATE TABLE vandelay.authority_attr_definition (
1889 id SERIAL PRIMARY KEY,
1890 code TEXT UNIQUE NOT NULL,
1892 xpath TEXT NOT NULL,
1893 remove TEXT NOT NULL DEFAULT ''
1896 CREATE TABLE vandelay.authority_queue (
1897 queue_type TEXT NOT NULL DEFAULT 'authority' CHECK (queue_type = 'authority'),
1898 CONSTRAINT vand_authority_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
1899 ) INHERITS (vandelay.queue);
1900 ALTER TABLE vandelay.authority_queue ADD PRIMARY KEY (id);
1902 CREATE TABLE vandelay.queued_authority_record (
1903 queue INT NOT NULL REFERENCES vandelay.authority_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1904 imported_as INT REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1905 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
1907 ) INHERITS (vandelay.queued_record);
1908 ALTER TABLE vandelay.queued_authority_record ADD PRIMARY KEY (id);
1909 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
1911 CREATE TABLE vandelay.queued_authority_record_attr (
1912 id BIGSERIAL PRIMARY KEY,
1913 record BIGINT NOT NULL REFERENCES vandelay.queued_authority_record (id) DEFERRABLE INITIALLY DEFERRED,
1914 field INT NOT NULL REFERENCES vandelay.authority_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
1915 attr_value TEXT NOT NULL
1917 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
1919 CREATE TABLE vandelay.authority_match (
1920 id BIGSERIAL PRIMARY KEY,
1921 queued_record BIGINT REFERENCES vandelay.queued_authority_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1922 eg_record BIGINT REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1923 quality INT NOT NULL DEFAULT 0
1926 CREATE OR REPLACE FUNCTION vandelay.ingest_authority_marc ( ) RETURNS TRIGGER AS $$
1932 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1936 FOR adef IN SELECT * FROM vandelay.authority_attr_definition LOOP
1938 SELECT extract_marc_field('vandelay.queued_authority_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_authority_record WHERE id = NEW.id;
1939 IF (value IS NOT NULL AND value <> '') THEN
1940 INSERT INTO vandelay.queued_authority_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1947 $$ LANGUAGE PLPGSQL;
1949 CREATE OR REPLACE FUNCTION vandelay.cleanup_authority_marc ( ) RETURNS TRIGGER AS $$
1951 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1955 DELETE FROM vandelay.queued_authority_record_attr WHERE record = OLD.id;
1956 IF TG_OP = 'UPDATE' THEN
1961 $$ LANGUAGE PLPGSQL;
1963 CREATE TRIGGER cleanup_authority_trigger
1964 BEFORE UPDATE OR DELETE ON vandelay.queued_authority_record
1965 FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_authority_marc();
1967 CREATE TRIGGER ingest_authority_trigger
1968 AFTER INSERT OR UPDATE ON vandelay.queued_authority_record
1969 FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_authority_marc();
1971 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1973 merge_profile vandelay.merge_profile%ROWTYPE;
1974 dyn_profile vandelay.compile_profile%ROWTYPE;
1983 SELECT b.marc INTO eg_marc
1984 FROM authority.record_entry b
1985 JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
1988 SELECT q.marc INTO v_marc
1989 FROM vandelay.queued_record q
1990 JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
1993 IF eg_marc IS NULL OR v_marc IS NULL THEN
1994 -- RAISE NOTICE 'no marc for vandelay or authority record';
1998 dyn_profile := vandelay.compile_profile( v_marc );
2000 IF merge_profile_id IS NOT NULL THEN
2001 SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
2003 dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
2004 dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
2005 dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
2006 dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
2010 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
2011 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
2015 IF dyn_profile.replace_rule <> '' THEN
2016 source_marc = v_marc;
2017 target_marc = eg_marc;
2018 replace_rule = dyn_profile.replace_rule;
2020 source_marc = eg_marc;
2021 target_marc = v_marc;
2022 replace_rule = dyn_profile.preserve_rule;
2025 UPDATE authority.record_entry
2026 SET marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
2030 UPDATE vandelay.queued_authority_record
2031 SET imported_as = eg_id,
2033 WHERE id = import_id;
2037 -- RAISE NOTICE 'update of authority.record_entry failed';
2042 $$ LANGUAGE PLPGSQL;
2044 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
2049 SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
2051 IF match_count <> 1 THEN
2052 -- RAISE NOTICE 'not an exact match';
2056 SELECT m.eg_record INTO eg_id
2057 FROM vandelay.authority_match m
2058 WHERE m.queued_record = import_id
2061 IF eg_id IS NULL THEN
2065 RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
2067 $$ LANGUAGE PLPGSQL;
2069 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
2071 queued_record vandelay.queued_authority_record%ROWTYPE;
2074 FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
2076 IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
2077 RETURN NEXT queued_record.id;
2085 $$ LANGUAGE PLPGSQL;
2087 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
2088 SELECT * FROM vandelay.auto_overlay_authority_queue( $1, NULL );
2092 -- Vandelay (for importing and exporting records) 012.schema.vandelay.sql
2093 --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)]');
2094 --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)]');
2095 --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]');
2096 --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]');
2097 --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$);
2098 --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$);
2099 --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]');
2100 --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);
2101 --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);
2102 --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);
2103 --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);
2104 --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]');
2105 --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$);
2106 --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]');
2108 --INSERT INTO vandelay.import_item_attr_definition (
2109 -- owner, name, tag, owning_lib, circ_lib, location,
2110 -- call_number, circ_modifier, barcode, price, copy_number,
2111 -- circulate, ref, holdable, opac_visible, status
2114 -- 'Evergreen 852 export format',
2116 -- '[@code = "b"][1]',
2117 -- '[@code = "b"][2]',
2124 -- '[@code = "x" and text() = "circulating"]',
2125 -- '[@code = "x" and text() = "reference"]',
2126 -- '[@code = "x" and text() = "holdable"]',
2127 -- '[@code = "x" and text() = "visible"]',
2131 --INSERT INTO vandelay.import_item_attr_definition (
2144 -- 'Unicorn Import format -- 999',
2155 --INSERT INTO vandelay.authority_attr_definition ( code, description, xpath, ident ) VALUES ('rec_identifier','Identifier','//*[@tag="001"]', TRUE);