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 heading BOOLEAN NOT NULL DEFAULT FALSE, -- match on authority heading
27 CONSTRAINT vmsp_need_a_subfield_with_a_tag CHECK ((tag IS NOT NULL AND subfield IS NOT NULL) OR tag IS NULL),
28 CONSTRAINT vmsp_need_a_tag_or_a_ff_or_a_bo CHECK (
29 (tag IS NOT NULL AND svf IS NULL AND heading IS FALSE AND bool_op IS NULL) OR
30 (tag IS NULL AND svf IS NOT NULL AND heading IS FALSE AND bool_op IS NULL) OR
31 (tag IS NULL AND svf IS NULL AND heading IS TRUE AND bool_op IS NULL) OR
32 (tag IS NULL AND svf IS NULL AND heading IS FALSE AND bool_op IS NOT NULL)
36 CREATE TABLE vandelay.match_set_quality (
37 id SERIAL PRIMARY KEY,
38 match_set INT NOT NULL REFERENCES vandelay.match_set (id) ON DELETE CASCADE,
39 svf TEXT REFERENCES config.record_attr_definition,
43 quality INT NOT NULL DEFAULT 1, -- higher is better
44 CONSTRAINT vmsq_need_a_subfield_with_a_tag CHECK ((tag IS NOT NULL AND subfield IS NOT NULL) OR tag IS NULL),
45 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))
47 CREATE UNIQUE INDEX vmsq_def_once_per_set ON vandelay.match_set_quality (match_set, COALESCE(tag,''), COALESCE(subfield,''), COALESCE(svf,''), value);
50 CREATE TABLE vandelay.queue (
51 id BIGSERIAL PRIMARY KEY,
52 owner INT NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
54 complete BOOL NOT NULL DEFAULT FALSE,
55 match_set INT REFERENCES vandelay.match_set (id) ON UPDATE CASCADE ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED
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,
110 CONSTRAINT vand_import_item_attr_def_idx UNIQUE (owner,name)
113 CREATE TABLE vandelay.import_error (
114 code TEXT PRIMARY KEY,
115 description TEXT NOT NULL -- i18n
118 CREATE TYPE vandelay.bib_queue_queue_type AS ENUM ('bib', 'acq');
120 CREATE TABLE vandelay.bib_queue (
121 queue_type vandelay.bib_queue_queue_type NOT NULL DEFAULT 'bib',
122 item_attr_def BIGINT REFERENCES vandelay.import_item_attr_definition (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
123 match_bucket INTEGER, -- REFERENCES container.biblio_record_entry_bucket(id);
124 CONSTRAINT vand_bib_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
125 ) INHERITS (vandelay.queue);
126 ALTER TABLE vandelay.bib_queue ADD PRIMARY KEY (id);
128 CREATE TABLE vandelay.queued_bib_record (
129 queue INT NOT NULL REFERENCES vandelay.bib_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
130 bib_source INT REFERENCES config.bib_source (id) DEFERRABLE INITIALLY DEFERRED,
131 imported_as BIGINT REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
132 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
134 ) INHERITS (vandelay.queued_record);
135 ALTER TABLE vandelay.queued_bib_record ADD PRIMARY KEY (id);
136 CREATE INDEX queued_bib_record_queue_idx ON vandelay.queued_bib_record (queue);
138 CREATE TABLE vandelay.queued_bib_record_attr (
139 id BIGSERIAL PRIMARY KEY,
140 record BIGINT NOT NULL REFERENCES vandelay.queued_bib_record (id) DEFERRABLE INITIALLY DEFERRED,
141 field INT NOT NULL REFERENCES vandelay.bib_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
142 attr_value TEXT NOT NULL
144 CREATE INDEX queued_bib_record_attr_record_idx ON vandelay.queued_bib_record_attr (record);
146 CREATE TABLE vandelay.bib_match (
147 id BIGSERIAL PRIMARY KEY,
148 queued_record BIGINT REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
149 eg_record BIGINT REFERENCES biblio.record_entry (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
150 quality INT NOT NULL DEFAULT 1,
151 match_score INT NOT NULL DEFAULT 0
154 CREATE TABLE vandelay.import_item (
155 id BIGSERIAL PRIMARY KEY,
156 record BIGINT NOT NULL REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
157 definition BIGINT NOT NULL REFERENCES vandelay.import_item_attr_definition (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
158 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
161 import_time TIMESTAMP WITH TIME ZONE,
170 deposit_amount NUMERIC(8,2),
181 internal_id BIGINT -- queue_type == 'acq' ? acq.lineitem_detail.id : asset.copy.id
184 CREATE TABLE vandelay.import_bib_trash_group(
185 id SERIAL PRIMARY KEY,
186 owner INTEGER NOT NULL REFERENCES actor.org_unit(id),
187 label TEXT NOT NULL, --i18n
188 always_apply BOOLEAN NOT NULL DEFAULT FALSE,
189 CONSTRAINT vand_import_bib_trash_grp_owner_label UNIQUE (owner, label)
192 CREATE TABLE vandelay.import_bib_trash_fields (
193 id BIGSERIAL PRIMARY KEY,
194 grp INTEGER NOT NULL REFERENCES vandelay.import_bib_trash_group,
196 CONSTRAINT vand_import_bib_trash_fields_once_per UNIQUE (grp, field)
199 CREATE TABLE vandelay.merge_profile (
200 id BIGSERIAL PRIMARY KEY,
201 owner INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
208 CONSTRAINT vand_merge_prof_owner_name_idx UNIQUE (owner,name),
209 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))
212 CREATE OR REPLACE FUNCTION vandelay.marc21_record_type( marc TEXT ) RETURNS config.marc21_rec_type_map AS $func$
219 retval config.marc21_rec_type_map%ROWTYPE;
221 ldr := oils_xpath_string( '//*[local-name()="leader"]', marc );
223 IF ldr IS NULL OR ldr = '' THEN
224 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
228 SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
229 SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
232 tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
233 bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
235 -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
237 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
240 IF retval.code IS NULL THEN
241 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
246 $func$ LANGUAGE PLPGSQL;
248 CREATE TYPE biblio.record_ff_map AS (record BIGINT, ff_name TEXT, ff_value TEXT);
249 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$
254 output biblio.record_ff_map%ROWTYPE;
256 rtype := (vandelay.marc21_record_type( marc )).code;
258 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE rec_type = rtype ORDER BY tag DESC LOOP
259 output.ff_name := ff_pos.fixed_field;
260 output.ff_value := NULL;
262 IF ff_pos.tag = 'ldr' THEN
263 output.ff_value := oils_xpath_string('//*[local-name()="leader"]', marc);
264 IF output.ff_value IS NOT NULL THEN
265 output.ff_value := SUBSTRING( output.ff_value, ff_pos.start_pos + 1, ff_pos.length );
267 output.ff_value := NULL;
270 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
271 output.ff_value := SUBSTRING( tag_data, ff_pos.start_pos + 1, ff_pos.length );
272 CONTINUE WHEN output.ff_value IS NULL AND NOT use_default;
273 IF output.ff_value IS NULL THEN output.ff_value := REPEAT( ff_pos.default_val, ff_pos.length ); END IF;
275 output.ff_value := NULL;
283 $func$ LANGUAGE PLPGSQL;
285 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field_list( marc TEXT, ff TEXT, use_default BOOL DEFAULT FALSE ) RETURNS TEXT[] AS $func$
291 collection TEXT[] := '{}'::TEXT[];
293 rtype := (vandelay.marc21_record_type( marc )).code;
294 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
295 IF ff_pos.tag = 'ldr' THEN
296 val := oils_xpath_string('//*[local-name()="leader"]', marc);
297 IF val IS NOT NULL THEN
298 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
299 collection := collection || val;
302 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
303 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
304 collection := collection || val;
307 CONTINUE WHEN NOT use_default;
308 CONTINUE WHEN ARRAY_UPPER(collection, 1) > 0;
309 val := REPEAT( ff_pos.default_val, ff_pos.length );
310 collection := collection || val;
315 $func$ LANGUAGE PLPGSQL;
317 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field( marc TEXT, ff TEXT, use_default BOOL DEFAULT FALSE ) RETURNS TEXT AS $func$
324 rtype := (vandelay.marc21_record_type( marc )).code;
325 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
326 IF ff_pos.tag = 'ldr' THEN
327 val := oils_xpath_string('//*[local-name()="leader"]', marc);
328 IF val IS NOT NULL THEN
329 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
333 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
334 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
338 CONTINUE WHEN NOT use_default;
339 val := REPEAT( ff_pos.default_val, ff_pos.length );
345 $func$ LANGUAGE PLPGSQL;
347 CREATE TYPE biblio.marc21_physical_characteristics AS ( id INT, record BIGINT, ptype TEXT, subfield INT, value INT );
348 CREATE OR REPLACE FUNCTION vandelay.marc21_physical_characteristics( marc TEXT) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
352 ptype config.marc21_physical_characteristic_type_map%ROWTYPE;
353 psf config.marc21_physical_characteristic_subfield_map%ROWTYPE;
354 pval config.marc21_physical_characteristic_value_map%ROWTYPE;
355 retval biblio.marc21_physical_characteristics%ROWTYPE;
358 FOR _007 IN SELECT oils_xpath_string('//*', value) FROM UNNEST(oils_xpath('//*[@tag="007"]', marc)) x(value) LOOP
359 IF _007 IS NOT NULL AND _007 <> '' THEN
360 SELECT * INTO ptype FROM config.marc21_physical_characteristic_type_map WHERE ptype_key = SUBSTRING( _007, 1, 1 );
362 IF ptype.ptype_key IS NOT NULL THEN
363 FOR psf IN SELECT * FROM config.marc21_physical_characteristic_subfield_map WHERE ptype_key = ptype.ptype_key LOOP
364 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 );
366 IF pval.id IS NOT NULL THEN
369 retval.ptype := ptype.ptype_key;
370 retval.subfield := psf.id;
371 retval.value := pval.id;
382 $func$ LANGUAGE PLPGSQL;
384 CREATE TYPE vandelay.flat_marc AS ( tag CHAR(3), ind1 TEXT, ind2 TEXT, subfield TEXT, value TEXT );
385 CREATE OR REPLACE FUNCTION vandelay.flay_marc ( TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
388 use MARC::File::XML (BinaryEncoding => 'UTF-8');
392 MARC::Charset->assume_unicode(1);
395 my $r = MARC::Record->new_from_xml( $xml );
397 return_next( { tag => 'LDR', value => $r->leader } );
399 for my $f ( $r->fields ) {
400 if ($f->is_control_field) {
401 return_next({ tag => $f->tag, value => $f->data });
403 for my $s ($f->subfields) {
406 ind1 => $f->indicator(1),
407 ind2 => $f->indicator(2),
412 if ( $f->tag eq '245' and $s->[0] eq 'a' ) {
413 my $trim = $f->indicator(2) || 0;
416 ind1 => $f->indicator(1),
417 ind2 => $f->indicator(2),
419 value => substr( $s->[1], $trim )
428 $func$ LANGUAGE PLPERLU;
430 CREATE OR REPLACE FUNCTION vandelay.flatten_marc ( marc TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
432 output vandelay.flat_marc%ROWTYPE;
435 FOR field IN SELECT * FROM vandelay.flay_marc( marc ) LOOP
436 output.ind1 := field.ind1;
437 output.ind2 := field.ind2;
438 output.tag := field.tag;
439 output.subfield := field.subfield;
440 IF field.subfield IS NOT NULL AND field.tag NOT IN ('020','022','024') THEN -- exclude standard numbers and control fields
441 output.value := naco_normalize(field.value, field.subfield);
443 output.value := field.value;
446 CONTINUE WHEN output.value IS NULL;
451 $func$ LANGUAGE PLPGSQL;
453 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT, attr_defs TEXT[]) RETURNS hstore AS $_$
455 transformed_xml TEXT;
458 xfrm config.xml_transform%ROWTYPE;
460 new_attrs HSTORE := ''::HSTORE;
461 attr_def config.record_attr_definition%ROWTYPE;
464 FOR attr_def IN SELECT * FROM config.record_attr_definition WHERE name IN (SELECT * FROM UNNEST(attr_defs)) ORDER BY format LOOP
466 IF attr_def.tag IS NOT NULL THEN -- tag (and optional subfield list) selection
467 SELECT STRING_AGG(x.value, COALESCE(attr_def.joiner,' ')) INTO attr_value
468 FROM vandelay.flatten_marc(xml) AS x
469 WHERE x.tag LIKE attr_def.tag
471 WHEN attr_def.sf_list IS NOT NULL
472 THEN POSITION(x.subfield IN attr_def.sf_list) > 0
479 ELSIF attr_def.fixed_field IS NOT NULL THEN -- a named fixed field, see config.marc21_ff_pos_map.fixed_field
480 attr_value := vandelay.marc21_extract_fixed_field(xml, attr_def.fixed_field);
482 ELSIF attr_def.xpath IS NOT NULL THEN -- and xpath expression
484 SELECT INTO xfrm * FROM config.xml_transform WHERE name = attr_def.format;
486 -- See if we can skip the XSLT ... it's expensive
487 IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
488 -- Can't skip the transform
489 IF xfrm.xslt <> '---' THEN
490 transformed_xml := oils_xslt_process(xml,xfrm.xslt);
492 transformed_xml := xml;
495 prev_xfrm := xfrm.name;
498 IF xfrm.name IS NULL THEN
499 -- just grab the marcxml (empty) transform
500 SELECT INTO xfrm * FROM config.xml_transform WHERE xslt = '---' LIMIT 1;
501 prev_xfrm := xfrm.name;
504 attr_value := oils_xpath_string(attr_def.xpath, transformed_xml, COALESCE(attr_def.joiner,' '), ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]);
506 ELSIF attr_def.phys_char_sf IS NOT NULL THEN -- a named Physical Characteristic, see config.marc21_physical_characteristic_*_map
507 SELECT m.value::TEXT INTO attr_value
508 FROM vandelay.marc21_physical_characteristics(xml) v
509 JOIN config.marc21_physical_characteristic_value_map m ON (m.id = v.value)
510 WHERE v.subfield = attr_def.phys_char_sf
511 LIMIT 1; -- Just in case ...
515 -- apply index normalizers to attr_value
517 SELECT n.func AS func,
518 n.param_count AS param_count,
520 FROM config.index_normalizer n
521 JOIN config.record_attr_index_norm_map m ON (m.norm = n.id)
522 WHERE attr = attr_def.name
524 EXECUTE 'SELECT ' || normalizer.func || '(' ||
525 quote_nullable( attr_value ) ||
527 WHEN normalizer.param_count > 0
528 THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
535 -- Add the new value to the hstore
536 new_attrs := new_attrs || hstore( attr_def.name, attr_value );
542 $_$ LANGUAGE PLPGSQL;
544 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT ) RETURNS hstore AS $_$
545 SELECT vandelay.extract_rec_attrs( $1, (SELECT ARRAY_AGG(name) FROM config.record_attr_definition));
548 -- Everything between this comment and the beginning of the definition of
549 -- vandelay.match_bib_record() is strictly in service of that function.
550 CREATE TYPE vandelay.match_set_test_result AS (record BIGINT, quality INTEGER);
552 CREATE OR REPLACE FUNCTION vandelay.match_set_test_marcxml(
553 match_set_id INTEGER, record_xml TEXT, bucket_id INTEGER
554 ) RETURNS SETOF vandelay.match_set_test_result AS $$
565 tags_rstore := vandelay.flatten_marc_hstore(record_xml);
566 svf_rstore := vandelay.extract_rec_attrs(record_xml);
568 CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
569 CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
571 -- generate the where clause and return that directly (into wq), and as
572 -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
573 wq := vandelay.get_expr_from_match_set(match_set_id, tags_rstore);
575 query_ := 'SELECT DISTINCT(record), ';
577 -- qrows table is for the quality bits we add to the SELECT clause
579 'COALESCE(n' || q::TEXT || '.quality, 0)', ' + '
580 ) INTO coal FROM _vandelay_tmp_qrows;
582 -- our query string so far is the SELECT clause and the inital FROM.
583 -- no JOINs yet nor the WHERE clause
584 query_ := query_ || coal || ' AS quality ' || E'\n';
586 -- jrows table is for the joins we must make (and the real text conditions)
587 SELECT STRING_AGG(j, E'\n') INTO joins
588 FROM _vandelay_tmp_jrows;
590 -- add those joins and the where clause to our query.
591 query_ := query_ || joins || E'\n';
593 -- join the record bucket
594 IF bucket_id IS NOT NULL THEN
595 query_ := query_ || 'JOIN container.biblio_record_entry_bucket_item ' ||
596 'brebi ON (brebi.target_biblio_record_entry = record ' ||
597 'AND brebi.bucket = ' || bucket_id || E')\n';
600 query_ := query_ || 'JOIN biblio.record_entry bre ON (bre.id = record) ' || 'WHERE ' || wq || ' AND not bre.deleted';
602 -- this will return rows of record,quality
603 FOR rec IN EXECUTE query_ USING tags_rstore, svf_rstore LOOP
607 DROP TABLE _vandelay_tmp_qrows;
608 DROP TABLE _vandelay_tmp_jrows;
614 CREATE OR REPLACE FUNCTION vandelay.flatten_marc_hstore(
616 ) RETURNS HSTORE AS $func$
620 ARRAY_AGG(tag || (COALESCE(subfield, ''))),
624 SELECT tag, subfield, ARRAY_AGG(value)::TEXT AS value
627 CASE WHEN tag = '020' THEN -- caseless -- isbn
628 LOWER((REGEXP_MATCHES(value,$$^(\S{10,17})$$))[1] || '%')
629 WHEN tag = '022' THEN -- caseless -- issn
630 LOWER((REGEXP_MATCHES(value,$$^(\S{4}[- ]?\S{4})$$))[1] || '%')
631 WHEN tag = '024' THEN -- caseless -- upc (other)
636 FROM vandelay.flatten_marc(record_xml)) x
637 GROUP BY tag, subfield ORDER BY tag, subfield
641 $func$ LANGUAGE PLPGSQL;
643 -- backwards compat version so we don't have
644 -- to modify vandelay.match_set_test_marcxml()
645 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
646 match_set_id INTEGER,
650 RETURN vandelay.get_expr_from_match_set(
651 match_set_id, tags_rstore, NULL);
655 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
656 match_set_id INTEGER,
661 root vandelay.match_set_point;
663 SELECT * INTO root FROM vandelay.match_set_point
664 WHERE parent IS NULL AND match_set = match_set_id;
666 RETURN vandelay.get_expr_from_match_set_point(
667 root, tags_rstore, auth_heading);
671 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set_point(
672 node vandelay.match_set_point,
681 child vandelay.match_set_point;
683 SELECT ARRAY_AGG(id) INTO children FROM vandelay.match_set_point
684 WHERE parent = node.id;
686 IF ARRAY_LENGTH(children, 1) > 0 THEN
687 this_op := vandelay._get_expr_render_one(node);
690 WHILE children[i] IS NOT NULL LOOP
691 SELECT * INTO child FROM vandelay.match_set_point
692 WHERE id = children[i];
694 q := q || ' ' || this_op || ' ';
697 q := q || vandelay.get_expr_from_match_set_point(
698 child, tags_rstore, auth_heading);
702 ELSIF node.bool_op IS NULL THEN
703 PERFORM vandelay._get_expr_push_qrow(node);
704 PERFORM vandelay._get_expr_push_jrow(node, tags_rstore, auth_heading);
705 RETURN vandelay._get_expr_render_one(node);
712 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_qrow(
713 node vandelay.match_set_point
717 INSERT INTO _vandelay_tmp_qrows (q) VALUES (node.id);
721 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_jrow(
722 node vandelay.match_set_point,
737 -- remember $1 is tags_rstore, and $2 is svf_rstore
738 -- a non-NULL auth_heading means we're matching authority records
740 IF auth_heading IS NOT NULL THEN
741 rec_table := 'authority.full_rec';
743 rec_table := 'metabib.full_rec';
747 SELECT COUNT(*) INTO jrow_count FROM _vandelay_tmp_jrows;
748 IF jrow_count > 0 THEN
749 my_using := ' USING (record)';
750 my_join := 'FULL OUTER JOIN';
756 IF node.tag IS NOT NULL THEN
757 caseless := (node.tag IN ('020', '022', '024'));
759 IF node.subfield IS NOT NULL THEN
760 tagkey := tagkey || node.subfield;
778 my_alias := 'n' || node.id::TEXT;
780 jrow := my_join || ' (SELECT *, ';
781 IF node.tag IS NOT NULL THEN
782 jrow := jrow || node.quality ||
783 ' AS quality FROM ' || rec_table || ' mfr WHERE mfr.tag = ''' ||
785 IF node.subfield IS NOT NULL THEN
786 jrow := jrow || ' AND mfr.subfield = ''' ||
787 node.subfield || '''';
789 jrow := jrow || ' AND (';
790 jrow := jrow || vandelay._node_tag_comparisons(caseless, op, tags_rstore, tagkey);
791 jrow := jrow || ')) ' || my_alias || my_using || E'\n';
793 IF auth_heading IS NOT NULL THEN -- authority record
794 IF node.heading AND auth_heading <> '' THEN
795 jrow := jrow || 'id AS record, ' || node.quality ||
796 ' AS quality FROM authority.record_entry are ' ||
797 ' WHERE are.heading = ''' || auth_heading || '''';
798 jrow := jrow || ') ' || my_alias || my_using || E'\n';
801 jrow := jrow || 'id AS record, ' || node.quality ||
802 ' AS quality FROM metabib.record_attr_flat mraf WHERE mraf.attr = ''' ||
803 node.svf || ''' AND mraf.value ' || op || ' $2->''' || node.svf || ''') ' ||
804 my_alias || my_using || E'\n';
807 INSERT INTO _vandelay_tmp_jrows (j) VALUES (jrow);
811 CREATE OR REPLACE FUNCTION vandelay._node_tag_comparisons(
823 vals := tags_rstore->tagkey;
828 IF vals[i] IS NULL THEN
831 result := result || ' OR ';
836 result := result || 'LOWER(mfr.value) ' || op;
838 result := result || 'mfr.value ' || op;
841 result := result || ' ' || COALESCE('''' || vals[i] || '''', 'NULL');
843 IF vals[i] IS NULL THEN
854 CREATE OR REPLACE FUNCTION vandelay._get_expr_render_one(
855 node vandelay.match_set_point
860 IF node.bool_op IS NOT NULL THEN
863 RETURN '(n' || node.id::TEXT || '.id IS NOT NULL)';
868 CREATE OR REPLACE FUNCTION vandelay.match_bib_record() RETURNS TRIGGER AS $func$
870 incoming_existing_id TEXT;
871 test_result vandelay.match_set_test_result%ROWTYPE;
876 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
880 DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
882 SELECT q.match_set INTO match_set FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
884 IF match_set IS NOT NULL THEN
885 NEW.quality := vandelay.measure_record_quality( NEW.marc, match_set );
888 -- Perfect matches on 901$c exit early with a match with high quality.
889 incoming_existing_id :=
890 oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
892 IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
893 SELECT id INTO tmp_rec FROM biblio.record_entry WHERE id = incoming_existing_id::bigint;
894 IF tmp_rec IS NOT NULL THEN
895 INSERT INTO vandelay.bib_match (queued_record, eg_record, match_score, quality)
900 -- note: no match_set means quality==0
901 vandelay.measure_record_quality( b.marc, match_set )
902 FROM biblio.record_entry b
903 WHERE id = incoming_existing_id::bigint;
907 IF match_set IS NULL THEN
911 SELECT q.match_bucket INTO match_bucket FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
913 FOR test_result IN SELECT * FROM
914 vandelay.match_set_test_marcxml(match_set, NEW.marc, match_bucket) LOOP
916 INSERT INTO vandelay.bib_match ( queued_record, eg_record, match_score, quality )
921 vandelay.measure_record_quality( b.marc, match_set )
922 FROM biblio.record_entry b
923 WHERE id = test_result.record;
929 $func$ LANGUAGE PLPGSQL;
931 CREATE OR REPLACE FUNCTION vandelay.measure_record_quality ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
935 test vandelay.match_set_quality%ROWTYPE;
938 FOR test IN SELECT * FROM vandelay.match_set_quality WHERE match_set = match_set_id LOOP
939 IF test.tag IS NOT NULL THEN
940 FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml ) WHERE tag = test.tag AND subfield = test.subfield LOOP
941 IF test.value = rvalue THEN
942 out_q := out_q + test.quality;
946 IF test.value = vandelay.extract_rec_attrs(xml, ARRAY[test.svf]) -> test.svf THEN
947 out_q := out_q + test.quality;
954 $_$ LANGUAGE PLPGSQL;
956 CREATE TYPE vandelay.tcn_data AS (tcn TEXT, tcn_source TEXT, used BOOL);
957 CREATE OR REPLACE FUNCTION vandelay.find_bib_tcn_data ( xml TEXT ) RETURNS SETOF vandelay.tcn_data AS $_$
961 output vandelay.tcn_data%ROWTYPE;
965 eg_tcn := BTRIM((oils_xpath('//*[@tag="001"]/text()',xml))[1]);
966 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
968 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="003"]/text()',xml))[1]);
969 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
970 eg_tcn_source := 'System Local';
973 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
976 output.used := FALSE;
981 output.tcn := eg_tcn;
982 output.tcn_source := eg_tcn_source;
988 eg_tcn := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="a"]/text()',xml))[1]);
989 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
991 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="b"]/text()',xml))[1]);
992 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
993 eg_tcn_source := 'System Local';
996 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
999 output.used := FALSE;
1001 output.used := TRUE;
1004 output.tcn := eg_tcn;
1005 output.tcn_source := eg_tcn_source;
1011 eg_tcn := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="a"]/text()',xml))[1]);
1012 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1014 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="b"]/text()',xml))[1]);
1015 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
1016 eg_tcn_source := 'System Local';
1019 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1022 output.used := FALSE;
1024 output.used := TRUE;
1027 output.tcn := eg_tcn;
1028 output.tcn_source := eg_tcn_source;
1034 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="020"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1035 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1037 eg_tcn_source := 'ISBN';
1039 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1042 output.used := FALSE;
1044 output.used := TRUE;
1047 output.tcn := eg_tcn;
1048 output.tcn_source := eg_tcn_source;
1054 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="022"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1055 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1057 eg_tcn_source := 'ISSN';
1059 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1062 output.used := FALSE;
1064 output.used := TRUE;
1067 output.tcn := eg_tcn;
1068 output.tcn_source := eg_tcn_source;
1074 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="010"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1075 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1077 eg_tcn_source := 'LCCN';
1079 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1082 output.used := FALSE;
1084 output.used := TRUE;
1087 output.tcn := eg_tcn;
1088 output.tcn_source := eg_tcn_source;
1094 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="035"]/*[@code="a"]/text()',xml))[1], $re$^.*?(\w+)$$re$, $re$\1$re$);
1095 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1097 eg_tcn_source := 'System Legacy';
1099 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1102 output.used := FALSE;
1104 output.used := TRUE;
1107 output.tcn := eg_tcn;
1108 output.tcn_source := eg_tcn_source;
1115 $_$ LANGUAGE PLPGSQL;
1117 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT, force_add INT ) RETURNS TEXT AS $_$
1120 use MARC::File::XML (BinaryEncoding => 'UTF-8');
1124 MARC::Charset->assume_unicode(1);
1126 my $target_xml = shift;
1127 my $source_xml = shift;
1128 my $field_spec = shift;
1129 my $force_add = shift || 0;
1131 my $target_r = MARC::Record->new_from_xml( $target_xml );
1132 my $source_r = MARC::Record->new_from_xml( $source_xml );
1134 return $target_xml unless ($target_r && $source_r);
1136 my @field_list = split(',', $field_spec);
1139 for my $f (@field_list) {
1140 $f =~ s/^\s*//; $f =~ s/\s*$//;
1141 if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1147 $match =~ s/^\s*//; $match =~ s/\s*$//;
1148 $fields{$field} = { sf => [ split('', $sf) ] };
1150 my ($msf,$mre) = split('~', $match);
1151 if (length($msf) > 0 and length($mre) > 0) {
1152 $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1153 $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1154 $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1160 for my $f ( keys %fields) {
1161 if ( @{$fields{$f}{sf}} ) {
1162 for my $from_field ($source_r->field( $f )) {
1163 my @tos = $target_r->field( $f );
1165 next if (exists($fields{$f}{match}) and !$force_add);
1166 my @new_fields = map { $_->clone } $source_r->field( $f );
1167 $target_r->insert_fields_ordered( @new_fields );
1169 for my $to_field (@tos) {
1170 if (exists($fields{$f}{match})) {
1171 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1173 for my $old_sf ($from_field->subfields) {
1174 $to_field->add_subfields( @$old_sf ) if grep(/$$old_sf[0]/,@{$fields{$f}{sf}});
1180 my @new_fields = map { $_->clone } $source_r->field( $f );
1181 $target_r->insert_fields_ordered( @new_fields );
1185 $target_xml = $target_r->as_xml_record;
1186 $target_xml =~ s/^<\?.+?\?>$//mo;
1187 $target_xml =~ s/\n//sgo;
1188 $target_xml =~ s/>\s+</></sgo;
1192 $_$ LANGUAGE PLPERLU;
1194 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1195 SELECT vandelay.add_field( $1, $2, $3, 0 );
1198 CREATE OR REPLACE FUNCTION vandelay.strip_field ( xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1201 use MARC::File::XML (BinaryEncoding => 'UTF-8');
1205 MARC::Charset->assume_unicode(1);
1208 my $r = MARC::Record->new_from_xml( $xml );
1210 return $xml unless ($r);
1212 my $field_spec = shift;
1213 my @field_list = split(',', $field_spec);
1216 for my $f (@field_list) {
1217 $f =~ s/^\s*//; $f =~ s/\s*$//;
1218 if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1224 $match =~ s/^\s*//; $match =~ s/\s*$//;
1225 $fields{$field} = { sf => [ split('', $sf) ] };
1227 my ($msf,$mre) = split('~', $match);
1228 if (length($msf) > 0 and length($mre) > 0) {
1229 $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1230 $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1231 $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1237 for my $f ( keys %fields) {
1238 for my $to_field ($r->field( $f )) {
1239 if (exists($fields{$f}{match})) {
1240 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1243 if ( @{$fields{$f}{sf}} ) {
1244 $to_field->delete_subfield(code => $fields{$f}{sf});
1246 $r->delete_field( $to_field );
1251 $xml = $r->as_xml_record;
1252 $xml =~ s/^<\?.+?\?>$//mo;
1254 $xml =~ s/>\s+</></sgo;
1258 $_$ LANGUAGE PLPERLU;
1260 CREATE OR REPLACE FUNCTION vandelay.replace_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1267 parsed_target := vandelay.strip_field( target_xml, ''); -- this dance normalizes the format of the xml for the IF below
1268 xml_output := parsed_target; -- if there are no replace rules, just return the input
1270 FOR curr_field IN SELECT UNNEST( STRING_TO_ARRAY(field, ',') ) LOOP -- naive split, but it's the same we use in the perl
1272 xml_output := vandelay.strip_field( parsed_target, curr_field);
1274 IF xml_output <> parsed_target AND curr_field ~ E'~' THEN
1275 -- we removed something, and there was a regexp restriction in the curr_field definition, so proceed
1276 xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 1 );
1277 ELSIF curr_field !~ E'~' THEN
1278 -- No regexp restriction, add the curr_field
1279 xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 0 );
1282 parsed_target := xml_output; -- in prep for any following loop iterations
1288 $_$ LANGUAGE PLPGSQL;
1290 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 $_$
1291 SELECT vandelay.replace_field( vandelay.add_field( vandelay.strip_field( $1, $5) , $2, $3 ), $2, $4);
1294 CREATE TYPE vandelay.compile_profile AS (add_rule TEXT, replace_rule TEXT, preserve_rule TEXT, strip_rule TEXT);
1295 CREATE OR REPLACE FUNCTION vandelay.compile_profile ( incoming_xml TEXT ) RETURNS vandelay.compile_profile AS $_$
1297 output vandelay.compile_profile%ROWTYPE;
1298 profile vandelay.merge_profile%ROWTYPE;
1300 profile_tmpl_owner TEXT;
1301 add_rule TEXT := '';
1302 strip_rule TEXT := '';
1303 replace_rule TEXT := '';
1304 preserve_rule TEXT := '';
1308 profile_tmpl := (oils_xpath('//*[@tag="905"]/*[@code="t"]/text()',incoming_xml))[1];
1309 profile_tmpl_owner := (oils_xpath('//*[@tag="905"]/*[@code="o"]/text()',incoming_xml))[1];
1311 IF profile_tmpl IS NOT NULL AND profile_tmpl <> '' AND profile_tmpl_owner IS NOT NULL AND profile_tmpl_owner <> '' THEN
1312 SELECT p.* INTO profile
1313 FROM vandelay.merge_profile p
1314 JOIN actor.org_unit u ON (u.id = p.owner)
1315 WHERE p.name = profile_tmpl
1316 AND u.shortname = profile_tmpl_owner;
1318 IF profile.id IS NOT NULL THEN
1319 add_rule := COALESCE(profile.add_spec,'');
1320 strip_rule := COALESCE(profile.strip_spec,'');
1321 replace_rule := COALESCE(profile.replace_spec,'');
1322 preserve_rule := COALESCE(profile.preserve_spec,'');
1326 add_rule := add_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="a"]/text()',incoming_xml),','),'');
1327 strip_rule := strip_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="d"]/text()',incoming_xml),','),'');
1328 replace_rule := replace_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="r"]/text()',incoming_xml),','),'');
1329 preserve_rule := preserve_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="p"]/text()',incoming_xml),','),'');
1331 output.add_rule := BTRIM(add_rule,',');
1332 output.replace_rule := BTRIM(replace_rule,',');
1333 output.strip_rule := BTRIM(strip_rule,',');
1334 output.preserve_rule := BTRIM(preserve_rule,',');
1338 $_$ LANGUAGE PLPGSQL;
1340 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1342 merge_profile vandelay.merge_profile%ROWTYPE;
1343 dyn_profile vandelay.compile_profile%ROWTYPE;
1353 SELECT b.marc INTO eg_marc
1354 FROM biblio.record_entry b
1358 IF eg_marc IS NULL OR v_marc IS NULL THEN
1359 -- RAISE NOTICE 'no marc for template or bib record';
1363 dyn_profile := vandelay.compile_profile( v_marc );
1365 IF merge_profile_id IS NOT NULL THEN
1366 SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1368 dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1369 dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1370 dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1371 dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1375 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1376 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1380 IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1381 --Since we have nothing to do, just return a NOOP "we did it"
1383 ELSIF dyn_profile.replace_rule <> '' THEN
1384 source_marc = v_marc;
1385 target_marc = eg_marc;
1386 replace_rule = dyn_profile.replace_rule;
1388 source_marc = eg_marc;
1389 target_marc = v_marc;
1390 replace_rule = dyn_profile.preserve_rule;
1393 UPDATE biblio.record_entry
1394 SET marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1398 -- RAISE NOTICE 'update of biblio.record_entry failed';
1405 $$ LANGUAGE PLPGSQL;
1407 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_marc TEXT, template_marc TEXT ) RETURNS TEXT AS $$
1409 dyn_profile vandelay.compile_profile%ROWTYPE;
1417 IF target_marc IS NULL OR template_marc IS NULL THEN
1418 -- RAISE NOTICE 'no marc for target or template record';
1422 dyn_profile := vandelay.compile_profile( template_marc );
1424 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1425 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1429 IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1430 --Since we have nothing to do, just return what we were given.
1432 ELSIF dyn_profile.replace_rule <> '' THEN
1433 trgt_marc = target_marc;
1434 tmpl_marc = template_marc;
1435 replace_rule = dyn_profile.replace_rule;
1437 tmp_marc = target_marc;
1438 trgt_marc = template_marc;
1439 tmpl_marc = tmp_marc;
1440 replace_rule = dyn_profile.preserve_rule;
1443 RETURN vandelay.merge_record_xml( trgt_marc, tmpl_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
1446 $$ LANGUAGE PLPGSQL;
1448 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT) RETURNS BOOL AS $$
1449 SELECT vandelay.template_overlay_bib_record( $1, $2, NULL);
1452 CREATE OR REPLACE FUNCTION vandelay.overlay_bib_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1458 update_fields TEXT[];
1462 SELECT q.marc, q.bib_source INTO v_marc, v_bib_source
1463 FROM vandelay.queued_bib_record q
1464 JOIN vandelay.bib_match m ON (m.queued_record = q.id AND q.id = import_id)
1467 IF v_marc IS NULL THEN
1468 -- RAISE NOTICE 'no marc for vandelay or bib record';
1472 IF vandelay.template_overlay_bib_record( v_marc, eg_id, merge_profile_id) THEN
1473 UPDATE vandelay.queued_bib_record
1474 SET imported_as = eg_id,
1476 WHERE id = import_id;
1478 editor_string := (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
1480 IF editor_string IS NOT NULL AND editor_string <> '' THEN
1481 SELECT usr INTO editor_id FROM actor.card WHERE barcode = editor_string;
1483 IF editor_id IS NULL THEN
1484 SELECT id INTO editor_id FROM actor.usr WHERE usrname = editor_string;
1487 IF editor_id IS NOT NULL THEN
1488 --only update the edit date if we have a valid editor
1489 update_fields := ARRAY_APPEND(update_fields, 'editor = ' || editor_id || ', edit_date = NOW()');
1493 IF v_bib_source IS NOT NULL THEN
1494 update_fields := ARRAY_APPEND(update_fields, 'source = ' || v_bib_source);
1497 IF ARRAY_LENGTH(update_fields, 1) > 0 THEN
1498 update_query := 'UPDATE biblio.record_entry SET ' || ARRAY_TO_STRING(update_fields, ',') || ' WHERE id = ' || eg_id || ';';
1499 --RAISE NOTICE 'query: %', update_query;
1500 EXECUTE update_query;
1506 -- RAISE NOTICE 'update of biblio.record_entry failed';
1511 $$ LANGUAGE PLPGSQL;
1513 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 $$
1516 lwm_ratio_value NUMERIC;
1519 lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
1521 PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1524 -- RAISE NOTICE 'already imported, cannot auto-overlay'
1528 SELECT m.eg_record INTO eg_id
1529 FROM vandelay.bib_match m
1530 JOIN vandelay.queued_bib_record qr ON (m.queued_record = qr.id)
1531 JOIN vandelay.bib_queue q ON (qr.queue = q.id)
1532 JOIN biblio.record_entry r ON (r.id = m.eg_record)
1533 WHERE m.queued_record = import_id
1534 AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
1535 ORDER BY m.match_score DESC, -- required match score
1536 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
1537 m.id -- when in doubt, use the first match
1540 IF eg_id IS NULL THEN
1541 -- RAISE NOTICE 'incoming record is not of high enough quality';
1545 RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1547 $$ LANGUAGE PLPGSQL;
1549 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1550 SELECT vandelay.auto_overlay_bib_record_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1553 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1559 PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1562 -- RAISE NOTICE 'already imported, cannot auto-overlay'
1566 SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
1568 IF match_count <> 1 THEN
1569 -- RAISE NOTICE 'not an exact match';
1573 -- Check that the one match is on the first 901c
1574 SELECT m.eg_record INTO eg_id
1575 FROM vandelay.queued_bib_record q
1576 JOIN vandelay.bib_match m ON (m.queued_record = q.id)
1577 WHERE q.id = import_id
1578 AND m.eg_record = oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]',marc)::BIGINT;
1581 -- RAISE NOTICE 'not a 901c match';
1585 RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1587 $$ LANGUAGE PLPGSQL;
1589 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1591 queued_record vandelay.queued_bib_record%ROWTYPE;
1594 FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1596 IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
1597 RETURN NEXT queued_record.id;
1605 $$ LANGUAGE PLPGSQL;
1607 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 $$
1609 queued_record vandelay.queued_bib_record%ROWTYPE;
1612 FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1614 IF vandelay.auto_overlay_bib_record_with_best( queued_record.id, merge_profile_id, lwm_ratio_value ) THEN
1615 RETURN NEXT queued_record.id;
1623 $$ LANGUAGE PLPGSQL;
1625 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1626 SELECT vandelay.auto_overlay_bib_queue_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1629 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1630 SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
1633 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_marc ( ) RETURNS TRIGGER AS $$
1639 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1643 FOR adef IN SELECT * FROM vandelay.bib_attr_definition LOOP
1645 SELECT extract_marc_field('vandelay.queued_bib_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_bib_record WHERE id = NEW.id;
1646 IF (value IS NOT NULL AND value <> '') THEN
1647 INSERT INTO vandelay.queued_bib_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1654 $$ LANGUAGE PLPGSQL;
1656 CREATE OR REPLACE FUNCTION vandelay.cleanup_bib_marc ( ) RETURNS TRIGGER AS $$
1658 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1662 DELETE FROM vandelay.queued_bib_record_attr WHERE record = OLD.id;
1663 DELETE FROM vandelay.import_item WHERE record = OLD.id;
1665 IF TG_OP = 'UPDATE' THEN
1670 $$ LANGUAGE PLPGSQL;
1672 CREATE TRIGGER cleanup_bib_trigger
1673 BEFORE UPDATE OR DELETE ON vandelay.queued_bib_record
1674 FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_bib_marc();
1676 CREATE TRIGGER ingest_bib_trigger
1677 AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1678 FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_marc();
1680 CREATE TRIGGER zz_match_bibs_trigger
1681 BEFORE INSERT OR UPDATE ON vandelay.queued_bib_record
1682 FOR EACH ROW EXECUTE PROCEDURE vandelay.match_bib_record();
1685 /* Authority stuff down here */
1686 ---------------------------------------
1687 CREATE TABLE vandelay.authority_attr_definition (
1688 id SERIAL PRIMARY KEY,
1689 code TEXT UNIQUE NOT NULL,
1691 xpath TEXT NOT NULL,
1692 remove TEXT NOT NULL DEFAULT ''
1695 CREATE TYPE vandelay.authority_queue_queue_type AS ENUM ('authority');
1696 CREATE TABLE vandelay.authority_queue (
1697 queue_type vandelay.authority_queue_queue_type NOT NULL DEFAULT 'authority',
1698 CONSTRAINT vand_authority_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
1699 ) INHERITS (vandelay.queue);
1700 ALTER TABLE vandelay.authority_queue ADD PRIMARY KEY (id);
1702 CREATE TABLE vandelay.queued_authority_record (
1703 queue INT NOT NULL REFERENCES vandelay.authority_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1704 imported_as INT REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1705 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
1707 ) INHERITS (vandelay.queued_record);
1708 ALTER TABLE vandelay.queued_authority_record ADD PRIMARY KEY (id);
1709 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
1711 CREATE TABLE vandelay.queued_authority_record_attr (
1712 id BIGSERIAL PRIMARY KEY,
1713 record BIGINT NOT NULL REFERENCES vandelay.queued_authority_record (id) DEFERRABLE INITIALLY DEFERRED,
1714 field INT NOT NULL REFERENCES vandelay.authority_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
1715 attr_value TEXT NOT NULL
1717 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
1719 CREATE TABLE vandelay.authority_match (
1720 id BIGSERIAL PRIMARY KEY,
1721 queued_record BIGINT REFERENCES vandelay.queued_authority_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1722 eg_record BIGINT REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1723 quality INT NOT NULL DEFAULT 0,
1724 match_score INT NOT NULL DEFAULT 0
1727 CREATE OR REPLACE FUNCTION vandelay.ingest_authority_marc ( ) RETURNS TRIGGER AS $$
1733 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1737 FOR adef IN SELECT * FROM vandelay.authority_attr_definition LOOP
1739 SELECT extract_marc_field('vandelay.queued_authority_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_authority_record WHERE id = NEW.id;
1740 IF (value IS NOT NULL AND value <> '') THEN
1741 INSERT INTO vandelay.queued_authority_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1748 $$ LANGUAGE PLPGSQL;
1750 CREATE OR REPLACE FUNCTION vandelay.cleanup_authority_marc ( ) RETURNS TRIGGER AS $$
1752 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1756 DELETE FROM vandelay.queued_authority_record_attr WHERE record = OLD.id;
1757 IF TG_OP = 'UPDATE' THEN
1762 $$ LANGUAGE PLPGSQL;
1764 CREATE TRIGGER cleanup_authority_trigger
1765 BEFORE UPDATE OR DELETE ON vandelay.queued_authority_record
1766 FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_authority_marc();
1768 CREATE TRIGGER ingest_authority_trigger
1769 AFTER INSERT OR UPDATE ON vandelay.queued_authority_record
1770 FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_authority_marc();
1772 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1774 merge_profile vandelay.merge_profile%ROWTYPE;
1775 dyn_profile vandelay.compile_profile%ROWTYPE;
1784 SELECT b.marc INTO eg_marc
1785 FROM authority.record_entry b
1786 JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
1789 SELECT q.marc INTO v_marc
1790 FROM vandelay.queued_record q
1791 JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
1794 IF eg_marc IS NULL OR v_marc IS NULL THEN
1795 -- RAISE NOTICE 'no marc for vandelay or authority record';
1799 dyn_profile := vandelay.compile_profile( v_marc );
1801 IF merge_profile_id IS NOT NULL THEN
1802 SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1804 dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1805 dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1806 dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1807 dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1811 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1812 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1816 IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1817 --Since we have nothing to do, just return a NOOP "we did it"
1819 ELSIF dyn_profile.replace_rule <> '' THEN
1820 source_marc = v_marc;
1821 target_marc = eg_marc;
1822 replace_rule = dyn_profile.replace_rule;
1824 source_marc = eg_marc;
1825 target_marc = v_marc;
1826 replace_rule = dyn_profile.preserve_rule;
1829 UPDATE authority.record_entry
1830 SET marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1834 UPDATE vandelay.queued_authority_record
1835 SET imported_as = eg_id,
1837 WHERE id = import_id;
1841 -- RAISE NOTICE 'update of authority.record_entry failed';
1846 $$ LANGUAGE PLPGSQL;
1848 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1853 SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
1855 IF match_count <> 1 THEN
1856 -- RAISE NOTICE 'not an exact match';
1860 SELECT m.eg_record INTO eg_id
1861 FROM vandelay.authority_match m
1862 WHERE m.queued_record = import_id
1865 IF eg_id IS NULL THEN
1869 RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
1871 $$ LANGUAGE PLPGSQL;
1873 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1875 queued_record vandelay.queued_authority_record%ROWTYPE;
1878 FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
1880 IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
1881 RETURN NEXT queued_record.id;
1889 $$ LANGUAGE PLPGSQL;
1891 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1892 SELECT * FROM vandelay.auto_overlay_authority_queue( $1, NULL );
1895 CREATE OR REPLACE FUNCTION vandelay.match_set_test_authxml(
1896 match_set_id INTEGER, record_xml TEXT
1897 ) RETURNS SETOF vandelay.match_set_test_result AS $$
1908 tags_rstore := vandelay.flatten_marc_hstore(record_xml);
1910 SELECT normalize_heading INTO heading
1911 FROM authority.normalize_heading(record_xml);
1913 CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
1914 CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
1916 -- generate the where clause and return that directly (into wq), and as
1917 -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
1918 wq := vandelay.get_expr_from_match_set(
1919 match_set_id, tags_rstore, heading);
1921 query_ := 'SELECT DISTINCT(record), ';
1923 -- qrows table is for the quality bits we add to the SELECT clause
1925 'COALESCE(n' || q::TEXT || '.quality, 0)', ' + '
1926 ) INTO coal FROM _vandelay_tmp_qrows;
1928 -- our query string so far is the SELECT clause and the inital FROM.
1929 -- no JOINs yet nor the WHERE clause
1930 query_ := query_ || coal || ' AS quality ' || E'\n';
1932 -- jrows table is for the joins we must make (and the real text conditions)
1933 SELECT STRING_AGG(j, E'\n') INTO joins
1934 FROM _vandelay_tmp_jrows;
1936 -- add those joins and the where clause to our query.
1937 query_ := query_ || joins || E'\n';
1939 query_ := query_ || 'JOIN authority.record_entry are ON (are.id = record) '
1940 || 'WHERE ' || wq || ' AND not are.deleted';
1942 -- this will return rows of record,quality
1943 FOR rec IN EXECUTE query_ USING tags_rstore LOOP
1947 DROP TABLE _vandelay_tmp_qrows;
1948 DROP TABLE _vandelay_tmp_jrows;
1951 $$ LANGUAGE PLPGSQL;
1953 CREATE OR REPLACE FUNCTION vandelay.measure_auth_record_quality
1954 ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
1958 test vandelay.match_set_quality%ROWTYPE;
1961 FOR test IN SELECT * FROM vandelay.match_set_quality
1962 WHERE match_set = match_set_id LOOP
1963 IF test.tag IS NOT NULL THEN
1964 FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml )
1965 WHERE tag = test.tag AND subfield = test.subfield LOOP
1966 IF test.value = rvalue THEN
1967 out_q := out_q + test.quality;
1975 $_$ LANGUAGE PLPGSQL;
1979 CREATE OR REPLACE FUNCTION vandelay.match_authority_record() RETURNS TRIGGER AS $func$
1981 incoming_existing_id TEXT;
1982 test_result vandelay.match_set_test_result%ROWTYPE;
1986 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1990 DELETE FROM vandelay.authority_match WHERE queued_record = NEW.id;
1992 SELECT q.match_set INTO match_set FROM vandelay.authority_queue q WHERE q.id = NEW.queue;
1994 IF match_set IS NOT NULL THEN
1995 NEW.quality := vandelay.measure_auth_record_quality( NEW.marc, match_set );
1998 -- Perfect matches on 901$c exit early with a match with high quality.
1999 incoming_existing_id :=
2000 oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
2002 IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
2003 SELECT id INTO tmp_rec FROM authority.record_entry WHERE id = incoming_existing_id::bigint;
2004 IF tmp_rec IS NOT NULL THEN
2005 INSERT INTO vandelay.authority_match (queued_record, eg_record, match_score, quality)
2010 -- note: no match_set means quality==0
2011 vandelay.measure_auth_record_quality( b.marc, match_set )
2012 FROM authority.record_entry b
2013 WHERE id = incoming_existing_id::bigint;
2017 IF match_set IS NULL THEN
2021 FOR test_result IN SELECT * FROM
2022 vandelay.match_set_test_authxml(match_set, NEW.marc) LOOP
2024 INSERT INTO vandelay.authority_match ( queued_record, eg_record, match_score, quality )
2028 test_result.quality,
2029 vandelay.measure_auth_record_quality( b.marc, match_set )
2030 FROM authority.record_entry b
2031 WHERE id = test_result.record;
2037 $func$ LANGUAGE PLPGSQL;
2039 CREATE TRIGGER zz_match_auths_trigger
2040 BEFORE INSERT OR UPDATE ON vandelay.queued_authority_record
2041 FOR EACH ROW EXECUTE PROCEDURE vandelay.match_authority_record();
2043 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record_with_best ( import_id BIGINT, merge_profile_id INT, lwm_ratio_value_p NUMERIC ) RETURNS BOOL AS $$
2046 lwm_ratio_value NUMERIC;
2049 lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
2051 PERFORM * FROM vandelay.queued_authority_record WHERE import_time IS NOT NULL AND id = import_id;
2054 -- RAISE NOTICE 'already imported, cannot auto-overlay'
2058 SELECT m.eg_record INTO eg_id
2059 FROM vandelay.authority_match m
2060 JOIN vandelay.queued_authority_record qr ON (m.queued_record = qr.id)
2061 JOIN vandelay.authority_queue q ON (qr.queue = q.id)
2062 JOIN authority.record_entry r ON (r.id = m.eg_record)
2063 WHERE m.queued_record = import_id
2064 AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
2065 ORDER BY m.match_score DESC, -- required match score
2066 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
2067 m.id -- when in doubt, use the first match
2070 IF eg_id IS NULL THEN
2071 -- RAISE NOTICE 'incoming record is not of high enough quality';
2075 RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
2077 $$ LANGUAGE PLPGSQL;
2082 -- Vandelay (for importing and exporting records) 012.schema.vandelay.sql
2083 --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)]');
2084 --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)]');
2085 --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]');
2086 --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]');
2087 --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$);
2088 --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$);
2089 --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]');
2090 --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);
2091 --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);
2092 --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);
2093 --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);
2094 --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]');
2095 --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$);
2096 --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]');
2098 --INSERT INTO vandelay.import_item_attr_definition (
2099 -- owner, name, tag, owning_lib, circ_lib, location,
2100 -- call_number, circ_modifier, barcode, price, copy_number,
2101 -- circulate, ref, holdable, opac_visible, status
2104 -- 'Evergreen 852 export format',
2106 -- '[@code = "b"][1]',
2107 -- '[@code = "b"][2]',
2114 -- '[@code = "x" and text() = "circulating"]',
2115 -- '[@code = "x" and text() = "reference"]',
2116 -- '[@code = "x" and text() = "holdable"]',
2117 -- '[@code = "x" and text() = "visible"]',
2121 --INSERT INTO vandelay.import_item_attr_definition (
2134 -- 'Unicorn Import format -- 999',
2145 --INSERT INTO vandelay.authority_attr_definition ( code, description, xpath, ident ) VALUES ('rec_identifier','Identifier','//*[@tag="001"]', TRUE);