]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/030.schema.metabib.sql
Link browse entries to authority record when possible
[working/Evergreen.git] / Open-ILS / src / sql / Pg / 030.schema.metabib.sql
1 /*
2  * Copyright (C) 2004-2008  Georgia Public Library Service
3  * Copyright (C) 2007-2008  Equinox Software, Inc.
4  * Mike Rylander <miker@esilibrary.com> 
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  */
17
18 DROP SCHEMA IF EXISTS metabib CASCADE;
19
20 BEGIN;
21 CREATE SCHEMA metabib;
22
23 CREATE TABLE metabib.metarecord (
24         id              BIGSERIAL       PRIMARY KEY,
25         fingerprint     TEXT            NOT NULL,
26         master_record   BIGINT,
27         mods            TEXT
28 );
29 CREATE INDEX metabib_metarecord_master_record_idx ON metabib.metarecord (master_record);
30 CREATE INDEX metabib_metarecord_fingerprint_idx ON metabib.metarecord (fingerprint);
31
32 CREATE TABLE metabib.identifier_field_entry (
33         id              BIGSERIAL       PRIMARY KEY,
34         source          BIGINT          NOT NULL,
35         field           INT             NOT NULL,
36         value           TEXT            NOT NULL,
37         index_vector    tsvector        NOT NULL
38 );
39 CREATE TRIGGER metabib_identifier_field_entry_fti_trigger
40         BEFORE UPDATE OR INSERT ON metabib.identifier_field_entry
41         FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('identifier');
42
43 CREATE INDEX metabib_identifier_field_entry_index_vector_idx ON metabib.identifier_field_entry USING GIST (index_vector);
44 CREATE INDEX metabib_identifier_field_entry_value_idx ON metabib.identifier_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
45 CREATE INDEX metabib_identifier_field_entry_source_idx ON metabib.identifier_field_entry (source);
46
47 CREATE TABLE metabib.combined_identifier_field_entry (
48         record          BIGINT          NOT NULL,
49         metabib_field           INT             NULL,
50         index_vector    tsvector        NOT NULL
51 );
52 CREATE UNIQUE INDEX metabib_combined_identifier_field_entry_fakepk_idx ON metabib.combined_identifier_field_entry (record, COALESCE(metabib_field::TEXT,''));
53 CREATE INDEX metabib_combined_identifier_field_entry_index_vector_idx ON metabib.combined_identifier_field_entry USING GIST (index_vector);
54 CREATE INDEX metabib_combined_identifier_field_source_idx ON metabib.combined_identifier_field_entry (metabib_field);
55
56 CREATE TABLE metabib.title_field_entry (
57         id              BIGSERIAL       PRIMARY KEY,
58         source          BIGINT          NOT NULL,
59         field           INT             NOT NULL,
60         value           TEXT            NOT NULL,
61         index_vector    tsvector        NOT NULL
62 );
63 CREATE TRIGGER metabib_title_field_entry_fti_trigger
64         BEFORE UPDATE OR INSERT ON metabib.title_field_entry
65         FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('title');
66
67 CREATE INDEX metabib_title_field_entry_index_vector_idx ON metabib.title_field_entry USING GIST (index_vector);
68 CREATE INDEX metabib_title_field_entry_value_idx ON metabib.title_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
69 CREATE INDEX metabib_title_field_entry_source_idx ON metabib.title_field_entry (source);
70
71 CREATE TABLE metabib.combined_title_field_entry (
72         record          BIGINT          NOT NULL,
73         metabib_field           INT             NULL,
74         index_vector    tsvector        NOT NULL
75 );
76 CREATE UNIQUE INDEX metabib_combined_title_field_entry_fakepk_idx ON metabib.combined_title_field_entry (record, COALESCE(metabib_field::TEXT,''));
77 CREATE INDEX metabib_combined_title_field_entry_index_vector_idx ON metabib.combined_title_field_entry USING GIST (index_vector);
78 CREATE INDEX metabib_combined_title_field_source_idx ON metabib.combined_title_field_entry (metabib_field);
79
80 CREATE TABLE metabib.author_field_entry (
81         id              BIGSERIAL       PRIMARY KEY,
82         source          BIGINT          NOT NULL,
83         field           INT             NOT NULL,
84         value           TEXT            NOT NULL,
85         index_vector    tsvector        NOT NULL
86 );
87 CREATE TRIGGER metabib_author_field_entry_fti_trigger
88         BEFORE UPDATE OR INSERT ON metabib.author_field_entry
89         FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('author');
90
91 CREATE INDEX metabib_author_field_entry_index_vector_idx ON metabib.author_field_entry USING GIST (index_vector);
92 CREATE INDEX metabib_author_field_entry_value_idx ON metabib.author_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
93 CREATE INDEX metabib_author_field_entry_source_idx ON metabib.author_field_entry (source);
94
95 CREATE TABLE metabib.combined_author_field_entry (
96         record          BIGINT          NOT NULL,
97         metabib_field           INT             NULL,
98         index_vector    tsvector        NOT NULL
99 );
100 CREATE UNIQUE INDEX metabib_combined_author_field_entry_fakepk_idx ON metabib.combined_author_field_entry (record, COALESCE(metabib_field::TEXT,''));
101 CREATE INDEX metabib_combined_author_field_entry_index_vector_idx ON metabib.combined_author_field_entry USING GIST (index_vector);
102 CREATE INDEX metabib_combined_author_field_source_idx ON metabib.combined_author_field_entry (metabib_field);
103
104 CREATE TABLE metabib.subject_field_entry (
105         id              BIGSERIAL       PRIMARY KEY,
106         source          BIGINT          NOT NULL,
107         field           INT             NOT NULL,
108         value           TEXT            NOT NULL,
109         index_vector    tsvector        NOT NULL
110 );
111 CREATE TRIGGER metabib_subject_field_entry_fti_trigger
112         BEFORE UPDATE OR INSERT ON metabib.subject_field_entry
113         FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('subject');
114
115 CREATE INDEX metabib_subject_field_entry_index_vector_idx ON metabib.subject_field_entry USING GIST (index_vector);
116 CREATE INDEX metabib_subject_field_entry_value_idx ON metabib.subject_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
117 CREATE INDEX metabib_subject_field_entry_source_idx ON metabib.subject_field_entry (source);
118
119 CREATE TABLE metabib.combined_subject_field_entry (
120         record          BIGINT          NOT NULL,
121         metabib_field           INT             NULL,
122         index_vector    tsvector        NOT NULL
123 );
124 CREATE UNIQUE INDEX metabib_combined_subject_field_entry_fakepk_idx ON metabib.combined_subject_field_entry (record, COALESCE(metabib_field::TEXT,''));
125 CREATE INDEX metabib_combined_subject_field_entry_index_vector_idx ON metabib.combined_subject_field_entry USING GIST (index_vector);
126 CREATE INDEX metabib_combined_subject_field_source_idx ON metabib.combined_subject_field_entry (metabib_field);
127
128 CREATE TABLE metabib.keyword_field_entry (
129         id              BIGSERIAL       PRIMARY KEY,
130         source          BIGINT          NOT NULL,
131         field           INT             NOT NULL,
132         value           TEXT            NOT NULL,
133         index_vector    tsvector        NOT NULL
134 );
135 CREATE TRIGGER metabib_keyword_field_entry_fti_trigger
136         BEFORE UPDATE OR INSERT ON metabib.keyword_field_entry
137         FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('keyword');
138
139 CREATE INDEX metabib_keyword_field_entry_index_vector_idx ON metabib.keyword_field_entry USING GIST (index_vector);
140 CREATE INDEX metabib_keyword_field_entry_value_idx ON metabib.keyword_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
141 CREATE INDEX metabib_keyword_field_entry_source_idx ON metabib.keyword_field_entry (source);
142
143 CREATE TABLE metabib.combined_keyword_field_entry (
144         record          BIGINT          NOT NULL,
145         metabib_field           INT             NULL,
146         index_vector    tsvector        NOT NULL
147 );
148 CREATE UNIQUE INDEX metabib_combined_keyword_field_entry_fakepk_idx ON metabib.combined_keyword_field_entry (record, COALESCE(metabib_field::TEXT,''));
149 CREATE INDEX metabib_combined_keyword_field_entry_index_vector_idx ON metabib.combined_keyword_field_entry USING GIST (index_vector);
150 CREATE INDEX metabib_combined_keyword_field_source_idx ON metabib.combined_keyword_field_entry (metabib_field);
151
152 CREATE TABLE metabib.series_field_entry (
153         id              BIGSERIAL       PRIMARY KEY,
154         source          BIGINT          NOT NULL,
155         field           INT             NOT NULL,
156         value           TEXT            NOT NULL,
157         index_vector    tsvector        NOT NULL
158 );
159 CREATE TRIGGER metabib_series_field_entry_fti_trigger
160         BEFORE UPDATE OR INSERT ON metabib.series_field_entry
161         FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('series');
162
163 CREATE INDEX metabib_series_field_entry_index_vector_idx ON metabib.series_field_entry USING GIST (index_vector);
164 CREATE INDEX metabib_series_field_entry_value_idx ON metabib.series_field_entry (SUBSTRING(value,1,1024)) WHERE index_vector = ''::TSVECTOR;
165 CREATE INDEX metabib_series_field_entry_source_idx ON metabib.series_field_entry (source);
166
167 CREATE TABLE metabib.combined_series_field_entry (
168         record          BIGINT          NOT NULL,
169         metabib_field           INT             NULL,
170         index_vector    tsvector        NOT NULL
171 );
172 CREATE UNIQUE INDEX metabib_combined_series_field_entry_fakepk_idx ON metabib.combined_series_field_entry (record, COALESCE(metabib_field::TEXT,''));
173 CREATE INDEX metabib_combined_series_field_entry_index_vector_idx ON metabib.combined_series_field_entry USING GIST (index_vector);
174 CREATE INDEX metabib_combined_series_field_source_idx ON metabib.combined_series_field_entry (metabib_field);
175
176 CREATE TABLE metabib.facet_entry (
177         id              BIGSERIAL       PRIMARY KEY,
178         source          BIGINT          NOT NULL,
179         field           INT             NOT NULL,
180         value           TEXT            NOT NULL
181 );
182 CREATE INDEX metabib_facet_entry_field_idx ON metabib.facet_entry (field);
183 CREATE INDEX metabib_facet_entry_value_idx ON metabib.facet_entry (SUBSTRING(value,1,1024));
184 CREATE INDEX metabib_facet_entry_source_idx ON metabib.facet_entry (source);
185
186 CREATE TABLE metabib.browse_entry (
187     id BIGSERIAL PRIMARY KEY,
188     value TEXT unique,
189     index_vector tsvector
190 );
191 CREATE INDEX metabib_browse_entry_index_vector_idx ON metabib.browse_entry USING GIN (index_vector);
192 CREATE TRIGGER metabib_browse_entry_fti_trigger
193     BEFORE INSERT OR UPDATE ON metabib.browse_entry
194     FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('keyword');
195
196
197 CREATE TABLE metabib.browse_entry_def_map (
198     id BIGSERIAL PRIMARY KEY,
199     entry BIGINT REFERENCES metabib.browse_entry (id),
200     def INT REFERENCES config.metabib_field (id),
201     source BIGINT REFERENCES biblio.record_entry (id)
202 );
203 CREATE INDEX browse_entry_def_map_def_idx ON metabib.browse_entry_def_map (def);
204 CREATE INDEX browse_entry_def_map_entry_idx ON metabib.browse_entry_def_map (entry);
205 CREATE INDEX browse_entry_def_map_source_idx ON metabib.browse_entry_def_map (source);
206
207
208
209 CREATE OR REPLACE FUNCTION metabib.facet_normalize_trigger () RETURNS TRIGGER AS $$
210 DECLARE
211     normalizer  RECORD;
212     facet_text  TEXT;
213 BEGIN
214     facet_text := NEW.value;
215
216     FOR normalizer IN
217         SELECT  n.func AS func,
218                 n.param_count AS param_count,
219                 m.params AS params
220           FROM  config.index_normalizer n
221                 JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
222           WHERE m.field = NEW.field AND m.pos < 0
223           ORDER BY m.pos LOOP
224
225             EXECUTE 'SELECT ' || normalizer.func || '(' ||
226                 quote_literal( facet_text ) ||
227                 CASE
228                     WHEN normalizer.param_count > 0
229                         THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
230                         ELSE ''
231                     END ||
232                 ')' INTO facet_text;
233
234     END LOOP;
235
236     NEW.value = facet_text;
237
238     RETURN NEW;
239 END;
240 $$ LANGUAGE PLPGSQL;
241
242 CREATE TRIGGER facet_normalize_tgr
243         BEFORE UPDATE OR INSERT ON metabib.facet_entry
244         FOR EACH ROW EXECUTE PROCEDURE metabib.facet_normalize_trigger();
245
246 CREATE OR REPLACE FUNCTION evergreen.facet_force_nfc() RETURNS TRIGGER AS $$
247 BEGIN
248     NEW.value := force_unicode_normal_form(NEW.value,'NFC');
249     RETURN NEW;
250 END;
251 $$ LANGUAGE PLPGSQL;
252
253 CREATE TRIGGER facet_force_nfc_tgr
254         BEFORE UPDATE OR INSERT ON metabib.facet_entry
255         FOR EACH ROW EXECUTE PROCEDURE evergreen.facet_force_nfc();
256
257 CREATE TABLE metabib.record_attr (
258         id              BIGINT  PRIMARY KEY REFERENCES biblio.record_entry (id) ON DELETE CASCADE,
259         attrs   HSTORE  NOT NULL DEFAULT ''::HSTORE
260 );
261 CREATE INDEX metabib_svf_attrs_idx ON metabib.record_attr USING GIST (attrs);
262 CREATE INDEX metabib_svf_date1_idx ON metabib.record_attr ((attrs->'date1'));
263 CREATE INDEX metabib_svf_dates_idx ON metabib.record_attr ((attrs->'date1'),(attrs->'date2'));
264
265 -- Back-compat view ... we're moving to an HSTORE world
266 CREATE TYPE metabib.rec_desc_type AS (
267     item_type       TEXT,
268     item_form       TEXT,
269     bib_level       TEXT,
270     control_type    TEXT,
271     char_encoding   TEXT,
272     enc_level       TEXT,
273     audience        TEXT,
274     lit_form        TEXT,
275     type_mat        TEXT,
276     cat_form        TEXT,
277     pub_status      TEXT,
278     item_lang       TEXT,
279     vr_format       TEXT,
280     date1           TEXT,
281     date2           TEXT
282 );
283
284 CREATE VIEW metabib.rec_descriptor AS
285     SELECT  id,
286             id AS record,
287             (populate_record(NULL::metabib.rec_desc_type, attrs)).*
288       FROM  metabib.record_attr;
289
290 -- Use a sequence that matches previous version, for easier upgrading.
291 CREATE SEQUENCE metabib.full_rec_id_seq;
292
293 CREATE TABLE metabib.real_full_rec (
294         id                  BIGINT      NOT NULL DEFAULT NEXTVAL('metabib.full_rec_id_seq'::REGCLASS),
295         record          BIGINT          NOT NULL,
296         tag             CHAR(3)         NOT NULL,
297         ind1            TEXT,
298         ind2            TEXT,
299         subfield        TEXT,
300         value           TEXT            NOT NULL,
301         index_vector    tsvector        NOT NULL
302 );
303 ALTER TABLE metabib.real_full_rec ADD PRIMARY KEY (id);
304
305 CREATE INDEX metabib_full_rec_tag_subfield_idx ON metabib.real_full_rec (tag,subfield);
306 CREATE INDEX metabib_full_rec_value_idx ON metabib.real_full_rec (substring(value,1,1024));
307 /* Enable LIKE to use an index for database clusters with locales other than C or POSIX */
308 CREATE INDEX metabib_full_rec_value_tpo_index ON metabib.real_full_rec (substring(value,1,1024) text_pattern_ops);
309 CREATE INDEX metabib_full_rec_record_idx ON metabib.real_full_rec (record);
310 CREATE INDEX metabib_full_rec_index_vector_idx ON metabib.real_full_rec USING GIST (index_vector);
311 CREATE INDEX metabib_full_rec_isxn_caseless_idx
312     ON metabib.real_full_rec (LOWER(value))
313     WHERE tag IN ('020', '022', '024');
314 -- This next index might fully supplant the one above, but leaving both for now.
315 -- (they are not too large)
316 -- The reason we need this index is to ensure that the query parser always
317 -- prefers this index over the simpler tag/subfield index, as this greatly
318 -- increases Vandelay overlay speed for these identifiers, especially when
319 -- a record has many of these fields (around > 4-6 seems like the cutoff
320 -- on at least one PG9.1 system)
321 -- A similar index could be added for other fields (e.g. 010), but one should
322 -- leave out the LOWER() in all other cases.
323 -- TODO: verify whether we can discard the non tag/subfield/substring version
324 -- above (metabib_full_rec_isxn_caseless_idx)
325 CREATE INDEX metabib_full_rec_02x_tag_subfield_lower_substring
326     ON metabib.real_full_rec (tag, subfield, LOWER(substring(value, 1, 1024)))
327     WHERE tag IN ('020', '022', '024');
328
329
330 CREATE TRIGGER metabib_full_rec_fti_trigger
331         BEFORE UPDATE OR INSERT ON metabib.real_full_rec
332         FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('default');
333
334 CREATE OR REPLACE VIEW metabib.full_rec AS
335     SELECT  id,
336             record,
337             tag,
338             ind1,
339             ind2,
340             subfield,
341             SUBSTRING(value,1,1024) AS value,
342             index_vector
343       FROM  metabib.real_full_rec;
344
345 CREATE OR REPLACE RULE metabib_full_rec_insert_rule
346     AS ON INSERT TO metabib.full_rec
347     DO INSTEAD
348     INSERT INTO metabib.real_full_rec VALUES (
349         COALESCE(NEW.id, NEXTVAL('metabib.full_rec_id_seq'::REGCLASS)),
350         NEW.record,
351         NEW.tag,
352         NEW.ind1,
353         NEW.ind2,
354         NEW.subfield,
355         NEW.value,
356         NEW.index_vector
357     );
358
359 CREATE OR REPLACE RULE metabib_full_rec_update_rule
360     AS ON UPDATE TO metabib.full_rec
361     DO INSTEAD
362     UPDATE  metabib.real_full_rec SET
363         id = NEW.id,
364         record = NEW.record,
365         tag = NEW.tag,
366         ind1 = NEW.ind1,
367         ind2 = NEW.ind2,
368         subfield = NEW.subfield,
369         value = NEW.value,
370         index_vector = NEW.index_vector
371       WHERE id = OLD.id;
372
373 CREATE OR REPLACE RULE metabib_full_rec_delete_rule
374     AS ON DELETE TO metabib.full_rec
375     DO INSTEAD
376     DELETE FROM metabib.real_full_rec WHERE id = OLD.id;
377
378 CREATE TABLE metabib.metarecord_source_map (
379         id              BIGSERIAL       PRIMARY KEY,
380         metarecord      BIGINT          NOT NULL,
381         source          BIGINT          NOT NULL
382 );
383 CREATE INDEX metabib_metarecord_source_map_metarecord_idx ON metabib.metarecord_source_map (metarecord);
384 CREATE INDEX metabib_metarecord_source_map_source_record_idx ON metabib.metarecord_source_map (source);
385
386 CREATE TYPE metabib.field_entry_template AS (
387         field_class     TEXT,
388         field           INT,
389         facet_field     BOOL,
390         search_field    BOOL,
391         browse_field   BOOL,
392         source          BIGINT,
393         value           TEXT,
394         authority       BIGINT
395 );
396
397
398 CREATE OR REPLACE FUNCTION biblio.extract_metabib_field_entry ( rid BIGINT, default_joiner TEXT ) RETURNS SETOF metabib.field_entry_template AS $func$
399 DECLARE
400     bib     biblio.record_entry%ROWTYPE;
401     idx     config.metabib_field%ROWTYPE;
402     xfrm        config.xml_transform%ROWTYPE;
403     prev_xfrm   TEXT;
404     transformed_xml TEXT;
405     xml_node    TEXT;
406     xml_node_list   TEXT[];
407     facet_text  TEXT;
408     browse_text TEXT;
409     raw_text    TEXT;
410     curr_text   TEXT;
411     joiner      TEXT := default_joiner; -- XXX will index defs supply a joiner?
412     authority_text TEXT;
413     authority_link BIGINT;
414     output_row  metabib.field_entry_template%ROWTYPE;
415 BEGIN
416
417     -- Start out with no field-use bools set
418     output_row.browse_field = FALSE;
419     output_row.facet_field = FALSE;
420     output_row.search_field = FALSE;
421
422     -- Get the record
423     SELECT INTO bib * FROM biblio.record_entry WHERE id = rid;
424
425     -- Loop over the indexing entries
426     FOR idx IN SELECT * FROM config.metabib_field ORDER BY format LOOP
427
428         SELECT INTO xfrm * from config.xml_transform WHERE name = idx.format;
429
430         -- See if we can skip the XSLT ... it's expensive
431         IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
432             -- Can't skip the transform
433             IF xfrm.xslt <> '---' THEN
434                 transformed_xml := oils_xslt_process(bib.marc,xfrm.xslt);
435             ELSE
436                 transformed_xml := bib.marc;
437             END IF;
438
439             prev_xfrm := xfrm.name;
440         END IF;
441
442         xml_node_list := oils_xpath( idx.xpath, transformed_xml, ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]] );
443
444         raw_text := NULL;
445         FOR xml_node IN SELECT x FROM unnest(xml_node_list) AS x LOOP
446             CONTINUE WHEN xml_node !~ E'^\\s*<';
447
448             curr_text := ARRAY_TO_STRING(
449                 oils_xpath( '//text()',
450                     REGEXP_REPLACE( -- This escapes all &s not followed by "amp;".  Data ise returned from oils_xpath (above) in UTF-8, not entity encoded
451                         REGEXP_REPLACE( -- This escapes embeded <s
452                             xml_node,
453                             $re$(>[^<]+)(<)([^>]+<)$re$,
454                             E'\\1&lt;\\3',
455                             'g'
456                         ),
457                         '&(?!amp;)',
458                         '&amp;',
459                         'g'
460                     )
461                 ),
462                 ' '
463             );
464
465             CONTINUE WHEN curr_text IS NULL OR curr_text = '';
466
467             IF raw_text IS NOT NULL THEN
468                 raw_text := raw_text || joiner;
469             END IF;
470
471             raw_text := COALESCE(raw_text,'') || curr_text;
472
473             -- autosuggest/metabib.browse_entry
474             IF idx.browse_field THEN
475
476                 IF idx.browse_xpath IS NOT NULL AND idx.browse_xpath <> '' THEN
477                     browse_text := oils_xpath_string( idx.browse_xpath, xml_node, joiner, ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]] );
478                 ELSE
479                     browse_text := curr_text;
480                 END IF;
481
482                 output_row.field_class = idx.field_class;
483                 output_row.field = idx.id;
484                 output_row.source = rid;
485                 output_row.value = BTRIM(REGEXP_REPLACE(browse_text, E'\\s+', ' ', 'g'));
486
487                 IF idx.authority_xpath IS NOT NULL AND idx.authority_xpath <> '' THEN
488                     authority_text := oils_xpath_string(
489                         idx.authority_xpath, xml_node, joiner,
490                         ARRAY[
491                             ARRAY[xfrm.prefix, xfrm.namespace_uri],
492                             ARRAY['xlink','http://www.w3.org/1999/xlink']
493                         ]
494                     );
495
496                     IF authority_text ~ '^\d+$' THEN
497                         authority_link := authority_text::BIGINT;
498                         PERFORM * FROM authority.record_entry WHERE id = authority_link;
499                         IF FOUND THEN
500                             output_row.authority := authority_link;
501                         END IF;
502                     END IF;
503
504                 END IF;
505
506                 output_row.browse_field = TRUE;
507                 RETURN NEXT output_row;
508                 output_row.browse_field = FALSE;
509             END IF;
510
511             -- insert raw node text for faceting
512             IF idx.facet_field THEN
513
514                 IF idx.facet_xpath IS NOT NULL AND idx.facet_xpath <> '' THEN
515                     facet_text := oils_xpath_string( idx.facet_xpath, xml_node, joiner, ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]] );
516                 ELSE
517                     facet_text := curr_text;
518                 END IF;
519
520                 output_row.field_class = idx.field_class;
521                 output_row.field = -1 * idx.id;
522                 output_row.source = rid;
523                 output_row.value = BTRIM(REGEXP_REPLACE(facet_text, E'\\s+', ' ', 'g'));
524
525                 output_row.facet_field = TRUE;
526                 RETURN NEXT output_row;
527                 output_row.facet_field = FALSE;
528             END IF;
529
530         END LOOP;
531
532         CONTINUE WHEN raw_text IS NULL OR raw_text = '';
533
534         -- insert combined node text for searching
535         IF idx.search_field THEN
536             output_row.field_class = idx.field_class;
537             output_row.field = idx.id;
538             output_row.source = rid;
539             output_row.value = BTRIM(REGEXP_REPLACE(raw_text, E'\\s+', ' ', 'g'));
540
541             output_row.search_field = TRUE;
542             RETURN NEXT output_row;
543             output_row.search_field = FALSE;
544         END IF;
545
546     END LOOP;
547
548 END;
549
550 $func$ LANGUAGE PLPGSQL;
551
552 CREATE OR REPLACE FUNCTION metabib.update_combined_index_vectors(bib_id BIGINT) RETURNS VOID AS $func$
553 BEGIN
554     DELETE FROM metabib.combined_keyword_field_entry WHERE record = bib_id;
555     INSERT INTO metabib.combined_keyword_field_entry(record, metabib_field, index_vector)
556         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
557         FROM metabib.keyword_field_entry WHERE source = bib_id GROUP BY field;
558     INSERT INTO metabib.combined_keyword_field_entry(record, metabib_field, index_vector)
559         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
560         FROM metabib.keyword_field_entry WHERE source = bib_id;
561
562     DELETE FROM metabib.combined_title_field_entry WHERE record = bib_id;
563     INSERT INTO metabib.combined_title_field_entry(record, metabib_field, index_vector)
564         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
565         FROM metabib.title_field_entry WHERE source = bib_id GROUP BY field;
566     INSERT INTO metabib.combined_title_field_entry(record, metabib_field, index_vector)
567         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
568         FROM metabib.title_field_entry WHERE source = bib_id;
569
570     DELETE FROM metabib.combined_author_field_entry WHERE record = bib_id;
571     INSERT INTO metabib.combined_author_field_entry(record, metabib_field, index_vector)
572         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
573         FROM metabib.author_field_entry WHERE source = bib_id GROUP BY field;
574     INSERT INTO metabib.combined_author_field_entry(record, metabib_field, index_vector)
575         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
576         FROM metabib.author_field_entry WHERE source = bib_id;
577
578     DELETE FROM metabib.combined_subject_field_entry WHERE record = bib_id;
579     INSERT INTO metabib.combined_subject_field_entry(record, metabib_field, index_vector)
580         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
581         FROM metabib.subject_field_entry WHERE source = bib_id GROUP BY field;
582     INSERT INTO metabib.combined_subject_field_entry(record, metabib_field, index_vector)
583         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
584         FROM metabib.subject_field_entry WHERE source = bib_id;
585
586     DELETE FROM metabib.combined_series_field_entry WHERE record = bib_id;
587     INSERT INTO metabib.combined_series_field_entry(record, metabib_field, index_vector)
588         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
589         FROM metabib.series_field_entry WHERE source = bib_id GROUP BY field;
590     INSERT INTO metabib.combined_series_field_entry(record, metabib_field, index_vector)
591         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
592         FROM metabib.series_field_entry WHERE source = bib_id;
593
594     DELETE FROM metabib.combined_identifier_field_entry WHERE record = bib_id;
595     INSERT INTO metabib.combined_identifier_field_entry(record, metabib_field, index_vector)
596         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
597         FROM metabib.identifier_field_entry WHERE source = bib_id GROUP BY field;
598     INSERT INTO metabib.combined_identifier_field_entry(record, metabib_field, index_vector)
599         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
600         FROM metabib.identifier_field_entry WHERE source = bib_id;
601
602 END;
603 $func$ LANGUAGE PLPGSQL;
604
605 CREATE OR REPLACE FUNCTION metabib.reingest_metabib_field_entries( bib_id BIGINT, skip_facet BOOL DEFAULT FALSE, skip_browse BOOL DEFAULT FALSE, skip_search BOOL DEFAULT FALSE ) RETURNS VOID AS $func$
606 DECLARE
607     fclass          RECORD;
608     ind_data        metabib.field_entry_template%ROWTYPE;
609     mbe_row         metabib.browse_entry%ROWTYPE;
610     mbe_id          BIGINT;
611     b_skip_facet    BOOL;
612     b_skip_browse   BOOL;
613     b_skip_search   BOOL;
614 BEGIN
615
616     SELECT COALESCE(NULLIF(skip_facet, FALSE), EXISTS (SELECT enabled FROM config.internal_flag WHERE name =  'ingest.skip_facet_indexing' AND enabled)) INTO b_skip_facet;
617     SELECT COALESCE(NULLIF(skip_browse, FALSE), EXISTS (SELECT enabled FROM config.internal_flag WHERE name =  'ingest.skip_browse_indexing' AND enabled)) INTO b_skip_browse;
618     SELECT COALESCE(NULLIF(skip_search, FALSE), EXISTS (SELECT enabled FROM config.internal_flag WHERE name =  'ingest.skip_search_indexing' AND enabled)) INTO b_skip_search;
619
620     PERFORM * FROM config.internal_flag WHERE name = 'ingest.assume_inserts_only' AND enabled;
621     IF NOT FOUND THEN
622         IF NOT b_skip_search THEN
623             FOR fclass IN SELECT * FROM config.metabib_class LOOP
624                 -- RAISE NOTICE 'Emptying out %', fclass.name;
625                 EXECUTE $$DELETE FROM metabib.$$ || fclass.name || $$_field_entry WHERE source = $$ || bib_id;
626             END LOOP;
627         END IF;
628         IF NOT b_skip_facet THEN
629             DELETE FROM metabib.facet_entry WHERE source = bib_id;
630         END IF;
631         IF NOT b_skip_browse THEN
632             DELETE FROM metabib.browse_entry_def_map WHERE source = bib_id;
633         END IF;
634     END IF;
635
636     FOR ind_data IN SELECT * FROM biblio.extract_metabib_field_entry( bib_id ) LOOP
637         IF ind_data.field < 0 THEN
638             ind_data.field = -1 * ind_data.field;
639         END IF;
640
641         IF ind_data.facet_field AND NOT b_skip_facet THEN
642             INSERT INTO metabib.facet_entry (field, source, value)
643                 VALUES (ind_data.field, ind_data.source, ind_data.value);
644         END IF;
645
646         IF ind_data.browse_field AND NOT b_skip_browse THEN
647             -- A caveat about this SELECT: this should take care of replacing
648             -- old mbe rows when data changes, but not if normalization (by
649             -- which I mean specifically the output of
650             -- evergreen.oils_tsearch2()) changes.  It may or may not be
651             -- expensive to add a comparison of index_vector to index_vector
652             -- to the WHERE clause below.
653             SELECT INTO mbe_row * FROM metabib.browse_entry WHERE value = ind_data.value;
654             IF FOUND THEN
655                 mbe_id := mbe_row.id;
656             ELSE
657                 INSERT INTO metabib.browse_entry (value) VALUES
658                     (metabib.browse_normalize(ind_data.value, ind_data.field));
659                 mbe_id := CURRVAL('metabib.browse_entry_id_seq'::REGCLASS);
660             END IF;
661
662             INSERT INTO metabib.browse_entry_def_map (entry, def, source, authority)
663                 VALUES (mbe_id, ind_data.field, ind_data.source, ind_data.authority);
664         END IF;
665
666         -- Avoid inserting duplicate rows, but retain granularity of being
667         -- able to search browse fields with "starts with" type operators
668         -- (for example, for titles of songs in music albums)
669         IF (ind_data.search_field OR ind_data.browse_field) AND NOT b_skip_search THEN
670             EXECUTE 'SELECT 1 FROM metabib.' || ind_data.field_class ||
671                 '_field_entry WHERE field = $1 AND source = $2 AND value = $3'
672                 INTO mbe_id USING ind_data.field, ind_data.source, ind_data.value;
673                 -- RAISE NOTICE 'Search for an already matching row returned %', mbe_id;
674             IF mbe_id IS NULL THEN
675                 EXECUTE $$
676                 INSERT INTO metabib.$$ || ind_data.field_class || $$_field_entry (field, source, value)
677                     VALUES ($$ ||
678                         quote_literal(ind_data.field) || $$, $$ ||
679                         quote_literal(ind_data.source) || $$, $$ ||
680                         quote_literal(ind_data.value) ||
681                     $$);$$;
682             END IF;
683         END IF;
684
685     END LOOP;
686
687     IF NOT b_skip_search THEN
688         PERFORM metabib.update_combined_index_vectors(bib_id);
689     END IF;
690
691     RETURN;
692 END;
693 $func$ LANGUAGE PLPGSQL;
694
695 -- default to a space joiner
696 CREATE OR REPLACE FUNCTION biblio.extract_metabib_field_entry ( BIGINT ) RETURNS SETOF metabib.field_entry_template AS $func$
697         SELECT * FROM biblio.extract_metabib_field_entry($1, ' ');
698 $func$ LANGUAGE SQL;
699
700 CREATE OR REPLACE FUNCTION authority.flatten_marc ( rid BIGINT ) RETURNS SETOF authority.full_rec AS $func$
701 DECLARE
702         auth    authority.record_entry%ROWTYPE;
703         output  authority.full_rec%ROWTYPE;
704         field   RECORD;
705 BEGIN
706         SELECT INTO auth * FROM authority.record_entry WHERE id = rid;
707
708         FOR field IN SELECT * FROM vandelay.flatten_marc( auth.marc ) LOOP
709                 output.record := rid;
710                 output.ind1 := field.ind1;
711                 output.ind2 := field.ind2;
712                 output.tag := field.tag;
713                 output.subfield := field.subfield;
714                 output.value := field.value;
715
716                 RETURN NEXT output;
717         END LOOP;
718 END;
719 $func$ LANGUAGE PLPGSQL;
720
721 CREATE OR REPLACE FUNCTION biblio.flatten_marc ( rid BIGINT ) RETURNS SETOF metabib.full_rec AS $func$
722 DECLARE
723         bib     biblio.record_entry%ROWTYPE;
724         output  metabib.full_rec%ROWTYPE;
725         field   RECORD;
726 BEGIN
727         SELECT INTO bib * FROM biblio.record_entry WHERE id = rid;
728
729         FOR field IN SELECT * FROM vandelay.flatten_marc( bib.marc ) LOOP
730                 output.record := rid;
731                 output.ind1 := field.ind1;
732                 output.ind2 := field.ind2;
733                 output.tag := field.tag;
734                 output.subfield := field.subfield;
735                 output.value := field.value;
736
737                 RETURN NEXT output;
738         END LOOP;
739 END;
740 $func$ LANGUAGE PLPGSQL;
741
742 CREATE OR REPLACE FUNCTION vandelay.marc21_record_type( marc TEXT ) RETURNS config.marc21_rec_type_map AS $func$
743 DECLARE
744         ldr         TEXT;
745         tval        TEXT;
746         tval_rec    RECORD;
747         bval        TEXT;
748         bval_rec    RECORD;
749     retval      config.marc21_rec_type_map%ROWTYPE;
750 BEGIN
751     ldr := oils_xpath_string( '//*[local-name()="leader"]', marc );
752
753     IF ldr IS NULL OR ldr = '' THEN
754         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
755         RETURN retval;
756     END IF;
757
758     SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
759     SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
760
761
762     tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
763     bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
764
765     -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
766
767     SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
768
769
770     IF retval.code IS NULL THEN
771         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
772     END IF;
773
774     RETURN retval;
775 END;
776 $func$ LANGUAGE PLPGSQL;
777
778 CREATE OR REPLACE FUNCTION biblio.marc21_record_type( rid BIGINT ) RETURNS config.marc21_rec_type_map AS $func$
779     SELECT * FROM vandelay.marc21_record_type( (SELECT marc FROM biblio.record_entry WHERE id = $1) );
780 $func$ LANGUAGE SQL;
781
782 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field( marc TEXT, ff TEXT ) RETURNS TEXT AS $func$
783 DECLARE
784     rtype       TEXT;
785     ff_pos      RECORD;
786     tag_data    RECORD;
787     val         TEXT;
788 BEGIN
789     rtype := (vandelay.marc21_record_type( marc )).code;
790     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
791         IF ff_pos.tag = 'ldr' THEN
792             val := oils_xpath_string('//*[local-name()="leader"]', marc);
793             IF val IS NOT NULL THEN
794                 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
795                 RETURN val;
796             END IF;
797         ELSE
798             FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
799                 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
800                 RETURN val;
801             END LOOP;
802         END IF;
803         val := REPEAT( ff_pos.default_val, ff_pos.length );
804         RETURN val;
805     END LOOP;
806
807     RETURN NULL;
808 END;
809 $func$ LANGUAGE PLPGSQL;
810
811 CREATE OR REPLACE FUNCTION biblio.marc21_extract_fixed_field( rid BIGINT, ff TEXT ) RETURNS TEXT AS $func$
812     SELECT * FROM vandelay.marc21_extract_fixed_field( (SELECT marc FROM biblio.record_entry WHERE id = $1), $2 );
813 $func$ LANGUAGE SQL;
814
815 -- CREATE TYPE biblio.record_ff_map AS (record BIGINT, ff_name TEXT, ff_value TEXT);
816 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_all_fixed_fields( marc TEXT ) RETURNS SETOF biblio.record_ff_map AS $func$
817 DECLARE
818     tag_data    TEXT;
819     rtype       TEXT;
820     ff_pos      RECORD;
821     output      biblio.record_ff_map%ROWTYPE;
822 BEGIN
823     rtype := (vandelay.marc21_record_type( marc )).code;
824
825     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE rec_type = rtype ORDER BY tag DESC LOOP
826         output.ff_name  := ff_pos.fixed_field;
827         output.ff_value := NULL;
828
829         IF ff_pos.tag = 'ldr' THEN
830             output.ff_value := oils_xpath_string('//*[local-name()="leader"]', marc);
831             IF output.ff_value IS NOT NULL THEN
832                 output.ff_value := SUBSTRING( output.ff_value, ff_pos.start_pos + 1, ff_pos.length );
833                 RETURN NEXT output;
834                 output.ff_value := NULL;
835             END IF;
836         ELSE
837             FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
838                 output.ff_value := SUBSTRING( tag_data, ff_pos.start_pos + 1, ff_pos.length );
839                 IF output.ff_value IS NULL THEN output.ff_value := REPEAT( ff_pos.default_val, ff_pos.length ); END IF;
840                 RETURN NEXT output;
841                 output.ff_value := NULL;
842             END LOOP;
843         END IF;
844
845     END LOOP;
846
847     RETURN;
848 END;
849 $func$ LANGUAGE PLPGSQL;
850
851 CREATE OR REPLACE FUNCTION biblio.marc21_extract_all_fixed_fields( rid BIGINT ) RETURNS SETOF biblio.record_ff_map AS $func$
852     SELECT $1 AS record, ff_name, ff_value FROM vandelay.marc21_extract_all_fixed_fields( (SELECT marc FROM biblio.record_entry WHERE id = $1) );
853 $func$ LANGUAGE SQL;
854
855 CREATE OR REPLACE FUNCTION biblio.marc21_physical_characteristics( rid BIGINT ) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
856     SELECT id, $1 AS record, ptype, subfield, value FROM vandelay.marc21_physical_characteristics( (SELECT marc FROM biblio.record_entry WHERE id = $1) );
857 $func$ LANGUAGE SQL;
858
859 CREATE OR REPLACE FUNCTION biblio.extract_quality ( marc TEXT, best_lang TEXT, best_type TEXT ) RETURNS INT AS $func$
860 DECLARE
861     qual        INT;
862     ldr         TEXT;
863     tval        TEXT;
864     tval_rec    RECORD;
865     bval        TEXT;
866     bval_rec    RECORD;
867     type_map    RECORD;
868     ff_pos      RECORD;
869     ff_tag_data TEXT;
870 BEGIN
871
872     IF marc IS NULL OR marc = '' THEN
873         RETURN NULL;
874     END IF;
875
876     -- First, the count of tags
877     qual := ARRAY_UPPER(oils_xpath('*[local-name()="datafield"]', marc), 1);
878
879     -- now go through a bunch of pain to get the record type
880     IF best_type IS NOT NULL THEN
881         ldr := (oils_xpath('//*[local-name()="leader"]/text()', marc))[1];
882
883         IF ldr IS NOT NULL THEN
884             SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
885             SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
886
887
888             tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
889             bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
890
891             -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
892
893             SELECT * INTO type_map FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
894
895             IF type_map.code IS NOT NULL THEN
896                 IF best_type = type_map.code THEN
897                     qual := qual + qual / 2;
898                 END IF;
899
900                 FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = 'Lang' AND rec_type = type_map.code ORDER BY tag DESC LOOP
901                     ff_tag_data := SUBSTRING((oils_xpath('//*[@tag="' || ff_pos.tag || '"]/text()',marc))[1], ff_pos.start_pos + 1, ff_pos.length);
902                     IF ff_tag_data = best_lang THEN
903                             qual := qual + 100;
904                     END IF;
905                 END LOOP;
906             END IF;
907         END IF;
908     END IF;
909
910     -- Now look for some quality metrics
911     -- DCL record?
912     IF ARRAY_UPPER(oils_xpath('//*[@tag="040"]/*[@code="a" and contains(.,"DLC")]', marc), 1) = 1 THEN
913         qual := qual + 10;
914     END IF;
915
916     -- From OCLC?
917     IF (oils_xpath('//*[@tag="003"]/text()', marc))[1] ~* E'oclo?c' THEN
918         qual := qual + 10;
919     END IF;
920
921     RETURN qual;
922
923 END;
924 $func$ LANGUAGE PLPGSQL;
925
926 CREATE OR REPLACE FUNCTION biblio.extract_fingerprint ( marc text ) RETURNS TEXT AS $func$
927 DECLARE
928         idx             config.biblio_fingerprint%ROWTYPE;
929         xfrm            config.xml_transform%ROWTYPE;
930         prev_xfrm       TEXT;
931         transformed_xml TEXT;
932         xml_node        TEXT;
933         xml_node_list   TEXT[];
934         raw_text        TEXT;
935     output_text TEXT := '';
936 BEGIN
937
938     IF marc IS NULL OR marc = '' THEN
939         RETURN NULL;
940     END IF;
941
942         -- Loop over the indexing entries
943         FOR idx IN SELECT * FROM config.biblio_fingerprint ORDER BY format, id LOOP
944
945                 SELECT INTO xfrm * from config.xml_transform WHERE name = idx.format;
946
947                 -- See if we can skip the XSLT ... it's expensive
948                 IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
949                         -- Can't skip the transform
950                         IF xfrm.xslt <> '---' THEN
951                                 transformed_xml := oils_xslt_process(marc,xfrm.xslt);
952                         ELSE
953                                 transformed_xml := marc;
954                         END IF;
955
956                         prev_xfrm := xfrm.name;
957                 END IF;
958
959                 raw_text := COALESCE(
960             naco_normalize(
961                 ARRAY_TO_STRING(
962                     oils_xpath(
963                         '//text()',
964                         (oils_xpath(
965                             idx.xpath,
966                             transformed_xml,
967                             ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]] 
968                         ))[1]
969                     ),
970                     ''
971                 )
972             ),
973             ''
974         );
975
976         raw_text := REGEXP_REPLACE(raw_text, E'\\[.+?\\]', E'');
977         raw_text := REGEXP_REPLACE(raw_text, E'\\mthe\\M|\\man?d?d\\M', E'', 'g'); -- arg! the pain!
978
979         IF idx.first_word IS TRUE THEN
980             raw_text := REGEXP_REPLACE(raw_text, E'^(\\w+).*?$', E'\\1');
981         END IF;
982
983                 output_text := output_text || REGEXP_REPLACE(raw_text, E'\\s+', '', 'g');
984
985         END LOOP;
986
987     RETURN output_text;
988
989 END;
990 $func$ LANGUAGE PLPGSQL;
991
992 -- BEFORE UPDATE OR INSERT trigger for biblio.record_entry
993 CREATE OR REPLACE FUNCTION biblio.fingerprint_trigger () RETURNS TRIGGER AS $func$
994 BEGIN
995
996     -- For TG_ARGV, first param is language (like 'eng'), second is record type (like 'BKS')
997
998     IF NEW.deleted IS TRUE THEN -- we don't much care, then, do we?
999         RETURN NEW;
1000     END IF;
1001
1002     NEW.fingerprint := biblio.extract_fingerprint(NEW.marc);
1003     NEW.quality := biblio.extract_quality(NEW.marc, TG_ARGV[0], TG_ARGV[1]);
1004
1005     RETURN NEW;
1006
1007 END;
1008 $func$ LANGUAGE PLPGSQL;
1009
1010 CREATE OR REPLACE FUNCTION metabib.reingest_metabib_full_rec( bib_id BIGINT ) RETURNS VOID AS $func$
1011 BEGIN
1012     PERFORM * FROM config.internal_flag WHERE name = 'ingest.assume_inserts_only' AND enabled;
1013     IF NOT FOUND THEN
1014         DELETE FROM metabib.real_full_rec WHERE record = bib_id;
1015     END IF;
1016     INSERT INTO metabib.real_full_rec (record, tag, ind1, ind2, subfield, value)
1017         SELECT record, tag, ind1, ind2, subfield, value FROM biblio.flatten_marc( bib_id );
1018
1019     RETURN;
1020 END;
1021 $func$ LANGUAGE PLPGSQL;
1022
1023 CREATE OR REPLACE FUNCTION biblio.extract_located_uris( bib_id BIGINT, marcxml TEXT, editor_id INT ) RETURNS VOID AS $func$
1024 DECLARE
1025     uris            TEXT[];
1026     uri_xml         TEXT;
1027     uri_label       TEXT;
1028     uri_href        TEXT;
1029     uri_use         TEXT;
1030     uri_owner_list  TEXT[];
1031     uri_owner       TEXT;
1032     uri_owner_id    INT;
1033     uri_id          INT;
1034     uri_cn_id       INT;
1035     uri_map_id      INT;
1036 BEGIN
1037
1038     -- Clear any URI mappings and call numbers for this bib.
1039     -- This leads to acn / auricnm inflation, but also enables
1040     -- old acn/auricnm's to go away and for bibs to be deleted.
1041     FOR uri_cn_id IN SELECT id FROM asset.call_number WHERE record = bib_id AND label = '##URI##' AND NOT deleted LOOP
1042         DELETE FROM asset.uri_call_number_map WHERE call_number = uri_cn_id;
1043         DELETE FROM asset.call_number WHERE id = uri_cn_id;
1044     END LOOP;
1045
1046     uris := oils_xpath('//*[@tag="856" and (@ind1="4" or @ind1="1") and (@ind2="0" or @ind2="1")]',marcxml);
1047     IF ARRAY_UPPER(uris,1) > 0 THEN
1048         FOR i IN 1 .. ARRAY_UPPER(uris, 1) LOOP
1049             -- First we pull info out of the 856
1050             uri_xml     := uris[i];
1051
1052             uri_href    := (oils_xpath('//*[@code="u"]/text()',uri_xml))[1];
1053             uri_label   := (oils_xpath('//*[@code="y"]/text()|//*[@code="3"]/text()',uri_xml))[1];
1054             uri_use     := (oils_xpath('//*[@code="z"]/text()|//*[@code="2"]/text()|//*[@code="n"]/text()',uri_xml))[1];
1055
1056             IF uri_label IS NULL THEN
1057                 uri_label := uri_href;
1058             END IF;
1059             CONTINUE WHEN uri_href IS NULL;
1060
1061             -- Get the distinct list of libraries wanting to use 
1062             SELECT  ARRAY_ACCUM(
1063                         DISTINCT REGEXP_REPLACE(
1064                             x,
1065                             $re$^.*?\((\w+)\).*$$re$,
1066                             E'\\1'
1067                         )
1068                     ) INTO uri_owner_list
1069               FROM  UNNEST(
1070                         oils_xpath(
1071                             '//*[@code="9"]/text()|//*[@code="w"]/text()|//*[@code="n"]/text()',
1072                             uri_xml
1073                         )
1074                     )x;
1075
1076             IF ARRAY_UPPER(uri_owner_list,1) > 0 THEN
1077
1078                 -- look for a matching uri
1079                 IF uri_use IS NULL THEN
1080                     SELECT id INTO uri_id
1081                         FROM asset.uri
1082                         WHERE label = uri_label AND href = uri_href AND use_restriction IS NULL AND active
1083                         ORDER BY id LIMIT 1;
1084                     IF NOT FOUND THEN -- create one
1085                         INSERT INTO asset.uri (label, href, use_restriction) VALUES (uri_label, uri_href, uri_use);
1086                         SELECT id INTO uri_id
1087                             FROM asset.uri
1088                             WHERE label = uri_label AND href = uri_href AND use_restriction IS NULL AND active;
1089                     END IF;
1090                 ELSE
1091                     SELECT id INTO uri_id
1092                         FROM asset.uri
1093                         WHERE label = uri_label AND href = uri_href AND use_restriction = uri_use AND active
1094                         ORDER BY id LIMIT 1;
1095                     IF NOT FOUND THEN -- create one
1096                         INSERT INTO asset.uri (label, href, use_restriction) VALUES (uri_label, uri_href, uri_use);
1097                         SELECT id INTO uri_id
1098                             FROM asset.uri
1099                             WHERE label = uri_label AND href = uri_href AND use_restriction = uri_use AND active;
1100                     END IF;
1101                 END IF;
1102
1103                 FOR j IN 1 .. ARRAY_UPPER(uri_owner_list, 1) LOOP
1104                     uri_owner := uri_owner_list[j];
1105
1106                     SELECT id INTO uri_owner_id FROM actor.org_unit WHERE shortname = uri_owner;
1107                     CONTINUE WHEN NOT FOUND;
1108
1109                     -- we need a call number to link through
1110                     SELECT id INTO uri_cn_id FROM asset.call_number WHERE owning_lib = uri_owner_id AND record = bib_id AND label = '##URI##' AND NOT deleted;
1111                     IF NOT FOUND THEN
1112                         INSERT INTO asset.call_number (owning_lib, record, create_date, edit_date, creator, editor, label)
1113                             VALUES (uri_owner_id, bib_id, 'now', 'now', editor_id, editor_id, '##URI##');
1114                         SELECT id INTO uri_cn_id FROM asset.call_number WHERE owning_lib = uri_owner_id AND record = bib_id AND label = '##URI##' AND NOT deleted;
1115                     END IF;
1116
1117                     -- now, link them if they're not already
1118                     SELECT id INTO uri_map_id FROM asset.uri_call_number_map WHERE call_number = uri_cn_id AND uri = uri_id;
1119                     IF NOT FOUND THEN
1120                         INSERT INTO asset.uri_call_number_map (call_number, uri) VALUES (uri_cn_id, uri_id);
1121                     END IF;
1122
1123                 END LOOP;
1124
1125             END IF;
1126
1127         END LOOP;
1128     END IF;
1129
1130     RETURN;
1131 END;
1132 $func$ LANGUAGE PLPGSQL;
1133
1134 CREATE OR REPLACE FUNCTION metabib.remap_metarecord_for_bib( bib_id BIGINT, fp TEXT ) RETURNS BIGINT AS $func$
1135 DECLARE
1136     source_count    INT;
1137     old_mr          BIGINT;
1138     tmp_mr          metabib.metarecord%ROWTYPE;
1139     deleted_mrs     BIGINT[];
1140 BEGIN
1141
1142     DELETE FROM metabib.metarecord_source_map WHERE source = bib_id; -- Rid ourselves of the search-estimate-killing linkage
1143
1144     FOR tmp_mr IN SELECT  m.* FROM  metabib.metarecord m JOIN metabib.metarecord_source_map s ON (s.metarecord = m.id) WHERE s.source = bib_id LOOP
1145
1146         IF old_mr IS NULL AND fp = tmp_mr.fingerprint THEN -- Find the first fingerprint-matching
1147             old_mr := tmp_mr.id;
1148         ELSE
1149             SELECT COUNT(*) INTO source_count FROM metabib.metarecord_source_map WHERE metarecord = tmp_mr.id;
1150             IF source_count = 0 THEN -- No other records
1151                 deleted_mrs := ARRAY_APPEND(deleted_mrs, tmp_mr.id);
1152                 DELETE FROM metabib.metarecord WHERE id = tmp_mr.id;
1153             END IF;
1154         END IF;
1155
1156     END LOOP;
1157
1158     IF old_mr IS NULL THEN -- we found no suitable, preexisting MR based on old source maps
1159         SELECT id INTO old_mr FROM metabib.metarecord WHERE fingerprint = fp; -- is there one for our current fingerprint?
1160         IF old_mr IS NULL THEN -- nope, create one and grab its id
1161             INSERT INTO metabib.metarecord ( fingerprint, master_record ) VALUES ( fp, bib_id );
1162             SELECT id INTO old_mr FROM metabib.metarecord WHERE fingerprint = fp;
1163         ELSE -- indeed there is. update it with a null cache and recalcualated master record
1164             UPDATE  metabib.metarecord
1165               SET   mods = NULL,
1166                     master_record = ( SELECT id FROM biblio.record_entry WHERE fingerprint = fp ORDER BY quality DESC LIMIT 1)
1167               WHERE id = old_mr;
1168         END IF;
1169     ELSE -- there was one we already attached to, update its mods cache and master_record
1170         UPDATE  metabib.metarecord
1171           SET   mods = NULL,
1172                 master_record = ( SELECT id FROM biblio.record_entry WHERE fingerprint = fp ORDER BY quality DESC LIMIT 1)
1173           WHERE id = old_mr;
1174     END IF;
1175
1176     INSERT INTO metabib.metarecord_source_map (metarecord, source) VALUES (old_mr, bib_id); -- new source mapping
1177
1178     IF ARRAY_UPPER(deleted_mrs,1) > 0 THEN
1179         UPDATE action.hold_request SET target = old_mr WHERE target IN ( SELECT unnest(deleted_mrs) ) AND hold_type = 'M'; -- if we had to delete any MRs above, make sure their holds are moved
1180     END IF;
1181
1182     RETURN old_mr;
1183
1184 END;
1185 $func$ LANGUAGE PLPGSQL;
1186
1187 CREATE OR REPLACE FUNCTION biblio.map_authority_linking (bibid BIGINT, marc TEXT) RETURNS BIGINT AS $func$
1188     DELETE FROM authority.bib_linking WHERE bib = $1;
1189     INSERT INTO authority.bib_linking (bib, authority)
1190         SELECT  y.bib,
1191                 y.authority
1192           FROM (    SELECT  DISTINCT $1 AS bib,
1193                             BTRIM(remove_paren_substring(txt))::BIGINT AS authority
1194                       FROM  unnest(oils_xpath('//*[@code="0"]/text()',$2)) x(txt)
1195                       WHERE BTRIM(remove_paren_substring(txt)) ~ $re$^\d+$$re$
1196                 ) y JOIN authority.record_entry r ON r.id = y.authority;
1197     SELECT $1;
1198 $func$ LANGUAGE SQL;
1199
1200 -- AFTER UPDATE OR INSERT trigger for biblio.record_entry
1201 CREATE OR REPLACE FUNCTION biblio.indexing_ingest_or_delete () RETURNS TRIGGER AS $func$
1202 DECLARE
1203     transformed_xml TEXT;
1204     prev_xfrm       TEXT;
1205     normalizer      RECORD;
1206     xfrm            config.xml_transform%ROWTYPE;
1207     attr_value      TEXT;
1208     new_attrs       HSTORE := ''::HSTORE;
1209     attr_def        config.record_attr_definition%ROWTYPE;
1210 BEGIN
1211
1212     IF NEW.deleted IS TRUE THEN -- If this bib is deleted
1213         PERFORM * FROM config.internal_flag WHERE
1214             name = 'ingest.metarecord_mapping.preserve_on_delete' AND enabled;
1215         IF NOT FOUND THEN
1216             -- One needs to keep these around to support searches
1217             -- with the #deleted modifier, so one should turn on the named
1218             -- internal flag for that functionality.
1219             DELETE FROM metabib.metarecord_source_map WHERE source = NEW.id;
1220             DELETE FROM metabib.record_attr WHERE id = NEW.id;
1221         END IF;
1222
1223         DELETE FROM authority.bib_linking WHERE bib = NEW.id; -- Avoid updating fields in bibs that are no longer visible
1224         DELETE FROM biblio.peer_bib_copy_map WHERE peer_record = NEW.id; -- Separate any multi-homed items
1225         DELETE FROM metabib.browse_entry_def_map WHERE source = NEW.id; -- Don't auto-suggest deleted bibs
1226         RETURN NEW; -- and we're done
1227     END IF;
1228
1229     IF TG_OP = 'UPDATE' THEN -- re-ingest?
1230         PERFORM * FROM config.internal_flag WHERE name = 'ingest.reingest.force_on_same_marc' AND enabled;
1231
1232         IF NOT FOUND AND OLD.marc = NEW.marc THEN -- don't do anything if the MARC didn't change
1233             RETURN NEW;
1234         END IF;
1235     END IF;
1236
1237     -- Record authority linking
1238     PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_linking' AND enabled;
1239     IF NOT FOUND THEN
1240         PERFORM biblio.map_authority_linking( NEW.id, NEW.marc );
1241     END IF;
1242
1243     -- Flatten and insert the mfr data
1244     PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_metabib_full_rec' AND enabled;
1245     IF NOT FOUND THEN
1246         PERFORM metabib.reingest_metabib_full_rec(NEW.id);
1247
1248         -- Now we pull out attribute data, which is dependent on the mfr for all but XPath-based fields
1249         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_metabib_rec_descriptor' AND enabled;
1250         IF NOT FOUND THEN
1251             FOR attr_def IN SELECT * FROM config.record_attr_definition ORDER BY format LOOP
1252
1253                 IF attr_def.tag IS NOT NULL THEN -- tag (and optional subfield list) selection
1254                     SELECT  ARRAY_TO_STRING(ARRAY_ACCUM(value), COALESCE(attr_def.joiner,' ')) INTO attr_value
1255                       FROM  (SELECT * FROM metabib.full_rec ORDER BY tag, subfield) AS x
1256                       WHERE record = NEW.id
1257                             AND tag LIKE attr_def.tag
1258                             AND CASE
1259                                 WHEN attr_def.sf_list IS NOT NULL 
1260                                     THEN POSITION(subfield IN attr_def.sf_list) > 0
1261                                 ELSE TRUE
1262                                 END
1263                       GROUP BY tag
1264                       ORDER BY tag
1265                       LIMIT 1;
1266
1267                 ELSIF attr_def.fixed_field IS NOT NULL THEN -- a named fixed field, see config.marc21_ff_pos_map.fixed_field
1268                     attr_value := biblio.marc21_extract_fixed_field(NEW.id, attr_def.fixed_field);
1269
1270                 ELSIF attr_def.xpath IS NOT NULL THEN -- and xpath expression
1271
1272                     SELECT INTO xfrm * FROM config.xml_transform WHERE name = attr_def.format;
1273             
1274                     -- See if we can skip the XSLT ... it's expensive
1275                     IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
1276                         -- Can't skip the transform
1277                         IF xfrm.xslt <> '---' THEN
1278                             transformed_xml := oils_xslt_process(NEW.marc,xfrm.xslt);
1279                         ELSE
1280                             transformed_xml := NEW.marc;
1281                         END IF;
1282             
1283                         prev_xfrm := xfrm.name;
1284                     END IF;
1285
1286                     IF xfrm.name IS NULL THEN
1287                         -- just grab the marcxml (empty) transform
1288                         SELECT INTO xfrm * FROM config.xml_transform WHERE xslt = '---' LIMIT 1;
1289                         prev_xfrm := xfrm.name;
1290                     END IF;
1291
1292                     attr_value := oils_xpath_string(attr_def.xpath, transformed_xml, COALESCE(attr_def.joiner,' '), ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]);
1293
1294                 ELSIF attr_def.phys_char_sf IS NOT NULL THEN -- a named Physical Characteristic, see config.marc21_physical_characteristic_*_map
1295                     SELECT  m.value INTO attr_value
1296                       FROM  biblio.marc21_physical_characteristics(NEW.id) v
1297                             JOIN config.marc21_physical_characteristic_value_map m ON (m.id = v.value)
1298                       WHERE v.subfield = attr_def.phys_char_sf
1299                       LIMIT 1; -- Just in case ...
1300
1301                 END IF;
1302
1303                 -- apply index normalizers to attr_value
1304                 FOR normalizer IN
1305                     SELECT  n.func AS func,
1306                             n.param_count AS param_count,
1307                             m.params AS params
1308                       FROM  config.index_normalizer n
1309                             JOIN config.record_attr_index_norm_map m ON (m.norm = n.id)
1310                       WHERE attr = attr_def.name
1311                       ORDER BY m.pos LOOP
1312                         EXECUTE 'SELECT ' || normalizer.func || '(' ||
1313                             COALESCE( quote_literal( attr_value ), 'NULL' ) ||
1314                             CASE
1315                                 WHEN normalizer.param_count > 0
1316                                     THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
1317                                     ELSE ''
1318                                 END ||
1319                             ')' INTO attr_value;
1320         
1321                 END LOOP;
1322
1323                 -- Add the new value to the hstore
1324                 new_attrs := new_attrs || hstore( attr_def.name, attr_value );
1325
1326             END LOOP;
1327
1328             IF TG_OP = 'INSERT' OR OLD.deleted THEN -- initial insert OR revivication
1329                 DELETE FROM metabib.record_attr WHERE id = NEW.id;
1330                 INSERT INTO metabib.record_attr (id, attrs) VALUES (NEW.id, new_attrs);
1331             ELSE
1332                 UPDATE metabib.record_attr SET attrs = new_attrs WHERE id = NEW.id;
1333             END IF;
1334
1335         END IF;
1336     END IF;
1337
1338     -- Gather and insert the field entry data
1339     PERFORM metabib.reingest_metabib_field_entries(NEW.id);
1340
1341     -- Located URI magic
1342     IF TG_OP = 'INSERT' THEN
1343         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_located_uri' AND enabled;
1344         IF NOT FOUND THEN
1345             PERFORM biblio.extract_located_uris( NEW.id, NEW.marc, NEW.editor );
1346         END IF;
1347     ELSE
1348         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_located_uri' AND enabled;
1349         IF NOT FOUND THEN
1350             PERFORM biblio.extract_located_uris( NEW.id, NEW.marc, NEW.editor );
1351         END IF;
1352     END IF;
1353
1354     -- (re)map metarecord-bib linking
1355     IF TG_OP = 'INSERT' THEN -- if not deleted and performing an insert, check for the flag
1356         PERFORM * FROM config.internal_flag WHERE name = 'ingest.metarecord_mapping.skip_on_insert' AND enabled;
1357         IF NOT FOUND THEN
1358             PERFORM metabib.remap_metarecord_for_bib( NEW.id, NEW.fingerprint );
1359         END IF;
1360     ELSE -- we're doing an update, and we're not deleted, remap
1361         PERFORM * FROM config.internal_flag WHERE name = 'ingest.metarecord_mapping.skip_on_update' AND enabled;
1362         IF NOT FOUND THEN
1363             PERFORM metabib.remap_metarecord_for_bib( NEW.id, NEW.fingerprint );
1364         END IF;
1365     END IF;
1366
1367     RETURN NEW;
1368 END;
1369 $func$ LANGUAGE PLPGSQL;
1370
1371 CREATE OR REPLACE FUNCTION metabib.browse_normalize(facet_text TEXT, mapped_field INT) RETURNS TEXT AS $$
1372 DECLARE
1373     normalizer  RECORD;
1374 BEGIN
1375
1376     FOR normalizer IN
1377         SELECT  n.func AS func,
1378                 n.param_count AS param_count,
1379                 m.params AS params
1380           FROM  config.index_normalizer n
1381                 JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
1382           WHERE m.field = mapped_field AND m.pos < 0
1383           ORDER BY m.pos LOOP
1384
1385             EXECUTE 'SELECT ' || normalizer.func || '(' ||
1386                 quote_literal( facet_text ) ||
1387                 CASE
1388                     WHEN normalizer.param_count > 0
1389                         THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
1390                         ELSE ''
1391                     END ||
1392                 ')' INTO facet_text;
1393
1394     END LOOP;
1395
1396     RETURN facet_text;
1397 END;
1398
1399 $$ LANGUAGE PLPGSQL;
1400
1401
1402 -- This mimics a specific part of QueryParser, turning the first part of a
1403 -- classed search (search_class) into a set of classes and possibly fields.
1404 -- search_class might look like "author" or "title|proper" or "ti|uniform"
1405 -- or "au" or "au|corporate|personal" or anything like that, where the first
1406 -- element of the list you get by separating on the "|" character is either
1407 -- a registered class (config.metabib_class) or an alias
1408 -- (config.metabib_search_alias), and the rest of any such elements are
1409 -- fields (config.metabib_field).
1410 CREATE OR REPLACE
1411     FUNCTION metabib.search_class_to_registered_components(search_class TEXT)
1412     RETURNS SETOF RECORD AS $func$
1413 DECLARE
1414     search_parts        TEXT[];
1415     field_name          TEXT;
1416     search_part_count   INTEGER;
1417     rec                 RECORD;
1418     registered_class    config.metabib_class%ROWTYPE;
1419     registered_alias    config.metabib_search_alias%ROWTYPE;
1420     registered_field    config.metabib_field%ROWTYPE;
1421 BEGIN
1422     search_parts := REGEXP_SPLIT_TO_ARRAY(search_class, E'\\|');
1423
1424     search_part_count := ARRAY_LENGTH(search_parts, 1);
1425     IF search_part_count = 0 THEN
1426         RETURN;
1427     ELSE
1428         SELECT INTO registered_class
1429             * FROM config.metabib_class WHERE name = search_parts[1];
1430         IF FOUND THEN
1431             IF search_part_count < 2 THEN   -- all fields
1432                 rec := (registered_class.name, NULL::INTEGER);
1433                 RETURN NEXT rec;
1434                 RETURN; -- done
1435             END IF;
1436             FOR field_name IN SELECT *
1437                 FROM UNNEST(search_parts[2:search_part_count]) LOOP
1438                 SELECT INTO registered_field
1439                     * FROM config.metabib_field
1440                     WHERE name = field_name AND
1441                         field_class = registered_class.name;
1442                 IF FOUND THEN
1443                     rec := (registered_class.name, registered_field.id);
1444                     RETURN NEXT rec;
1445                 END IF;
1446             END LOOP;
1447         ELSE
1448             -- maybe we have an alias?
1449             SELECT INTO registered_alias
1450                 * FROM config.metabib_search_alias WHERE alias=search_parts[1];
1451             IF NOT FOUND THEN
1452                 RETURN;
1453             ELSE
1454                 IF search_part_count < 2 THEN   -- return w/e the alias says
1455                     rec := (
1456                         registered_alias.field_class, registered_alias.field
1457                     );
1458                     RETURN NEXT rec;
1459                     RETURN; -- done
1460                 ELSE
1461                     FOR field_name IN SELECT *
1462                         FROM UNNEST(search_parts[2:search_part_count]) LOOP
1463                         SELECT INTO registered_field
1464                             * FROM config.metabib_field
1465                             WHERE name = field_name AND
1466                                 field_class = registered_alias.field_class;
1467                         IF FOUND THEN
1468                             rec := (
1469                                 registered_alias.field_class,
1470                                 registered_field.id
1471                             );
1472                             RETURN NEXT rec;
1473                         END IF;
1474                     END LOOP;
1475                 END IF;
1476             END IF;
1477         END IF;
1478     END IF;
1479 END;
1480 $func$ LANGUAGE PLPGSQL ROWS 1;
1481
1482
1483 -- Given a string such as a user might type into a search box, prepare
1484 -- two changed variants for TO_TSQUERY(). See
1485 -- http://www.postgresql.org/docs/9.0/static/textsearch-controls.html
1486 -- The first variant is normalized to match indexed documents regardless
1487 -- of diacritics.  The second variant keeps its diacritics for proper
1488 -- highlighting via TS_HEADLINE().
1489 CREATE OR REPLACE
1490     FUNCTION metabib.autosuggest_prepare_tsquery(orig TEXT) RETURNS TEXT[] AS
1491 $$
1492 DECLARE
1493     orig_ended_in_space     BOOLEAN;
1494     result                  RECORD;
1495     plain                   TEXT;
1496     normalized              TEXT;
1497 BEGIN
1498     orig_ended_in_space := orig ~ E'\\s$';
1499
1500     orig := ARRAY_TO_STRING(
1501         evergreen.regexp_split_to_array(orig, E'\\W+'), ' '
1502     );
1503
1504     normalized := public.search_normalize(orig); -- also trim()s
1505     plain := trim(orig);
1506
1507     IF NOT orig_ended_in_space THEN
1508         plain := plain || ':*';
1509         normalized := normalized || ':*';
1510     END IF;
1511
1512     plain := ARRAY_TO_STRING(
1513         evergreen.regexp_split_to_array(plain, E'\\s+'), ' & '
1514     );
1515     normalized := ARRAY_TO_STRING(
1516         evergreen.regexp_split_to_array(normalized, E'\\s+'), ' & '
1517     );
1518
1519     RETURN ARRAY[normalized, plain];
1520 END;
1521 $$ LANGUAGE PLPGSQL;
1522
1523
1524 CREATE OR REPLACE
1525     FUNCTION metabib.suggest_browse_entries(
1526         raw_query_text  TEXT,   -- actually typed by humans at the UI level
1527         search_class    TEXT,   -- 'alias' or 'class' or 'class|field..', etc
1528         headline_opts   TEXT,   -- markup options for ts_headline()
1529         visibility_org  INTEGER,-- null if you don't want opac visibility test
1530         query_limit     INTEGER,-- use in LIMIT clause of interal query
1531         normalization   INTEGER -- argument to TS_RANK_CD()
1532     ) RETURNS TABLE (
1533         value                   TEXT,   -- plain
1534         field                   INTEGER,
1535         buoyant_and_class_match BOOL,
1536         field_match             BOOL,
1537         field_weight            INTEGER,
1538         rank                    REAL,
1539         buoyant                 BOOL,
1540         match                   TEXT    -- marked up
1541     ) AS $func$
1542 DECLARE
1543     prepared_query_texts    TEXT[];
1544     query                   TSQUERY;
1545     plain_query             TSQUERY;
1546     opac_visibility_join    TEXT;
1547     search_class_join       TEXT;
1548     r_fields                RECORD;
1549 BEGIN
1550     prepared_query_texts := metabib.autosuggest_prepare_tsquery(raw_query_text);
1551
1552     query := TO_TSQUERY('keyword', prepared_query_texts[1]);
1553     plain_query := TO_TSQUERY('keyword', prepared_query_texts[2]);
1554
1555     visibility_org := NULLIF(visibility_org,-1);
1556     IF visibility_org IS NOT NULL THEN
1557         opac_visibility_join := '
1558     JOIN asset.opac_visible_copies aovc ON (
1559         aovc.record = x.source AND
1560         aovc.circ_lib IN (SELECT id FROM actor.org_unit_descendants($4))
1561     )';
1562     ELSE
1563         opac_visibility_join := '';
1564     END IF;
1565
1566     -- The following determines whether we only provide suggestsons matching
1567     -- the user's selected search_class, or whether we show other suggestions
1568     -- too. The reason for MIN() is that for search_classes like
1569     -- 'title|proper|uniform' you would otherwise get multiple rows.  The
1570     -- implication is that if title as a class doesn't have restrict,
1571     -- nor does the proper field, but the uniform field does, you're going
1572     -- to get 'false' for your overall evaluation of 'should we restrict?'
1573     -- To invert that, change from MIN() to MAX().
1574
1575     SELECT
1576         INTO r_fields
1577             MIN(cmc.restrict::INT) AS restrict_class,
1578             MIN(cmf.restrict::INT) AS restrict_field
1579         FROM metabib.search_class_to_registered_components(search_class)
1580             AS _registered (field_class TEXT, field INT)
1581         JOIN
1582             config.metabib_class cmc ON (cmc.name = _registered.field_class)
1583         LEFT JOIN
1584             config.metabib_field cmf ON (cmf.id = _registered.field);
1585
1586     -- evaluate 'should we restrict?'
1587     IF r_fields.restrict_field::BOOL OR r_fields.restrict_class::BOOL THEN
1588         search_class_join := '
1589     JOIN
1590         metabib.search_class_to_registered_components($2)
1591         AS _registered (field_class TEXT, field INT) ON (
1592             (_registered.field IS NULL AND
1593                 _registered.field_class = cmf.field_class) OR
1594             (_registered.field = cmf.id)
1595         )
1596     ';
1597     ELSE
1598         search_class_join := '
1599     LEFT JOIN
1600         metabib.search_class_to_registered_components($2)
1601         AS _registered (field_class TEXT, field INT) ON (
1602             _registered.field_class = cmc.name
1603         )
1604     ';
1605     END IF;
1606
1607     RETURN QUERY EXECUTE '
1608 SELECT  DISTINCT
1609         x.value,
1610         x.id,
1611         x.push,
1612         x.restrict,
1613         x.weight,
1614         x.ts_rank_cd,
1615         x.buoyant,
1616         TS_HEADLINE(value, $7, $3)
1617   FROM  (SELECT DISTINCT
1618                 mbe.value,
1619                 cmf.id,
1620                 cmc.buoyant AND _registered.field_class IS NOT NULL AS push,
1621                 _registered.field = cmf.id AS restrict,
1622                 cmf.weight,
1623                 TS_RANK_CD(mbe.index_vector, $1, $6),
1624                 cmc.buoyant,
1625                 mbedm.source
1626           FROM  metabib.browse_entry_def_map mbedm
1627                 JOIN (SELECT * FROM metabib.browse_entry WHERE index_vector @@ $1 LIMIT 10000) mbe ON (mbe.id = mbedm.entry)
1628                 JOIN config.metabib_field cmf ON (cmf.id = mbedm.def)
1629                 JOIN config.metabib_class cmc ON (cmf.field_class = cmc.name)
1630                 '  || search_class_join || '
1631           ORDER BY 3 DESC, 4 DESC NULLS LAST, 5 DESC, 6 DESC, 7 DESC, 1 ASC
1632           LIMIT 1000) AS x
1633         ' || opac_visibility_join || '
1634   ORDER BY 3 DESC, 4 DESC NULLS LAST, 5 DESC, 6 DESC, 7 DESC, 1 ASC
1635   LIMIT $5
1636 '   -- sic, repeat the order by clause in the outer select too
1637     USING
1638         query, search_class, headline_opts,
1639         visibility_org, query_limit, normalization, plain_query
1640         ;
1641
1642     -- sort order:
1643     --  buoyant AND chosen class = match class
1644     --  chosen field = match field
1645     --  field weight
1646     --  rank
1647     --  buoyancy
1648     --  value itself
1649
1650 END;
1651 $func$ LANGUAGE PLPGSQL;
1652
1653 CREATE OR REPLACE FUNCTION public.oils_tsearch2 () RETURNS TRIGGER AS $$
1654 DECLARE
1655     normalizer      RECORD;
1656     value           TEXT := '';
1657     temp_vector     TEXT := '';
1658     ts_rec          RECORD;
1659     cur_weight      "char";
1660 BEGIN
1661
1662     value := NEW.value;
1663     NEW.index_vector = ''::tsvector;
1664
1665     IF TG_TABLE_NAME::TEXT ~ 'field_entry$' THEN
1666         FOR normalizer IN
1667             SELECT  n.func AS func,
1668                     n.param_count AS param_count,
1669                     m.params AS params
1670               FROM  config.index_normalizer n
1671                     JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
1672               WHERE field = NEW.field AND m.pos < 0
1673               ORDER BY m.pos LOOP
1674                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
1675                     quote_literal( value ) ||
1676                     CASE
1677                         WHEN normalizer.param_count > 0
1678                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
1679                             ELSE ''
1680                         END ||
1681                     ')' INTO value;
1682
1683         END LOOP;
1684
1685         NEW.value = value;
1686
1687         FOR normalizer IN
1688             SELECT  n.func AS func,
1689                     n.param_count AS param_count,
1690                     m.params AS params
1691               FROM  config.index_normalizer n
1692                     JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
1693               WHERE field = NEW.field AND m.pos >= 0
1694               ORDER BY m.pos LOOP
1695                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
1696                     quote_literal( value ) ||
1697                     CASE
1698                         WHEN normalizer.param_count > 0
1699                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
1700                             ELSE ''
1701                         END ||
1702                     ')' INTO value;
1703
1704         END LOOP;
1705    END IF;
1706
1707     IF TG_TABLE_NAME::TEXT ~ 'browse_entry$' THEN
1708         value :=  ARRAY_TO_STRING(
1709             evergreen.regexp_split_to_array(value, E'\\W+'), ' '
1710         );
1711         value := public.search_normalize(value);
1712         NEW.index_vector = to_tsvector(TG_ARGV[0]::regconfig, value);
1713     ELSIF TG_TABLE_NAME::TEXT ~ 'field_entry$' THEN
1714         FOR ts_rec IN
1715             SELECT ts_config, index_weight
1716             FROM config.metabib_class_ts_map
1717             WHERE field_class = TG_ARGV[0]
1718                 AND index_lang IS NULL OR EXISTS (SELECT 1 FROM metabib.record_attr WHERE id = NEW.source AND index_lang IN(attrs->'item_lang',attrs->'language'))
1719                 AND always OR NOT EXISTS (SELECT 1 FROM config.metabib_field_ts_map WHERE metabib_field = NEW.field)
1720             UNION
1721             SELECT ts_config, index_weight
1722             FROM config.metabib_field_ts_map
1723             WHERE metabib_field = NEW.field
1724                AND index_lang IS NULL OR EXISTS (SELECT 1 FROM metabib.record_attr WHERE id = NEW.source AND index_lang IN(attrs->'item_lang',attrs->'language'))
1725             ORDER BY index_weight ASC
1726         LOOP
1727             IF cur_weight IS NOT NULL AND cur_weight != ts_rec.index_weight THEN
1728                 NEW.index_vector = NEW.index_vector || setweight(temp_vector::tsvector,cur_weight);
1729                 temp_vector = '';
1730             END IF;
1731             cur_weight = ts_rec.index_weight;
1732             SELECT INTO temp_vector temp_vector || ' ' || to_tsvector(ts_rec.ts_config::regconfig, value)::TEXT;
1733         END LOOP;
1734         NEW.index_vector = NEW.index_vector || setweight(temp_vector::tsvector,cur_weight);
1735     ELSE
1736         NEW.index_vector = to_tsvector(TG_ARGV[0]::regconfig, value);
1737     END IF;
1738
1739     RETURN NEW;
1740 END;
1741 $$ LANGUAGE PLPGSQL;
1742
1743 COMMIT;