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
153 CREATE INDEX bib_match_queued_record ON vandelay.bib_match (queued_record);
155 CREATE TABLE vandelay.import_item (
156 id BIGSERIAL PRIMARY KEY,
157 record BIGINT NOT NULL REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
158 definition BIGINT NOT NULL REFERENCES vandelay.import_item_attr_definition (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
159 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
162 import_time TIMESTAMP WITH TIME ZONE,
171 deposit_amount NUMERIC(8,2),
182 internal_id BIGINT -- queue_type == 'acq' ? acq.lineitem_detail.id : asset.copy.id
184 CREATE INDEX import_item_record ON vandelay.import_item (record);
186 CREATE TABLE vandelay.import_bib_trash_group(
187 id SERIAL PRIMARY KEY,
188 owner INTEGER NOT NULL REFERENCES actor.org_unit(id),
189 label TEXT NOT NULL, --i18n
190 always_apply BOOLEAN NOT NULL DEFAULT FALSE,
191 CONSTRAINT vand_import_bib_trash_grp_owner_label UNIQUE (owner, label)
194 CREATE TABLE vandelay.import_bib_trash_fields (
195 id BIGSERIAL PRIMARY KEY,
196 grp INTEGER NOT NULL REFERENCES vandelay.import_bib_trash_group,
198 CONSTRAINT vand_import_bib_trash_fields_once_per UNIQUE (grp, field)
201 CREATE TABLE vandelay.merge_profile (
202 id BIGSERIAL PRIMARY KEY,
203 owner INT NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
210 CONSTRAINT vand_merge_prof_owner_name_idx UNIQUE (owner,name),
211 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))
214 CREATE OR REPLACE FUNCTION vandelay.marc21_record_type( marc TEXT ) RETURNS config.marc21_rec_type_map AS $func$
221 retval config.marc21_rec_type_map%ROWTYPE;
223 ldr := oils_xpath_string( '//*[local-name()="leader"]', marc );
225 IF ldr IS NULL OR ldr = '' THEN
226 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
230 SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
231 SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
234 tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
235 bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
237 -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
239 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
242 IF retval.code IS NULL THEN
243 SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
248 $func$ LANGUAGE PLPGSQL;
250 CREATE TYPE biblio.record_ff_map AS (record BIGINT, ff_name TEXT, ff_value TEXT);
251 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_all_fixed_fields( marc TEXT, use_default BOOL DEFAULT FALSE ) RETURNS SETOF biblio.record_ff_map AS $func$
256 output biblio.record_ff_map%ROWTYPE;
258 rtype := (vandelay.marc21_record_type( marc )).code;
260 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE rec_type = rtype ORDER BY tag DESC LOOP
261 output.ff_name := ff_pos.fixed_field;
262 output.ff_value := NULL;
264 IF ff_pos.tag = 'ldr' THEN
265 output.ff_value := oils_xpath_string('//*[local-name()="leader"]', marc);
266 IF output.ff_value IS NOT NULL THEN
267 output.ff_value := SUBSTRING( output.ff_value, ff_pos.start_pos + 1, ff_pos.length );
269 output.ff_value := NULL;
272 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
273 output.ff_value := SUBSTRING( tag_data, ff_pos.start_pos + 1, ff_pos.length );
274 CONTINUE WHEN output.ff_value IS NULL AND NOT use_default;
275 IF output.ff_value IS NULL THEN output.ff_value := REPEAT( ff_pos.default_val, ff_pos.length ); END IF;
277 output.ff_value := NULL;
285 $func$ LANGUAGE PLPGSQL;
287 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field_list( marc TEXT, ff TEXT, use_default BOOL DEFAULT FALSE ) RETURNS TEXT[] AS $func$
293 collection TEXT[] := '{}'::TEXT[];
295 rtype := (vandelay.marc21_record_type( marc )).code;
296 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
297 IF ff_pos.tag = 'ldr' THEN
298 val := oils_xpath_string('//*[local-name()="leader"]', marc);
299 IF val IS NOT NULL THEN
300 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
301 collection := collection || val;
304 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
305 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
306 collection := collection || val;
309 CONTINUE WHEN NOT use_default;
310 CONTINUE WHEN ARRAY_UPPER(collection, 1) > 0;
311 val := REPEAT( ff_pos.default_val, ff_pos.length );
312 collection := collection || val;
317 $func$ LANGUAGE PLPGSQL;
319 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field( marc TEXT, ff TEXT, use_default BOOL DEFAULT FALSE ) RETURNS TEXT AS $func$
326 rtype := (vandelay.marc21_record_type( marc )).code;
327 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
328 IF ff_pos.tag = 'ldr' THEN
329 val := oils_xpath_string('//*[local-name()="leader"]', marc);
330 IF val IS NOT NULL THEN
331 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
335 FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
336 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
340 CONTINUE WHEN NOT use_default;
341 val := REPEAT( ff_pos.default_val, ff_pos.length );
347 $func$ LANGUAGE PLPGSQL;
349 CREATE TYPE biblio.marc21_physical_characteristics AS ( id INT, record BIGINT, ptype TEXT, subfield INT, value INT );
350 CREATE OR REPLACE FUNCTION vandelay.marc21_physical_characteristics( marc TEXT) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
354 ptype config.marc21_physical_characteristic_type_map%ROWTYPE;
355 psf config.marc21_physical_characteristic_subfield_map%ROWTYPE;
356 pval config.marc21_physical_characteristic_value_map%ROWTYPE;
357 retval biblio.marc21_physical_characteristics%ROWTYPE;
360 FOR _007 IN SELECT oils_xpath_string('//*', value) FROM UNNEST(oils_xpath('//*[@tag="007"]', marc)) x(value) LOOP
361 IF _007 IS NOT NULL AND _007 <> '' THEN
362 SELECT * INTO ptype FROM config.marc21_physical_characteristic_type_map WHERE ptype_key = SUBSTRING( _007, 1, 1 );
364 IF ptype.ptype_key IS NOT NULL THEN
365 FOR psf IN SELECT * FROM config.marc21_physical_characteristic_subfield_map WHERE ptype_key = ptype.ptype_key LOOP
366 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 );
368 IF pval.id IS NOT NULL THEN
371 retval.ptype := ptype.ptype_key;
372 retval.subfield := psf.id;
373 retval.value := pval.id;
384 $func$ LANGUAGE PLPGSQL;
386 CREATE TYPE vandelay.flat_marc AS ( tag CHAR(3), ind1 TEXT, ind2 TEXT, subfield TEXT, value TEXT );
387 CREATE OR REPLACE FUNCTION vandelay.flay_marc ( TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
390 use MARC::File::XML (BinaryEncoding => 'UTF-8');
394 MARC::Charset->assume_unicode(1);
397 my $r = MARC::Record->new_from_xml( $xml );
399 return_next( { tag => 'LDR', value => $r->leader } );
401 for my $f ( $r->fields ) {
402 if ($f->is_control_field) {
403 return_next({ tag => $f->tag, value => $f->data });
405 for my $s ($f->subfields) {
408 ind1 => $f->indicator(1),
409 ind2 => $f->indicator(2),
414 if ( $f->tag eq '245' and $s->[0] eq 'a' ) {
415 my $trim = $f->indicator(2) || 0;
418 ind1 => $f->indicator(1),
419 ind2 => $f->indicator(2),
421 value => substr( $s->[1], $trim )
430 $func$ LANGUAGE PLPERLU;
432 CREATE OR REPLACE FUNCTION vandelay.flatten_marc ( marc TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
434 output vandelay.flat_marc%ROWTYPE;
437 FOR field IN SELECT * FROM vandelay.flay_marc( marc ) LOOP
438 output.ind1 := field.ind1;
439 output.ind2 := field.ind2;
440 output.tag := field.tag;
441 output.subfield := field.subfield;
442 IF field.subfield IS NOT NULL AND field.tag NOT IN ('020','022','024') THEN -- exclude standard numbers and control fields
443 output.value := naco_normalize(field.value, field.subfield);
445 output.value := field.value;
448 CONTINUE WHEN output.value IS NULL;
453 $func$ LANGUAGE PLPGSQL;
455 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT, attr_defs TEXT[]) RETURNS hstore AS $_$
457 transformed_xml TEXT;
460 xfrm config.xml_transform%ROWTYPE;
462 new_attrs HSTORE := ''::HSTORE;
463 attr_def config.record_attr_definition%ROWTYPE;
466 FOR attr_def IN SELECT * FROM config.record_attr_definition WHERE name IN (SELECT * FROM UNNEST(attr_defs)) ORDER BY format LOOP
468 IF attr_def.tag IS NOT NULL THEN -- tag (and optional subfield list) selection
469 SELECT STRING_AGG(x.value, COALESCE(attr_def.joiner,' ')) INTO attr_value
470 FROM vandelay.flatten_marc(xml) AS x
471 WHERE x.tag LIKE attr_def.tag
473 WHEN attr_def.sf_list IS NOT NULL
474 THEN POSITION(x.subfield IN attr_def.sf_list) > 0
481 ELSIF attr_def.fixed_field IS NOT NULL THEN -- a named fixed field, see config.marc21_ff_pos_map.fixed_field
482 attr_value := vandelay.marc21_extract_fixed_field(xml, attr_def.fixed_field);
484 ELSIF attr_def.xpath IS NOT NULL THEN -- and xpath expression
486 SELECT INTO xfrm * FROM config.xml_transform WHERE name = attr_def.format;
488 -- See if we can skip the XSLT ... it's expensive
489 IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
490 -- Can't skip the transform
491 IF xfrm.xslt <> '---' THEN
492 transformed_xml := oils_xslt_process(xml,xfrm.xslt);
494 transformed_xml := xml;
497 prev_xfrm := xfrm.name;
500 IF xfrm.name IS NULL THEN
501 -- just grab the marcxml (empty) transform
502 SELECT INTO xfrm * FROM config.xml_transform WHERE xslt = '---' LIMIT 1;
503 prev_xfrm := xfrm.name;
506 attr_value := oils_xpath_string(attr_def.xpath, transformed_xml, COALESCE(attr_def.joiner,' '), ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]);
508 ELSIF attr_def.phys_char_sf IS NOT NULL THEN -- a named Physical Characteristic, see config.marc21_physical_characteristic_*_map
509 SELECT m.value::TEXT INTO attr_value
510 FROM vandelay.marc21_physical_characteristics(xml) v
511 JOIN config.marc21_physical_characteristic_value_map m ON (m.id = v.value)
512 WHERE v.subfield = attr_def.phys_char_sf
513 LIMIT 1; -- Just in case ...
517 -- apply index normalizers to attr_value
519 SELECT n.func AS func,
520 n.param_count AS param_count,
522 FROM config.index_normalizer n
523 JOIN config.record_attr_index_norm_map m ON (m.norm = n.id)
524 WHERE attr = attr_def.name
526 EXECUTE 'SELECT ' || normalizer.func || '(' ||
527 quote_nullable( attr_value ) ||
529 WHEN normalizer.param_count > 0
530 THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
537 -- Add the new value to the hstore
538 new_attrs := new_attrs || hstore( attr_def.name, attr_value );
544 $_$ LANGUAGE PLPGSQL;
546 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT ) RETURNS hstore AS $_$
547 SELECT vandelay.extract_rec_attrs( $1, (SELECT ARRAY_AGG(name) FROM config.record_attr_definition));
550 -- Everything between this comment and the beginning of the definition of
551 -- vandelay.match_bib_record() is strictly in service of that function.
552 CREATE TYPE vandelay.match_set_test_result AS (record BIGINT, quality INTEGER);
554 CREATE OR REPLACE FUNCTION vandelay.match_set_test_marcxml(
555 match_set_id INTEGER, record_xml TEXT, bucket_id INTEGER
556 ) RETURNS SETOF vandelay.match_set_test_result AS $$
567 tags_rstore := vandelay.flatten_marc_hstore(record_xml);
568 svf_rstore := vandelay.extract_rec_attrs(record_xml);
570 CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
571 CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
573 -- generate the where clause and return that directly (into wq), and as
574 -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
575 wq := vandelay.get_expr_from_match_set(match_set_id, tags_rstore);
577 query_ := 'SELECT DISTINCT(record), ';
579 -- qrows table is for the quality bits we add to the SELECT clause
581 'COALESCE(n' || q::TEXT || '.quality, 0)', ' + '
582 ) INTO coal FROM _vandelay_tmp_qrows;
584 -- our query string so far is the SELECT clause and the inital FROM.
585 -- no JOINs yet nor the WHERE clause
586 query_ := query_ || coal || ' AS quality ' || E'\n';
588 -- jrows table is for the joins we must make (and the real text conditions)
589 SELECT STRING_AGG(j, E'\n') INTO joins
590 FROM _vandelay_tmp_jrows;
592 -- add those joins and the where clause to our query.
593 query_ := query_ || joins || E'\n';
595 -- join the record bucket
596 IF bucket_id IS NOT NULL THEN
597 query_ := query_ || 'JOIN container.biblio_record_entry_bucket_item ' ||
598 'brebi ON (brebi.target_biblio_record_entry = record ' ||
599 'AND brebi.bucket = ' || bucket_id || E')\n';
602 query_ := query_ || 'JOIN biblio.record_entry bre ON (bre.id = record) ' || 'WHERE ' || wq || ' AND not bre.deleted';
604 -- this will return rows of record,quality
605 FOR rec IN EXECUTE query_ USING tags_rstore, svf_rstore LOOP
609 DROP TABLE _vandelay_tmp_qrows;
610 DROP TABLE _vandelay_tmp_jrows;
616 CREATE OR REPLACE FUNCTION vandelay.flatten_marc_hstore(
618 ) RETURNS HSTORE AS $func$
622 ARRAY_AGG(tag || (COALESCE(subfield, ''))),
626 SELECT tag, subfield, ARRAY_AGG(value)::TEXT AS value
629 CASE WHEN tag = '020' THEN -- caseless -- isbn
630 LOWER((REGEXP_MATCHES(value,$$^(\S{10,17})$$))[1] || '%')
631 WHEN tag = '022' THEN -- caseless -- issn
632 LOWER((REGEXP_MATCHES(value,$$^(\S{4}[- ]?\S{4})$$))[1] || '%')
633 WHEN tag = '024' THEN -- caseless -- upc (other)
638 FROM vandelay.flatten_marc(record_xml)) x
639 GROUP BY tag, subfield ORDER BY tag, subfield
643 $func$ LANGUAGE PLPGSQL;
645 -- backwards compat version so we don't have
646 -- to modify vandelay.match_set_test_marcxml()
647 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
648 match_set_id INTEGER,
652 RETURN vandelay.get_expr_from_match_set(
653 match_set_id, tags_rstore, NULL);
657 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
658 match_set_id INTEGER,
663 root vandelay.match_set_point;
665 SELECT * INTO root FROM vandelay.match_set_point
666 WHERE parent IS NULL AND match_set = match_set_id;
668 RETURN vandelay.get_expr_from_match_set_point(
669 root, tags_rstore, auth_heading);
673 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set_point(
674 node vandelay.match_set_point,
683 child vandelay.match_set_point;
685 SELECT ARRAY_AGG(id) INTO children FROM vandelay.match_set_point
686 WHERE parent = node.id;
688 IF ARRAY_LENGTH(children, 1) > 0 THEN
689 this_op := vandelay._get_expr_render_one(node);
692 WHILE children[i] IS NOT NULL LOOP
693 SELECT * INTO child FROM vandelay.match_set_point
694 WHERE id = children[i];
696 q := q || ' ' || this_op || ' ';
699 q := q || vandelay.get_expr_from_match_set_point(
700 child, tags_rstore, auth_heading);
704 ELSIF node.bool_op IS NULL THEN
705 PERFORM vandelay._get_expr_push_qrow(node);
706 PERFORM vandelay._get_expr_push_jrow(node, tags_rstore, auth_heading);
707 RETURN vandelay._get_expr_render_one(node);
714 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_qrow(
715 node vandelay.match_set_point
719 INSERT INTO _vandelay_tmp_qrows (q) VALUES (node.id);
723 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_jrow(
724 node vandelay.match_set_point,
739 -- remember $1 is tags_rstore, and $2 is svf_rstore
740 -- a non-NULL auth_heading means we're matching authority records
742 IF auth_heading IS NOT NULL THEN
743 rec_table := 'authority.full_rec';
745 rec_table := 'metabib.full_rec';
749 SELECT COUNT(*) INTO jrow_count FROM _vandelay_tmp_jrows;
750 IF jrow_count > 0 THEN
751 my_using := ' USING (record)';
752 my_join := 'FULL OUTER JOIN';
758 IF node.tag IS NOT NULL THEN
759 caseless := (node.tag IN ('020', '022', '024'));
761 IF node.subfield IS NOT NULL THEN
762 tagkey := tagkey || node.subfield;
780 my_alias := 'n' || node.id::TEXT;
782 jrow := my_join || ' (SELECT *, ';
783 IF node.tag IS NOT NULL THEN
784 jrow := jrow || node.quality ||
785 ' AS quality FROM ' || rec_table || ' mfr WHERE mfr.tag = ''' ||
787 IF node.subfield IS NOT NULL THEN
788 jrow := jrow || ' AND mfr.subfield = ''' ||
789 node.subfield || '''';
791 jrow := jrow || ' AND (';
792 jrow := jrow || vandelay._node_tag_comparisons(caseless, op, tags_rstore, tagkey);
793 jrow := jrow || ')) ' || my_alias || my_using || E'\n';
795 IF auth_heading IS NOT NULL THEN -- authority record
796 IF node.heading AND auth_heading <> '' THEN
797 jrow := jrow || 'id AS record, ' || node.quality ||
798 ' AS quality FROM authority.record_entry are ' ||
799 ' WHERE are.heading = ''' || auth_heading || '''';
800 jrow := jrow || ') ' || my_alias || my_using || E'\n';
803 jrow := jrow || 'id AS record, ' || node.quality ||
804 ' AS quality FROM metabib.record_attr_flat mraf WHERE mraf.attr = ''' ||
805 node.svf || ''' AND mraf.value ' || op || ' $2->''' || node.svf || ''') ' ||
806 my_alias || my_using || E'\n';
809 INSERT INTO _vandelay_tmp_jrows (j) VALUES (jrow);
813 CREATE OR REPLACE FUNCTION vandelay._node_tag_comparisons(
825 vals := tags_rstore->tagkey;
830 IF vals[i] IS NULL THEN
833 result := result || ' OR ';
838 result := result || 'LOWER(mfr.value) ' || op;
840 result := result || 'mfr.value ' || op;
843 result := result || ' ' || COALESCE('''' || vals[i] || '''', 'NULL');
845 IF vals[i] IS NULL THEN
856 CREATE OR REPLACE FUNCTION vandelay._get_expr_render_one(
857 node vandelay.match_set_point
862 IF node.bool_op IS NOT NULL THEN
865 RETURN '(n' || node.id::TEXT || '.id IS NOT NULL)';
870 CREATE OR REPLACE FUNCTION vandelay.match_bib_record() RETURNS TRIGGER AS $func$
872 incoming_existing_id TEXT;
873 test_result vandelay.match_set_test_result%ROWTYPE;
878 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
882 DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
884 SELECT q.match_set INTO match_set FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
886 IF match_set IS NOT NULL THEN
887 NEW.quality := vandelay.measure_record_quality( NEW.marc, match_set );
890 -- Perfect matches on 901$c exit early with a match with high quality.
891 incoming_existing_id :=
892 oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
894 IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
895 SELECT id INTO tmp_rec FROM biblio.record_entry WHERE id = incoming_existing_id::bigint;
896 IF tmp_rec IS NOT NULL THEN
897 INSERT INTO vandelay.bib_match (queued_record, eg_record, match_score, quality)
902 -- note: no match_set means quality==0
903 vandelay.measure_record_quality( b.marc, match_set )
904 FROM biblio.record_entry b
905 WHERE id = incoming_existing_id::bigint;
909 IF match_set IS NULL THEN
913 SELECT q.match_bucket INTO match_bucket FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
915 FOR test_result IN SELECT * FROM
916 vandelay.match_set_test_marcxml(match_set, NEW.marc, match_bucket) LOOP
918 INSERT INTO vandelay.bib_match ( queued_record, eg_record, match_score, quality )
923 vandelay.measure_record_quality( b.marc, match_set )
924 FROM biblio.record_entry b
925 WHERE id = test_result.record;
931 $func$ LANGUAGE PLPGSQL;
933 CREATE OR REPLACE FUNCTION vandelay.measure_record_quality ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
937 test vandelay.match_set_quality%ROWTYPE;
940 FOR test IN SELECT * FROM vandelay.match_set_quality WHERE match_set = match_set_id LOOP
941 IF test.tag IS NOT NULL THEN
942 FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml ) WHERE tag = test.tag AND subfield = test.subfield LOOP
943 IF test.value = rvalue THEN
944 out_q := out_q + test.quality;
948 IF test.value = vandelay.extract_rec_attrs(xml, ARRAY[test.svf]) -> test.svf THEN
949 out_q := out_q + test.quality;
956 $_$ LANGUAGE PLPGSQL;
958 CREATE TYPE vandelay.tcn_data AS (tcn TEXT, tcn_source TEXT, used BOOL);
959 CREATE OR REPLACE FUNCTION vandelay.find_bib_tcn_data ( xml TEXT ) RETURNS SETOF vandelay.tcn_data AS $_$
963 output vandelay.tcn_data%ROWTYPE;
967 eg_tcn := BTRIM((oils_xpath('//*[@tag="001"]/text()',xml))[1]);
968 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
970 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="003"]/text()',xml))[1]);
971 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
972 eg_tcn_source := 'System Local';
975 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
978 output.used := FALSE;
983 output.tcn := eg_tcn;
984 output.tcn_source := eg_tcn_source;
990 eg_tcn := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="a"]/text()',xml))[1]);
991 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
993 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="b"]/text()',xml))[1]);
994 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
995 eg_tcn_source := 'System Local';
998 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1001 output.used := FALSE;
1003 output.used := TRUE;
1006 output.tcn := eg_tcn;
1007 output.tcn_source := eg_tcn_source;
1013 eg_tcn := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="a"]/text()',xml))[1]);
1014 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1016 eg_tcn_source := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="b"]/text()',xml))[1]);
1017 IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
1018 eg_tcn_source := 'System Local';
1021 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1024 output.used := FALSE;
1026 output.used := TRUE;
1029 output.tcn := eg_tcn;
1030 output.tcn_source := eg_tcn_source;
1036 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="020"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1037 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1039 eg_tcn_source := 'ISBN';
1041 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1044 output.used := FALSE;
1046 output.used := TRUE;
1049 output.tcn := eg_tcn;
1050 output.tcn_source := eg_tcn_source;
1056 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="022"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1057 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1059 eg_tcn_source := 'ISSN';
1061 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1064 output.used := FALSE;
1066 output.used := TRUE;
1069 output.tcn := eg_tcn;
1070 output.tcn_source := eg_tcn_source;
1076 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="010"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1077 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1079 eg_tcn_source := 'LCCN';
1081 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1084 output.used := FALSE;
1086 output.used := TRUE;
1089 output.tcn := eg_tcn;
1090 output.tcn_source := eg_tcn_source;
1096 eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="035"]/*[@code="a"]/text()',xml))[1], $re$^.*?(\w+)$$re$, $re$\1$re$);
1097 IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1099 eg_tcn_source := 'System Legacy';
1101 PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn AND NOT deleted;
1104 output.used := FALSE;
1106 output.used := TRUE;
1109 output.tcn := eg_tcn;
1110 output.tcn_source := eg_tcn_source;
1117 $_$ LANGUAGE PLPGSQL;
1119 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT, force_add INT ) RETURNS TEXT AS $_$
1122 use MARC::File::XML (BinaryEncoding => 'UTF-8');
1126 MARC::Charset->assume_unicode(1);
1128 my $target_xml = shift;
1129 my $source_xml = shift;
1130 my $field_spec = shift;
1131 my $force_add = shift || 0;
1133 my $target_r = MARC::Record->new_from_xml( $target_xml );
1134 my $source_r = MARC::Record->new_from_xml( $source_xml );
1136 return $target_xml unless ($target_r && $source_r);
1138 my @field_list = split(',', $field_spec);
1141 for my $f (@field_list) {
1142 $f =~ s/^\s*//; $f =~ s/\s*$//;
1143 if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1149 $match =~ s/^\s*//; $match =~ s/\s*$//;
1150 $fields{$field} = { sf => [ split('', $sf) ] };
1152 my ($msf,$mre) = split('~', $match);
1153 if (length($msf) > 0 and length($mre) > 0) {
1154 $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1155 $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1156 $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1162 for my $f ( keys %fields) {
1163 if ( @{$fields{$f}{sf}} ) {
1164 for my $from_field ($source_r->field( $f )) {
1165 my @tos = $target_r->field( $f );
1167 next if (exists($fields{$f}{match}) and !$force_add);
1168 my @new_fields = map { $_->clone } $source_r->field( $f );
1169 $target_r->insert_fields_ordered( @new_fields );
1171 for my $to_field (@tos) {
1172 if (exists($fields{$f}{match})) {
1173 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1175 for my $old_sf ($from_field->subfields) {
1176 $to_field->add_subfields( @$old_sf ) if grep(/$$old_sf[0]/,@{$fields{$f}{sf}});
1182 my @new_fields = map { $_->clone } $source_r->field( $f );
1183 $target_r->insert_fields_ordered( @new_fields );
1187 $target_xml = $target_r->as_xml_record;
1188 $target_xml =~ s/^<\?.+?\?>$//mo;
1189 $target_xml =~ s/\n//sgo;
1190 $target_xml =~ s/>\s+</></sgo;
1194 $_$ LANGUAGE PLPERLU;
1196 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1197 SELECT vandelay.add_field( $1, $2, $3, 0 );
1200 CREATE OR REPLACE FUNCTION vandelay.strip_field ( xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1203 use MARC::File::XML (BinaryEncoding => 'UTF-8');
1207 MARC::Charset->assume_unicode(1);
1210 my $r = MARC::Record->new_from_xml( $xml );
1212 return $xml unless ($r);
1214 my $field_spec = shift;
1215 my @field_list = split(',', $field_spec);
1218 for my $f (@field_list) {
1219 $f =~ s/^\s*//; $f =~ s/\s*$//;
1220 if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1226 $match =~ s/^\s*//; $match =~ s/\s*$//;
1227 $fields{$field} = { sf => [ split('', $sf) ] };
1229 my ($msf,$mre) = split('~', $match);
1230 if (length($msf) > 0 and length($mre) > 0) {
1231 $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1232 $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1233 $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1239 for my $f ( keys %fields) {
1240 for my $to_field ($r->field( $f )) {
1241 if (exists($fields{$f}{match})) {
1242 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1245 if ( @{$fields{$f}{sf}} ) {
1246 $to_field->delete_subfield(code => $fields{$f}{sf});
1248 $r->delete_field( $to_field );
1253 $xml = $r->as_xml_record;
1254 $xml =~ s/^<\?.+?\?>$//mo;
1256 $xml =~ s/>\s+</></sgo;
1260 $_$ LANGUAGE PLPERLU;
1262 CREATE OR REPLACE FUNCTION vandelay.replace_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1269 parsed_target := vandelay.strip_field( target_xml, ''); -- this dance normalizes the format of the xml for the IF below
1270 xml_output := parsed_target; -- if there are no replace rules, just return the input
1272 FOR curr_field IN SELECT UNNEST( STRING_TO_ARRAY(field, ',') ) LOOP -- naive split, but it's the same we use in the perl
1274 xml_output := vandelay.strip_field( parsed_target, curr_field);
1276 IF xml_output <> parsed_target AND curr_field ~ E'~' THEN
1277 -- we removed something, and there was a regexp restriction in the curr_field definition, so proceed
1278 xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 1 );
1279 ELSIF curr_field !~ E'~' THEN
1280 -- No regexp restriction, add the curr_field
1281 xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 0 );
1284 parsed_target := xml_output; -- in prep for any following loop iterations
1290 $_$ LANGUAGE PLPGSQL;
1292 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 $_$
1293 SELECT vandelay.replace_field( vandelay.add_field( vandelay.strip_field( $1, $5) , $2, $3 ), $2, $4);
1296 CREATE TYPE vandelay.compile_profile AS (add_rule TEXT, replace_rule TEXT, preserve_rule TEXT, strip_rule TEXT);
1297 CREATE OR REPLACE FUNCTION vandelay.compile_profile ( incoming_xml TEXT ) RETURNS vandelay.compile_profile AS $_$
1299 output vandelay.compile_profile%ROWTYPE;
1300 profile vandelay.merge_profile%ROWTYPE;
1302 profile_tmpl_owner TEXT;
1303 add_rule TEXT := '';
1304 strip_rule TEXT := '';
1305 replace_rule TEXT := '';
1306 preserve_rule TEXT := '';
1310 profile_tmpl := (oils_xpath('//*[@tag="905"]/*[@code="t"]/text()',incoming_xml))[1];
1311 profile_tmpl_owner := (oils_xpath('//*[@tag="905"]/*[@code="o"]/text()',incoming_xml))[1];
1313 IF profile_tmpl IS NOT NULL AND profile_tmpl <> '' AND profile_tmpl_owner IS NOT NULL AND profile_tmpl_owner <> '' THEN
1314 SELECT p.* INTO profile
1315 FROM vandelay.merge_profile p
1316 JOIN actor.org_unit u ON (u.id = p.owner)
1317 WHERE p.name = profile_tmpl
1318 AND u.shortname = profile_tmpl_owner;
1320 IF profile.id IS NOT NULL THEN
1321 add_rule := COALESCE(profile.add_spec,'');
1322 strip_rule := COALESCE(profile.strip_spec,'');
1323 replace_rule := COALESCE(profile.replace_spec,'');
1324 preserve_rule := COALESCE(profile.preserve_spec,'');
1328 add_rule := add_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="a"]/text()',incoming_xml),','),'');
1329 strip_rule := strip_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="d"]/text()',incoming_xml),','),'');
1330 replace_rule := replace_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="r"]/text()',incoming_xml),','),'');
1331 preserve_rule := preserve_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="p"]/text()',incoming_xml),','),'');
1333 output.add_rule := BTRIM(add_rule,',');
1334 output.replace_rule := BTRIM(replace_rule,',');
1335 output.strip_rule := BTRIM(strip_rule,',');
1336 output.preserve_rule := BTRIM(preserve_rule,',');
1340 $_$ LANGUAGE PLPGSQL;
1342 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1344 merge_profile vandelay.merge_profile%ROWTYPE;
1345 dyn_profile vandelay.compile_profile%ROWTYPE;
1355 SELECT b.marc INTO eg_marc
1356 FROM biblio.record_entry b
1360 IF eg_marc IS NULL OR v_marc IS NULL THEN
1361 -- RAISE NOTICE 'no marc for template or bib record';
1365 dyn_profile := vandelay.compile_profile( v_marc );
1367 IF merge_profile_id IS NOT NULL THEN
1368 SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1370 dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1371 dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1372 dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1373 dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1377 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1378 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1382 IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1383 --Since we have nothing to do, just return a NOOP "we did it"
1385 ELSIF dyn_profile.replace_rule <> '' THEN
1386 source_marc = v_marc;
1387 target_marc = eg_marc;
1388 replace_rule = dyn_profile.replace_rule;
1390 source_marc = eg_marc;
1391 target_marc = v_marc;
1392 replace_rule = dyn_profile.preserve_rule;
1395 UPDATE biblio.record_entry
1396 SET marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1400 -- RAISE NOTICE 'update of biblio.record_entry failed';
1407 $$ LANGUAGE PLPGSQL;
1409 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_marc TEXT, template_marc TEXT ) RETURNS TEXT AS $$
1411 dyn_profile vandelay.compile_profile%ROWTYPE;
1419 IF target_marc IS NULL OR template_marc IS NULL THEN
1420 -- RAISE NOTICE 'no marc for target or template record';
1424 dyn_profile := vandelay.compile_profile( template_marc );
1426 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1427 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1431 IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1432 --Since we have nothing to do, just return what we were given.
1434 ELSIF dyn_profile.replace_rule <> '' THEN
1435 trgt_marc = target_marc;
1436 tmpl_marc = template_marc;
1437 replace_rule = dyn_profile.replace_rule;
1439 tmp_marc = target_marc;
1440 trgt_marc = template_marc;
1441 tmpl_marc = tmp_marc;
1442 replace_rule = dyn_profile.preserve_rule;
1445 RETURN vandelay.merge_record_xml( trgt_marc, tmpl_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
1448 $$ LANGUAGE PLPGSQL;
1450 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT) RETURNS BOOL AS $$
1451 SELECT vandelay.template_overlay_bib_record( $1, $2, NULL);
1454 CREATE OR REPLACE FUNCTION vandelay.overlay_bib_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1460 update_fields TEXT[];
1464 SELECT q.marc, q.bib_source INTO v_marc, v_bib_source
1465 FROM vandelay.queued_bib_record q
1466 JOIN vandelay.bib_match m ON (m.queued_record = q.id AND q.id = import_id)
1469 IF v_marc IS NULL THEN
1470 -- RAISE NOTICE 'no marc for vandelay or bib record';
1474 IF vandelay.template_overlay_bib_record( v_marc, eg_id, merge_profile_id) THEN
1475 UPDATE vandelay.queued_bib_record
1476 SET imported_as = eg_id,
1478 WHERE id = import_id;
1480 editor_string := (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
1482 IF editor_string IS NOT NULL AND editor_string <> '' THEN
1483 SELECT usr INTO editor_id FROM actor.card WHERE barcode = editor_string;
1485 IF editor_id IS NULL THEN
1486 SELECT id INTO editor_id FROM actor.usr WHERE usrname = editor_string;
1489 IF editor_id IS NOT NULL THEN
1490 --only update the edit date if we have a valid editor
1491 update_fields := ARRAY_APPEND(update_fields, 'editor = ' || editor_id || ', edit_date = NOW()');
1495 IF v_bib_source IS NOT NULL THEN
1496 update_fields := ARRAY_APPEND(update_fields, 'source = ' || v_bib_source);
1499 IF ARRAY_LENGTH(update_fields, 1) > 0 THEN
1500 update_query := 'UPDATE biblio.record_entry SET ' || ARRAY_TO_STRING(update_fields, ',') || ' WHERE id = ' || eg_id || ';';
1501 --RAISE NOTICE 'query: %', update_query;
1502 EXECUTE update_query;
1508 -- RAISE NOTICE 'update of biblio.record_entry failed';
1513 $$ LANGUAGE PLPGSQL;
1515 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 $$
1518 lwm_ratio_value NUMERIC;
1521 lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
1523 PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1526 -- RAISE NOTICE 'already imported, cannot auto-overlay'
1530 SELECT m.eg_record INTO eg_id
1531 FROM vandelay.bib_match m
1532 JOIN vandelay.queued_bib_record qr ON (m.queued_record = qr.id)
1533 JOIN vandelay.bib_queue q ON (qr.queue = q.id)
1534 JOIN biblio.record_entry r ON (r.id = m.eg_record)
1535 WHERE m.queued_record = import_id
1536 AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
1537 ORDER BY m.match_score DESC, -- required match score
1538 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
1539 m.id -- when in doubt, use the first match
1542 IF eg_id IS NULL THEN
1543 -- RAISE NOTICE 'incoming record is not of high enough quality';
1547 RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1549 $$ LANGUAGE PLPGSQL;
1551 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1552 SELECT vandelay.auto_overlay_bib_record_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1555 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1561 PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1564 -- RAISE NOTICE 'already imported, cannot auto-overlay'
1568 SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
1570 IF match_count <> 1 THEN
1571 -- RAISE NOTICE 'not an exact match';
1575 -- Check that the one match is on the first 901c
1576 SELECT m.eg_record INTO eg_id
1577 FROM vandelay.queued_bib_record q
1578 JOIN vandelay.bib_match m ON (m.queued_record = q.id)
1579 WHERE q.id = import_id
1580 AND m.eg_record = oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]',marc)::BIGINT;
1583 -- RAISE NOTICE 'not a 901c match';
1587 RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1589 $$ LANGUAGE PLPGSQL;
1591 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1593 queued_record vandelay.queued_bib_record%ROWTYPE;
1596 FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1598 IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
1599 RETURN NEXT queued_record.id;
1607 $$ LANGUAGE PLPGSQL;
1609 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 $$
1611 queued_record vandelay.queued_bib_record%ROWTYPE;
1614 FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1616 IF vandelay.auto_overlay_bib_record_with_best( queued_record.id, merge_profile_id, lwm_ratio_value ) THEN
1617 RETURN NEXT queued_record.id;
1625 $$ LANGUAGE PLPGSQL;
1627 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1628 SELECT vandelay.auto_overlay_bib_queue_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1631 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1632 SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
1635 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_marc ( ) RETURNS TRIGGER AS $$
1641 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1645 FOR adef IN SELECT * FROM vandelay.bib_attr_definition LOOP
1647 SELECT extract_marc_field('vandelay.queued_bib_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_bib_record WHERE id = NEW.id;
1648 IF (value IS NOT NULL AND value <> '') THEN
1649 INSERT INTO vandelay.queued_bib_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1656 $$ LANGUAGE PLPGSQL;
1658 CREATE OR REPLACE FUNCTION vandelay.cleanup_bib_marc ( ) RETURNS TRIGGER AS $$
1660 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1664 DELETE FROM vandelay.queued_bib_record_attr WHERE record = OLD.id;
1665 DELETE FROM vandelay.import_item WHERE record = OLD.id;
1667 IF TG_OP = 'UPDATE' THEN
1672 $$ LANGUAGE PLPGSQL;
1674 CREATE TRIGGER cleanup_bib_trigger
1675 BEFORE UPDATE OR DELETE ON vandelay.queued_bib_record
1676 FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_bib_marc();
1678 CREATE TRIGGER ingest_bib_trigger
1679 AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1680 FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_marc();
1682 CREATE TRIGGER zz_match_bibs_trigger
1683 BEFORE INSERT OR UPDATE ON vandelay.queued_bib_record
1684 FOR EACH ROW EXECUTE PROCEDURE vandelay.match_bib_record();
1687 /* Authority stuff down here */
1688 ---------------------------------------
1689 CREATE TABLE vandelay.authority_attr_definition (
1690 id SERIAL PRIMARY KEY,
1691 code TEXT UNIQUE NOT NULL,
1693 xpath TEXT NOT NULL,
1694 remove TEXT NOT NULL DEFAULT ''
1697 CREATE TYPE vandelay.authority_queue_queue_type AS ENUM ('authority');
1698 CREATE TABLE vandelay.authority_queue (
1699 queue_type vandelay.authority_queue_queue_type NOT NULL DEFAULT 'authority',
1700 CONSTRAINT vand_authority_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
1701 ) INHERITS (vandelay.queue);
1702 ALTER TABLE vandelay.authority_queue ADD PRIMARY KEY (id);
1704 CREATE TABLE vandelay.queued_authority_record (
1705 queue INT NOT NULL REFERENCES vandelay.authority_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1706 imported_as INT REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1707 import_error TEXT REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
1709 ) INHERITS (vandelay.queued_record);
1710 ALTER TABLE vandelay.queued_authority_record ADD PRIMARY KEY (id);
1711 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
1713 CREATE TABLE vandelay.queued_authority_record_attr (
1714 id BIGSERIAL PRIMARY KEY,
1715 record BIGINT NOT NULL REFERENCES vandelay.queued_authority_record (id) DEFERRABLE INITIALLY DEFERRED,
1716 field INT NOT NULL REFERENCES vandelay.authority_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
1717 attr_value TEXT NOT NULL
1719 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
1721 CREATE TABLE vandelay.authority_match (
1722 id BIGSERIAL PRIMARY KEY,
1723 queued_record BIGINT REFERENCES vandelay.queued_authority_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1724 eg_record BIGINT REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1725 quality INT NOT NULL DEFAULT 0,
1726 match_score INT NOT NULL DEFAULT 0
1729 CREATE OR REPLACE FUNCTION vandelay.ingest_authority_marc ( ) RETURNS TRIGGER AS $$
1735 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1739 FOR adef IN SELECT * FROM vandelay.authority_attr_definition LOOP
1741 SELECT extract_marc_field('vandelay.queued_authority_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_authority_record WHERE id = NEW.id;
1742 IF (value IS NOT NULL AND value <> '') THEN
1743 INSERT INTO vandelay.queued_authority_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1750 $$ LANGUAGE PLPGSQL;
1752 CREATE OR REPLACE FUNCTION vandelay.cleanup_authority_marc ( ) RETURNS TRIGGER AS $$
1754 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1758 DELETE FROM vandelay.queued_authority_record_attr WHERE record = OLD.id;
1759 IF TG_OP = 'UPDATE' THEN
1764 $$ LANGUAGE PLPGSQL;
1766 CREATE TRIGGER cleanup_authority_trigger
1767 BEFORE UPDATE OR DELETE ON vandelay.queued_authority_record
1768 FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_authority_marc();
1770 CREATE TRIGGER ingest_authority_trigger
1771 AFTER INSERT OR UPDATE ON vandelay.queued_authority_record
1772 FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_authority_marc();
1774 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1776 merge_profile vandelay.merge_profile%ROWTYPE;
1777 dyn_profile vandelay.compile_profile%ROWTYPE;
1786 SELECT b.marc INTO eg_marc
1787 FROM authority.record_entry b
1788 JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
1791 SELECT q.marc INTO v_marc
1792 FROM vandelay.queued_record q
1793 JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
1796 IF eg_marc IS NULL OR v_marc IS NULL THEN
1797 -- RAISE NOTICE 'no marc for vandelay or authority record';
1801 dyn_profile := vandelay.compile_profile( v_marc );
1803 IF merge_profile_id IS NOT NULL THEN
1804 SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1806 dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1807 dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1808 dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1809 dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1813 IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1814 -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1818 IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1819 --Since we have nothing to do, just return a NOOP "we did it"
1821 ELSIF dyn_profile.replace_rule <> '' THEN
1822 source_marc = v_marc;
1823 target_marc = eg_marc;
1824 replace_rule = dyn_profile.replace_rule;
1826 source_marc = eg_marc;
1827 target_marc = v_marc;
1828 replace_rule = dyn_profile.preserve_rule;
1831 UPDATE authority.record_entry
1832 SET marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1836 UPDATE vandelay.queued_authority_record
1837 SET imported_as = eg_id,
1839 WHERE id = import_id;
1843 -- RAISE NOTICE 'update of authority.record_entry failed';
1848 $$ LANGUAGE PLPGSQL;
1850 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1855 SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
1857 IF match_count <> 1 THEN
1858 -- RAISE NOTICE 'not an exact match';
1862 SELECT m.eg_record INTO eg_id
1863 FROM vandelay.authority_match m
1864 WHERE m.queued_record = import_id
1867 IF eg_id IS NULL THEN
1871 RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
1873 $$ LANGUAGE PLPGSQL;
1875 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1877 queued_record vandelay.queued_authority_record%ROWTYPE;
1880 FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
1882 IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
1883 RETURN NEXT queued_record.id;
1891 $$ LANGUAGE PLPGSQL;
1893 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1894 SELECT * FROM vandelay.auto_overlay_authority_queue( $1, NULL );
1897 CREATE OR REPLACE FUNCTION vandelay.match_set_test_authxml(
1898 match_set_id INTEGER, record_xml TEXT
1899 ) RETURNS SETOF vandelay.match_set_test_result AS $$
1910 tags_rstore := vandelay.flatten_marc_hstore(record_xml);
1912 SELECT normalize_heading INTO heading
1913 FROM authority.normalize_heading(record_xml);
1915 CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
1916 CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
1918 -- generate the where clause and return that directly (into wq), and as
1919 -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
1920 wq := vandelay.get_expr_from_match_set(
1921 match_set_id, tags_rstore, heading);
1923 query_ := 'SELECT DISTINCT(record), ';
1925 -- qrows table is for the quality bits we add to the SELECT clause
1927 'COALESCE(n' || q::TEXT || '.quality, 0)', ' + '
1928 ) INTO coal FROM _vandelay_tmp_qrows;
1930 -- our query string so far is the SELECT clause and the inital FROM.
1931 -- no JOINs yet nor the WHERE clause
1932 query_ := query_ || coal || ' AS quality ' || E'\n';
1934 -- jrows table is for the joins we must make (and the real text conditions)
1935 SELECT STRING_AGG(j, E'\n') INTO joins
1936 FROM _vandelay_tmp_jrows;
1938 -- add those joins and the where clause to our query.
1939 query_ := query_ || joins || E'\n';
1941 query_ := query_ || 'JOIN authority.record_entry are ON (are.id = record) '
1942 || 'WHERE ' || wq || ' AND not are.deleted';
1944 -- this will return rows of record,quality
1945 FOR rec IN EXECUTE query_ USING tags_rstore LOOP
1949 DROP TABLE _vandelay_tmp_qrows;
1950 DROP TABLE _vandelay_tmp_jrows;
1953 $$ LANGUAGE PLPGSQL;
1955 CREATE OR REPLACE FUNCTION vandelay.measure_auth_record_quality
1956 ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
1960 test vandelay.match_set_quality%ROWTYPE;
1963 FOR test IN SELECT * FROM vandelay.match_set_quality
1964 WHERE match_set = match_set_id LOOP
1965 IF test.tag IS NOT NULL THEN
1966 FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml )
1967 WHERE tag = test.tag AND subfield = test.subfield LOOP
1968 IF test.value = rvalue THEN
1969 out_q := out_q + test.quality;
1977 $_$ LANGUAGE PLPGSQL;
1981 CREATE OR REPLACE FUNCTION vandelay.match_authority_record() RETURNS TRIGGER AS $func$
1983 incoming_existing_id TEXT;
1984 test_result vandelay.match_set_test_result%ROWTYPE;
1988 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1992 DELETE FROM vandelay.authority_match WHERE queued_record = NEW.id;
1994 SELECT q.match_set INTO match_set FROM vandelay.authority_queue q WHERE q.id = NEW.queue;
1996 IF match_set IS NOT NULL THEN
1997 NEW.quality := vandelay.measure_auth_record_quality( NEW.marc, match_set );
2000 -- Perfect matches on 901$c exit early with a match with high quality.
2001 incoming_existing_id :=
2002 oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
2004 IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
2005 SELECT id INTO tmp_rec FROM authority.record_entry WHERE id = incoming_existing_id::bigint;
2006 IF tmp_rec IS NOT NULL THEN
2007 INSERT INTO vandelay.authority_match (queued_record, eg_record, match_score, quality)
2012 -- note: no match_set means quality==0
2013 vandelay.measure_auth_record_quality( b.marc, match_set )
2014 FROM authority.record_entry b
2015 WHERE id = incoming_existing_id::bigint;
2019 IF match_set IS NULL THEN
2023 FOR test_result IN SELECT * FROM
2024 vandelay.match_set_test_authxml(match_set, NEW.marc) LOOP
2026 INSERT INTO vandelay.authority_match ( queued_record, eg_record, match_score, quality )
2030 test_result.quality,
2031 vandelay.measure_auth_record_quality( b.marc, match_set )
2032 FROM authority.record_entry b
2033 WHERE id = test_result.record;
2039 $func$ LANGUAGE PLPGSQL;
2041 CREATE TRIGGER zz_match_auths_trigger
2042 BEFORE INSERT OR UPDATE ON vandelay.queued_authority_record
2043 FOR EACH ROW EXECUTE PROCEDURE vandelay.match_authority_record();
2045 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 $$
2048 lwm_ratio_value NUMERIC;
2051 lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
2053 PERFORM * FROM vandelay.queued_authority_record WHERE import_time IS NOT NULL AND id = import_id;
2056 -- RAISE NOTICE 'already imported, cannot auto-overlay'
2060 SELECT m.eg_record INTO eg_id
2061 FROM vandelay.authority_match m
2062 JOIN vandelay.queued_authority_record qr ON (m.queued_record = qr.id)
2063 JOIN vandelay.authority_queue q ON (qr.queue = q.id)
2064 JOIN authority.record_entry r ON (r.id = m.eg_record)
2065 WHERE m.queued_record = import_id
2066 AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
2067 ORDER BY m.match_score DESC, -- required match score
2068 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
2069 m.id -- when in doubt, use the first match
2072 IF eg_id IS NULL THEN
2073 -- RAISE NOTICE 'incoming record is not of high enough quality';
2077 RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
2079 $$ LANGUAGE PLPGSQL;
2084 -- Vandelay (for importing and exporting records) 012.schema.vandelay.sql
2085 --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)]');
2086 --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)]');
2087 --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]');
2088 --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]');
2089 --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$);
2090 --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$);
2091 --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]');
2092 --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);
2093 --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);
2094 --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);
2095 --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);
2096 --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]');
2097 --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$);
2098 --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]');
2100 --INSERT INTO vandelay.import_item_attr_definition (
2101 -- owner, name, tag, owning_lib, circ_lib, location,
2102 -- call_number, circ_modifier, barcode, price, copy_number,
2103 -- circulate, ref, holdable, opac_visible, status
2106 -- 'Evergreen 852 export format',
2108 -- '[@code = "b"][1]',
2109 -- '[@code = "b"][2]',
2116 -- '[@code = "x" and text() = "circulating"]',
2117 -- '[@code = "x" and text() = "reference"]',
2118 -- '[@code = "x" and text() = "holdable"]',
2119 -- '[@code = "x" and text() = "visible"]',
2123 --INSERT INTO vandelay.import_item_attr_definition (
2136 -- 'Unicorn Import format -- 999',
2147 --INSERT INTO vandelay.authority_attr_definition ( code, description, xpath, ident ) VALUES ('rec_identifier','Identifier','//*[@tag="001"]', TRUE);