]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/030.schema.metabib.sql
4e1d445fc315481e16d88af68bb2df31f78e6119
[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,
189     index_vector tsvector,
190     sort_value  TEXT NOT NULL,
191     UNIQUE(sort_value, value)
192 );
193
194
195 CREATE INDEX browse_entry_sort_value_idx
196     ON metabib.browse_entry USING BTREE (sort_value);
197
198 CREATE INDEX metabib_browse_entry_index_vector_idx ON metabib.browse_entry USING GIN (index_vector);
199 CREATE TRIGGER metabib_browse_entry_fti_trigger
200     BEFORE INSERT OR UPDATE ON metabib.browse_entry
201     FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('keyword');
202
203
204 CREATE TABLE metabib.browse_entry_def_map (
205     id BIGSERIAL PRIMARY KEY,
206     entry BIGINT REFERENCES metabib.browse_entry (id),
207     def INT REFERENCES config.metabib_field (id) ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
208     source BIGINT REFERENCES biblio.record_entry (id),
209     authority BIGINT REFERENCES authority.record_entry (id) ON DELETE SET NULL
210 );
211 CREATE INDEX browse_entry_def_map_def_idx ON metabib.browse_entry_def_map (def);
212 CREATE INDEX browse_entry_def_map_entry_idx ON metabib.browse_entry_def_map (entry);
213 CREATE INDEX browse_entry_def_map_source_idx ON metabib.browse_entry_def_map (source);
214
215 CREATE TABLE metabib.browse_entry_simple_heading_map (
216     id BIGSERIAL PRIMARY KEY,
217     entry BIGINT REFERENCES metabib.browse_entry (id),
218     simple_heading BIGINT REFERENCES authority.simple_heading (id) ON DELETE CASCADE
219 );
220 CREATE INDEX browse_entry_sh_map_entry_idx ON metabib.browse_entry_simple_heading_map (entry);
221 CREATE INDEX browse_entry_sh_map_sh_idx ON metabib.browse_entry_simple_heading_map (simple_heading);
222
223 CREATE OR REPLACE FUNCTION metabib.facet_normalize_trigger () RETURNS TRIGGER AS $$
224 DECLARE
225     normalizer  RECORD;
226     facet_text  TEXT;
227 BEGIN
228     facet_text := NEW.value;
229
230     FOR normalizer IN
231         SELECT  n.func AS func,
232                 n.param_count AS param_count,
233                 m.params AS params
234           FROM  config.index_normalizer n
235                 JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
236           WHERE m.field = NEW.field AND m.pos < 0
237           ORDER BY m.pos LOOP
238
239             EXECUTE 'SELECT ' || normalizer.func || '(' ||
240                 quote_literal( facet_text ) ||
241                 CASE
242                     WHEN normalizer.param_count > 0
243                         THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
244                         ELSE ''
245                     END ||
246                 ')' INTO facet_text;
247
248     END LOOP;
249
250     NEW.value = facet_text;
251
252     RETURN NEW;
253 END;
254 $$ LANGUAGE PLPGSQL;
255
256 CREATE TRIGGER facet_normalize_tgr
257         BEFORE UPDATE OR INSERT ON metabib.facet_entry
258         FOR EACH ROW EXECUTE PROCEDURE metabib.facet_normalize_trigger();
259
260 CREATE OR REPLACE FUNCTION evergreen.facet_force_nfc() RETURNS TRIGGER AS $$
261 BEGIN
262     NEW.value := force_unicode_normal_form(NEW.value,'NFC');
263     RETURN NEW;
264 END;
265 $$ LANGUAGE PLPGSQL;
266
267 CREATE TRIGGER facet_force_nfc_tgr
268         BEFORE UPDATE OR INSERT ON metabib.facet_entry
269         FOR EACH ROW EXECUTE PROCEDURE evergreen.facet_force_nfc();
270
271 CREATE TABLE metabib.record_attr (
272         id              BIGINT  PRIMARY KEY REFERENCES biblio.record_entry (id) ON DELETE CASCADE,
273         attrs   HSTORE  NOT NULL DEFAULT ''::HSTORE
274 );
275 CREATE INDEX metabib_svf_attrs_idx ON metabib.record_attr USING GIST (attrs);
276 CREATE INDEX metabib_svf_date1_idx ON metabib.record_attr ((attrs->'date1'));
277 CREATE INDEX metabib_svf_dates_idx ON metabib.record_attr ((attrs->'date1'),(attrs->'date2'));
278
279 -- Back-compat view ... we're moving to an HSTORE world
280 CREATE TYPE metabib.rec_desc_type AS (
281     item_type       TEXT,
282     item_form       TEXT,
283     bib_level       TEXT,
284     control_type    TEXT,
285     char_encoding   TEXT,
286     enc_level       TEXT,
287     audience        TEXT,
288     lit_form        TEXT,
289     type_mat        TEXT,
290     cat_form        TEXT,
291     pub_status      TEXT,
292     item_lang       TEXT,
293     vr_format       TEXT,
294     date1           TEXT,
295     date2           TEXT
296 );
297
298 CREATE VIEW metabib.rec_descriptor AS
299     SELECT  id,
300             id AS record,
301             (populate_record(NULL::metabib.rec_desc_type, attrs)).*
302       FROM  metabib.record_attr;
303
304 -- Use a sequence that matches previous version, for easier upgrading.
305 CREATE SEQUENCE metabib.full_rec_id_seq;
306
307 CREATE TABLE metabib.real_full_rec (
308         id                  BIGINT      NOT NULL DEFAULT NEXTVAL('metabib.full_rec_id_seq'::REGCLASS),
309         record          BIGINT          NOT NULL,
310         tag             CHAR(3)         NOT NULL,
311         ind1            TEXT,
312         ind2            TEXT,
313         subfield        TEXT,
314         value           TEXT            NOT NULL,
315         index_vector    tsvector        NOT NULL
316 );
317 ALTER TABLE metabib.real_full_rec ADD PRIMARY KEY (id);
318
319 CREATE INDEX metabib_full_rec_tag_subfield_idx ON metabib.real_full_rec (tag,subfield);
320 CREATE INDEX metabib_full_rec_value_idx ON metabib.real_full_rec (substring(value,1,1024));
321 /* Enable LIKE to use an index for database clusters with locales other than C or POSIX */
322 CREATE INDEX metabib_full_rec_value_tpo_index ON metabib.real_full_rec (substring(value,1,1024) text_pattern_ops);
323 CREATE INDEX metabib_full_rec_record_idx ON metabib.real_full_rec (record);
324 CREATE INDEX metabib_full_rec_index_vector_idx ON metabib.real_full_rec USING GIST (index_vector);
325 CREATE INDEX metabib_full_rec_isxn_caseless_idx
326     ON metabib.real_full_rec (LOWER(value))
327     WHERE tag IN ('020', '022', '024');
328 -- This next index might fully supplant the one above, but leaving both for now.
329 -- (they are not too large)
330 -- The reason we need this index is to ensure that the query parser always
331 -- prefers this index over the simpler tag/subfield index, as this greatly
332 -- increases Vandelay overlay speed for these identifiers, especially when
333 -- a record has many of these fields (around > 4-6 seems like the cutoff
334 -- on at least one PG9.1 system)
335 -- A similar index could be added for other fields (e.g. 010), but one should
336 -- leave out the LOWER() in all other cases.
337 -- TODO: verify whether we can discard the non tag/subfield/substring version
338 -- above (metabib_full_rec_isxn_caseless_idx)
339 CREATE INDEX metabib_full_rec_02x_tag_subfield_lower_substring
340     ON metabib.real_full_rec (tag, subfield, LOWER(substring(value, 1, 1024)))
341     WHERE tag IN ('020', '022', '024');
342
343
344 CREATE TRIGGER metabib_full_rec_fti_trigger
345         BEFORE UPDATE OR INSERT ON metabib.real_full_rec
346         FOR EACH ROW EXECUTE PROCEDURE oils_tsearch2('default');
347
348 CREATE OR REPLACE VIEW metabib.full_rec AS
349     SELECT  id,
350             record,
351             tag,
352             ind1,
353             ind2,
354             subfield,
355             SUBSTRING(value,1,1024) AS value,
356             index_vector
357       FROM  metabib.real_full_rec;
358
359 CREATE OR REPLACE RULE metabib_full_rec_insert_rule
360     AS ON INSERT TO metabib.full_rec
361     DO INSTEAD
362     INSERT INTO metabib.real_full_rec VALUES (
363         COALESCE(NEW.id, NEXTVAL('metabib.full_rec_id_seq'::REGCLASS)),
364         NEW.record,
365         NEW.tag,
366         NEW.ind1,
367         NEW.ind2,
368         NEW.subfield,
369         NEW.value,
370         NEW.index_vector
371     );
372
373 CREATE OR REPLACE RULE metabib_full_rec_update_rule
374     AS ON UPDATE TO metabib.full_rec
375     DO INSTEAD
376     UPDATE  metabib.real_full_rec SET
377         id = NEW.id,
378         record = NEW.record,
379         tag = NEW.tag,
380         ind1 = NEW.ind1,
381         ind2 = NEW.ind2,
382         subfield = NEW.subfield,
383         value = NEW.value,
384         index_vector = NEW.index_vector
385       WHERE id = OLD.id;
386
387 CREATE OR REPLACE RULE metabib_full_rec_delete_rule
388     AS ON DELETE TO metabib.full_rec
389     DO INSTEAD
390     DELETE FROM metabib.real_full_rec WHERE id = OLD.id;
391
392 CREATE TABLE metabib.metarecord_source_map (
393         id              BIGSERIAL       PRIMARY KEY,
394         metarecord      BIGINT          NOT NULL,
395         source          BIGINT          NOT NULL
396 );
397 CREATE INDEX metabib_metarecord_source_map_metarecord_idx ON metabib.metarecord_source_map (metarecord);
398 CREATE INDEX metabib_metarecord_source_map_source_record_idx ON metabib.metarecord_source_map (source);
399
400 CREATE TYPE metabib.field_entry_template AS (
401     field_class         TEXT,
402     field               INT,
403     facet_field         BOOL,
404     search_field        BOOL,
405     browse_field        BOOL,
406     source              BIGINT,
407     value               TEXT,
408     authority           BIGINT,
409     sort_value          TEXT
410 );
411
412
413 CREATE OR REPLACE FUNCTION biblio.extract_metabib_field_entry ( rid BIGINT, default_joiner TEXT ) RETURNS SETOF metabib.field_entry_template AS $func$
414 DECLARE
415     bib     biblio.record_entry%ROWTYPE;
416     idx     config.metabib_field%ROWTYPE;
417     xfrm        config.xml_transform%ROWTYPE;
418     prev_xfrm   TEXT;
419     transformed_xml TEXT;
420     xml_node    TEXT;
421     xml_node_list   TEXT[];
422     facet_text  TEXT;
423     browse_text TEXT;
424     sort_value  TEXT;
425     raw_text    TEXT;
426     curr_text   TEXT;
427     joiner      TEXT := default_joiner; -- XXX will index defs supply a joiner?
428     authority_text TEXT;
429     authority_link BIGINT;
430     output_row  metabib.field_entry_template%ROWTYPE;
431 BEGIN
432
433     -- Start out with no field-use bools set
434     output_row.browse_field = FALSE;
435     output_row.facet_field = FALSE;
436     output_row.search_field = FALSE;
437
438     -- Get the record
439     SELECT INTO bib * FROM biblio.record_entry WHERE id = rid;
440
441     -- Loop over the indexing entries
442     FOR idx IN SELECT * FROM config.metabib_field ORDER BY format LOOP
443
444         joiner := COALESCE(idx.joiner, default_joiner);
445
446         SELECT INTO xfrm * from config.xml_transform WHERE name = idx.format;
447
448         -- See if we can skip the XSLT ... it's expensive
449         IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
450             -- Can't skip the transform
451             IF xfrm.xslt <> '---' THEN
452                 transformed_xml := oils_xslt_process(bib.marc,xfrm.xslt);
453             ELSE
454                 transformed_xml := bib.marc;
455             END IF;
456
457             prev_xfrm := xfrm.name;
458         END IF;
459
460         xml_node_list := oils_xpath( idx.xpath, transformed_xml, ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]] );
461
462         raw_text := NULL;
463         FOR xml_node IN SELECT x FROM unnest(xml_node_list) AS x LOOP
464             CONTINUE WHEN xml_node !~ E'^\\s*<';
465
466             -- XXX much of this should be moved into oils_xpath_string...
467             curr_text := ARRAY_TO_STRING(evergreen.array_remove_item_by_value(evergreen.array_remove_item_by_value(
468                 oils_xpath( '//text()',
469                     REGEXP_REPLACE(
470                         REGEXP_REPLACE( -- This escapes all &s not followed by "amp;".  Data ise returned from oils_xpath (above) in UTF-8, not entity encoded
471                             REGEXP_REPLACE( -- This escapes embeded <s
472                                 xml_node,
473                                 $re$(>[^<]+)(<)([^>]+<)$re$,
474                                 E'\\1&lt;\\3',
475                                 'g'
476                             ),
477                             '&(?!amp;)',
478                             '&amp;',
479                             'g'
480                         ),
481                         E'\\s+',
482                         ' ',
483                         'g'
484                     )
485                 ), ' '), ''),
486                 joiner
487             );
488
489             CONTINUE WHEN curr_text IS NULL OR curr_text = '';
490
491             IF raw_text IS NOT NULL THEN
492                 raw_text := raw_text || joiner;
493             END IF;
494
495             raw_text := COALESCE(raw_text,'') || curr_text;
496
497             -- autosuggest/metabib.browse_entry
498             IF idx.browse_field THEN
499
500                 IF idx.browse_xpath IS NOT NULL AND idx.browse_xpath <> '' THEN
501                     browse_text := oils_xpath_string( idx.browse_xpath, xml_node, joiner, ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]] );
502                 ELSE
503                     browse_text := curr_text;
504                 END IF;
505
506                 IF idx.browse_sort_xpath IS NOT NULL AND
507                     idx.browse_sort_xpath <> '' THEN
508
509                     sort_value := oils_xpath_string(
510                         idx.browse_sort_xpath, xml_node, joiner,
511                         ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]
512                     );
513                 ELSE
514                     sort_value := browse_text;
515                 END IF;
516
517                 output_row.field_class = idx.field_class;
518                 output_row.field = idx.id;
519                 output_row.source = rid;
520                 output_row.value = BTRIM(REGEXP_REPLACE(browse_text, E'\\s+', ' ', 'g'));
521                 output_row.sort_value :=
522                     public.naco_normalize(sort_value);
523
524                 output_row.authority := NULL;
525
526                 IF idx.authority_xpath IS NOT NULL AND idx.authority_xpath <> '' THEN
527                     authority_text := oils_xpath_string(
528                         idx.authority_xpath, xml_node, joiner,
529                         ARRAY[
530                             ARRAY[xfrm.prefix, xfrm.namespace_uri],
531                             ARRAY['xlink','http://www.w3.org/1999/xlink']
532                         ]
533                     );
534
535                     IF authority_text ~ '^\d+$' THEN
536                         authority_link := authority_text::BIGINT;
537                         PERFORM * FROM authority.record_entry WHERE id = authority_link;
538                         IF FOUND THEN
539                             output_row.authority := authority_link;
540                         END IF;
541                     END IF;
542
543                 END IF;
544
545                 output_row.browse_field = TRUE;
546                 -- Returning browse rows with search_field = true for search+browse
547                 -- configs allows us to retain granularity of being able to search
548                 -- browse fields with "starts with" type operators (for example, for
549                 -- titles of songs in music albums)
550                 IF idx.search_field THEN
551                     output_row.search_field = TRUE;
552                 END IF;
553                 RETURN NEXT output_row;
554                 output_row.browse_field = FALSE;
555                 output_row.search_field = FALSE;
556                 output_row.sort_value := NULL;
557             END IF;
558
559             -- insert raw node text for faceting
560             IF idx.facet_field THEN
561
562                 IF idx.facet_xpath IS NOT NULL AND idx.facet_xpath <> '' THEN
563                     facet_text := oils_xpath_string( idx.facet_xpath, xml_node, joiner, ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]] );
564                 ELSE
565                     facet_text := curr_text;
566                 END IF;
567
568                 output_row.field_class = idx.field_class;
569                 output_row.field = -1 * idx.id;
570                 output_row.source = rid;
571                 output_row.value = BTRIM(REGEXP_REPLACE(facet_text, E'\\s+', ' ', 'g'));
572
573                 output_row.facet_field = TRUE;
574                 RETURN NEXT output_row;
575                 output_row.facet_field = FALSE;
576             END IF;
577
578         END LOOP;
579
580         CONTINUE WHEN raw_text IS NULL OR raw_text = '';
581
582         -- insert combined node text for searching
583         IF idx.search_field THEN
584             output_row.field_class = idx.field_class;
585             output_row.field = idx.id;
586             output_row.source = rid;
587             output_row.value = BTRIM(REGEXP_REPLACE(raw_text, E'\\s+', ' ', 'g'));
588
589             output_row.search_field = TRUE;
590             RETURN NEXT output_row;
591             output_row.search_field = FALSE;
592         END IF;
593
594     END LOOP;
595
596 END;
597
598 $func$ LANGUAGE PLPGSQL;
599
600 CREATE OR REPLACE FUNCTION metabib.update_combined_index_vectors(bib_id BIGINT) RETURNS VOID AS $func$
601 BEGIN
602     DELETE FROM metabib.combined_keyword_field_entry WHERE record = bib_id;
603     INSERT INTO metabib.combined_keyword_field_entry(record, metabib_field, index_vector)
604         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
605         FROM metabib.keyword_field_entry WHERE source = bib_id GROUP BY field;
606     INSERT INTO metabib.combined_keyword_field_entry(record, metabib_field, index_vector)
607         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
608         FROM metabib.keyword_field_entry WHERE source = bib_id;
609
610     DELETE FROM metabib.combined_title_field_entry WHERE record = bib_id;
611     INSERT INTO metabib.combined_title_field_entry(record, metabib_field, index_vector)
612         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
613         FROM metabib.title_field_entry WHERE source = bib_id GROUP BY field;
614     INSERT INTO metabib.combined_title_field_entry(record, metabib_field, index_vector)
615         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
616         FROM metabib.title_field_entry WHERE source = bib_id;
617
618     DELETE FROM metabib.combined_author_field_entry WHERE record = bib_id;
619     INSERT INTO metabib.combined_author_field_entry(record, metabib_field, index_vector)
620         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
621         FROM metabib.author_field_entry WHERE source = bib_id GROUP BY field;
622     INSERT INTO metabib.combined_author_field_entry(record, metabib_field, index_vector)
623         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
624         FROM metabib.author_field_entry WHERE source = bib_id;
625
626     DELETE FROM metabib.combined_subject_field_entry WHERE record = bib_id;
627     INSERT INTO metabib.combined_subject_field_entry(record, metabib_field, index_vector)
628         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
629         FROM metabib.subject_field_entry WHERE source = bib_id GROUP BY field;
630     INSERT INTO metabib.combined_subject_field_entry(record, metabib_field, index_vector)
631         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
632         FROM metabib.subject_field_entry WHERE source = bib_id;
633
634     DELETE FROM metabib.combined_series_field_entry WHERE record = bib_id;
635     INSERT INTO metabib.combined_series_field_entry(record, metabib_field, index_vector)
636         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
637         FROM metabib.series_field_entry WHERE source = bib_id GROUP BY field;
638     INSERT INTO metabib.combined_series_field_entry(record, metabib_field, index_vector)
639         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
640         FROM metabib.series_field_entry WHERE source = bib_id;
641
642     DELETE FROM metabib.combined_identifier_field_entry WHERE record = bib_id;
643     INSERT INTO metabib.combined_identifier_field_entry(record, metabib_field, index_vector)
644         SELECT bib_id, field, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
645         FROM metabib.identifier_field_entry WHERE source = bib_id GROUP BY field;
646     INSERT INTO metabib.combined_identifier_field_entry(record, metabib_field, index_vector)
647         SELECT bib_id, NULL, strip(COALESCE(string_agg(index_vector::TEXT,' '),'')::tsvector)
648         FROM metabib.identifier_field_entry WHERE source = bib_id;
649
650 END;
651 $func$ LANGUAGE PLPGSQL;
652
653 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$
654 DECLARE
655     fclass          RECORD;
656     ind_data        metabib.field_entry_template%ROWTYPE;
657     mbe_row         metabib.browse_entry%ROWTYPE;
658     mbe_id          BIGINT;
659     b_skip_facet    BOOL;
660     b_skip_browse   BOOL;
661     b_skip_search   BOOL;
662     value_prepped   TEXT;
663 BEGIN
664
665     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;
666     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;
667     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;
668
669     PERFORM * FROM config.internal_flag WHERE name = 'ingest.assume_inserts_only' AND enabled;
670     IF NOT FOUND THEN
671         IF NOT b_skip_search THEN
672             FOR fclass IN SELECT * FROM config.metabib_class LOOP
673                 -- RAISE NOTICE 'Emptying out %', fclass.name;
674                 EXECUTE $$DELETE FROM metabib.$$ || fclass.name || $$_field_entry WHERE source = $$ || bib_id;
675             END LOOP;
676         END IF;
677         IF NOT b_skip_facet THEN
678             DELETE FROM metabib.facet_entry WHERE source = bib_id;
679         END IF;
680         IF NOT b_skip_browse THEN
681             DELETE FROM metabib.browse_entry_def_map WHERE source = bib_id;
682         END IF;
683     END IF;
684
685     FOR ind_data IN SELECT * FROM biblio.extract_metabib_field_entry( bib_id ) LOOP
686         IF ind_data.field < 0 THEN
687             ind_data.field = -1 * ind_data.field;
688         END IF;
689
690         IF ind_data.facet_field AND NOT b_skip_facet THEN
691             INSERT INTO metabib.facet_entry (field, source, value)
692                 VALUES (ind_data.field, ind_data.source, ind_data.value);
693         END IF;
694
695         IF ind_data.browse_field AND NOT b_skip_browse THEN
696             -- A caveat about this SELECT: this should take care of replacing
697             -- old mbe rows when data changes, but not if normalization (by
698             -- which I mean specifically the output of
699             -- evergreen.oils_tsearch2()) changes.  It may or may not be
700             -- expensive to add a comparison of index_vector to index_vector
701             -- to the WHERE clause below.
702
703             value_prepped := metabib.browse_normalize(ind_data.value, ind_data.field);
704             SELECT INTO mbe_row * FROM metabib.browse_entry
705                 WHERE value = value_prepped AND sort_value = ind_data.sort_value;
706
707             IF FOUND THEN
708                 mbe_id := mbe_row.id;
709             ELSE
710                 INSERT INTO metabib.browse_entry
711                     ( value, sort_value ) VALUES
712                     ( value_prepped, ind_data.sort_value );
713
714                 mbe_id := CURRVAL('metabib.browse_entry_id_seq'::REGCLASS);
715             END IF;
716
717             INSERT INTO metabib.browse_entry_def_map (entry, def, source, authority)
718                 VALUES (mbe_id, ind_data.field, ind_data.source, ind_data.authority);
719         END IF;
720
721         IF ind_data.search_field AND NOT b_skip_search THEN
722             -- Avoid inserting duplicate rows
723             EXECUTE 'SELECT 1 FROM metabib.' || ind_data.field_class ||
724                 '_field_entry WHERE field = $1 AND source = $2 AND value = $3'
725                 INTO mbe_id USING ind_data.field, ind_data.source, ind_data.value;
726                 -- RAISE NOTICE 'Search for an already matching row returned %', mbe_id;
727             IF mbe_id IS NULL THEN
728                 EXECUTE $$
729                 INSERT INTO metabib.$$ || ind_data.field_class || $$_field_entry (field, source, value)
730                     VALUES ($$ ||
731                         quote_literal(ind_data.field) || $$, $$ ||
732                         quote_literal(ind_data.source) || $$, $$ ||
733                         quote_literal(ind_data.value) ||
734                     $$);$$;
735             END IF;
736         END IF;
737
738     END LOOP;
739
740     IF NOT b_skip_search THEN
741         PERFORM metabib.update_combined_index_vectors(bib_id);
742     END IF;
743
744     RETURN;
745 END;
746 $func$ LANGUAGE PLPGSQL;
747
748 -- default to a space joiner
749 CREATE OR REPLACE FUNCTION biblio.extract_metabib_field_entry ( BIGINT ) RETURNS SETOF metabib.field_entry_template AS $func$
750         SELECT * FROM biblio.extract_metabib_field_entry($1, ' ');
751 $func$ LANGUAGE SQL;
752
753 CREATE OR REPLACE FUNCTION authority.flatten_marc ( rid BIGINT ) RETURNS SETOF authority.full_rec AS $func$
754 DECLARE
755         auth    authority.record_entry%ROWTYPE;
756         output  authority.full_rec%ROWTYPE;
757         field   RECORD;
758 BEGIN
759         SELECT INTO auth * FROM authority.record_entry WHERE id = rid;
760
761         FOR field IN SELECT * FROM vandelay.flatten_marc( auth.marc ) LOOP
762                 output.record := rid;
763                 output.ind1 := field.ind1;
764                 output.ind2 := field.ind2;
765                 output.tag := field.tag;
766                 output.subfield := field.subfield;
767                 output.value := field.value;
768
769                 RETURN NEXT output;
770         END LOOP;
771 END;
772 $func$ LANGUAGE PLPGSQL;
773
774 CREATE OR REPLACE FUNCTION biblio.flatten_marc ( rid BIGINT ) RETURNS SETOF metabib.full_rec AS $func$
775 DECLARE
776         bib     biblio.record_entry%ROWTYPE;
777         output  metabib.full_rec%ROWTYPE;
778         field   RECORD;
779 BEGIN
780         SELECT INTO bib * FROM biblio.record_entry WHERE id = rid;
781
782         FOR field IN SELECT * FROM vandelay.flatten_marc( bib.marc ) LOOP
783                 output.record := rid;
784                 output.ind1 := field.ind1;
785                 output.ind2 := field.ind2;
786                 output.tag := field.tag;
787                 output.subfield := field.subfield;
788                 output.value := field.value;
789
790                 RETURN NEXT output;
791         END LOOP;
792 END;
793 $func$ LANGUAGE PLPGSQL;
794
795 CREATE OR REPLACE FUNCTION vandelay.marc21_record_type( marc TEXT ) RETURNS config.marc21_rec_type_map AS $func$
796 DECLARE
797         ldr         TEXT;
798         tval        TEXT;
799         tval_rec    RECORD;
800         bval        TEXT;
801         bval_rec    RECORD;
802     retval      config.marc21_rec_type_map%ROWTYPE;
803 BEGIN
804     ldr := oils_xpath_string( '//*[local-name()="leader"]', marc );
805
806     IF ldr IS NULL OR ldr = '' THEN
807         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
808         RETURN retval;
809     END IF;
810
811     SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
812     SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
813
814
815     tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
816     bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
817
818     -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
819
820     SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
821
822
823     IF retval.code IS NULL THEN
824         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
825     END IF;
826
827     RETURN retval;
828 END;
829 $func$ LANGUAGE PLPGSQL;
830
831 CREATE OR REPLACE FUNCTION biblio.marc21_record_type( rid BIGINT ) RETURNS config.marc21_rec_type_map AS $func$
832     SELECT * FROM vandelay.marc21_record_type( (SELECT marc FROM biblio.record_entry WHERE id = $1) );
833 $func$ LANGUAGE SQL;
834
835 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field( marc TEXT, ff TEXT ) RETURNS TEXT AS $func$
836 DECLARE
837     rtype       TEXT;
838     ff_pos      RECORD;
839     tag_data    RECORD;
840     val         TEXT;
841 BEGIN
842     rtype := (vandelay.marc21_record_type( marc )).code;
843     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
844         IF ff_pos.tag = 'ldr' THEN
845             val := oils_xpath_string('//*[local-name()="leader"]', marc);
846             IF val IS NOT NULL THEN
847                 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
848                 RETURN val;
849             END IF;
850         ELSE
851             FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
852                 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
853                 RETURN val;
854             END LOOP;
855         END IF;
856         val := REPEAT( ff_pos.default_val, ff_pos.length );
857         RETURN val;
858     END LOOP;
859
860     RETURN NULL;
861 END;
862 $func$ LANGUAGE PLPGSQL;
863
864 CREATE OR REPLACE FUNCTION biblio.marc21_extract_fixed_field( rid BIGINT, ff TEXT ) RETURNS TEXT AS $func$
865     SELECT * FROM vandelay.marc21_extract_fixed_field( (SELECT marc FROM biblio.record_entry WHERE id = $1), $2 );
866 $func$ LANGUAGE SQL;
867
868 -- CREATE TYPE biblio.record_ff_map AS (record BIGINT, ff_name TEXT, ff_value TEXT);
869 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_all_fixed_fields( marc TEXT ) RETURNS SETOF biblio.record_ff_map AS $func$
870 DECLARE
871     tag_data    TEXT;
872     rtype       TEXT;
873     ff_pos      RECORD;
874     output      biblio.record_ff_map%ROWTYPE;
875 BEGIN
876     rtype := (vandelay.marc21_record_type( marc )).code;
877
878     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE rec_type = rtype ORDER BY tag DESC LOOP
879         output.ff_name  := ff_pos.fixed_field;
880         output.ff_value := NULL;
881
882         IF ff_pos.tag = 'ldr' THEN
883             output.ff_value := oils_xpath_string('//*[local-name()="leader"]', marc);
884             IF output.ff_value IS NOT NULL THEN
885                 output.ff_value := SUBSTRING( output.ff_value, ff_pos.start_pos + 1, ff_pos.length );
886                 RETURN NEXT output;
887                 output.ff_value := NULL;
888             END IF;
889         ELSE
890             FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
891                 output.ff_value := SUBSTRING( tag_data, ff_pos.start_pos + 1, ff_pos.length );
892                 IF output.ff_value IS NULL THEN output.ff_value := REPEAT( ff_pos.default_val, ff_pos.length ); END IF;
893                 RETURN NEXT output;
894                 output.ff_value := NULL;
895             END LOOP;
896         END IF;
897
898     END LOOP;
899
900     RETURN;
901 END;
902 $func$ LANGUAGE PLPGSQL;
903
904 CREATE OR REPLACE FUNCTION biblio.marc21_extract_all_fixed_fields( rid BIGINT ) RETURNS SETOF biblio.record_ff_map AS $func$
905     SELECT $1 AS record, ff_name, ff_value FROM vandelay.marc21_extract_all_fixed_fields( (SELECT marc FROM biblio.record_entry WHERE id = $1) );
906 $func$ LANGUAGE SQL;
907
908 CREATE OR REPLACE FUNCTION biblio.marc21_physical_characteristics( rid BIGINT ) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
909     SELECT id, $1 AS record, ptype, subfield, value FROM vandelay.marc21_physical_characteristics( (SELECT marc FROM biblio.record_entry WHERE id = $1) );
910 $func$ LANGUAGE SQL;
911
912 CREATE OR REPLACE FUNCTION biblio.extract_quality ( marc TEXT, best_lang TEXT, best_type TEXT ) RETURNS INT AS $func$
913 DECLARE
914     qual        INT;
915     ldr         TEXT;
916     tval        TEXT;
917     tval_rec    RECORD;
918     bval        TEXT;
919     bval_rec    RECORD;
920     type_map    RECORD;
921     ff_pos      RECORD;
922     ff_tag_data TEXT;
923 BEGIN
924
925     IF marc IS NULL OR marc = '' THEN
926         RETURN NULL;
927     END IF;
928
929     -- First, the count of tags
930     qual := ARRAY_UPPER(oils_xpath('*[local-name()="datafield"]', marc), 1);
931
932     -- now go through a bunch of pain to get the record type
933     IF best_type IS NOT NULL THEN
934         ldr := (oils_xpath('//*[local-name()="leader"]/text()', marc))[1];
935
936         IF ldr IS NOT NULL THEN
937             SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
938             SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
939
940
941             tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
942             bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
943
944             -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
945
946             SELECT * INTO type_map FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
947
948             IF type_map.code IS NOT NULL THEN
949                 IF best_type = type_map.code THEN
950                     qual := qual + qual / 2;
951                 END IF;
952
953                 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
954                     ff_tag_data := SUBSTRING((oils_xpath('//*[@tag="' || ff_pos.tag || '"]/text()',marc))[1], ff_pos.start_pos + 1, ff_pos.length);
955                     IF ff_tag_data = best_lang THEN
956                             qual := qual + 100;
957                     END IF;
958                 END LOOP;
959             END IF;
960         END IF;
961     END IF;
962
963     -- Now look for some quality metrics
964     -- DCL record?
965     IF ARRAY_UPPER(oils_xpath('//*[@tag="040"]/*[@code="a" and contains(.,"DLC")]', marc), 1) = 1 THEN
966         qual := qual + 10;
967     END IF;
968
969     -- From OCLC?
970     IF (oils_xpath('//*[@tag="003"]/text()', marc))[1] ~* E'oclo?c' THEN
971         qual := qual + 10;
972     END IF;
973
974     RETURN qual;
975
976 END;
977 $func$ LANGUAGE PLPGSQL;
978
979 CREATE OR REPLACE FUNCTION biblio.extract_fingerprint ( marc text ) RETURNS TEXT AS $func$
980 DECLARE
981         idx             config.biblio_fingerprint%ROWTYPE;
982         xfrm            config.xml_transform%ROWTYPE;
983         prev_xfrm       TEXT;
984         transformed_xml TEXT;
985         xml_node        TEXT;
986         xml_node_list   TEXT[];
987         raw_text        TEXT;
988     output_text TEXT := '';
989 BEGIN
990
991     IF marc IS NULL OR marc = '' THEN
992         RETURN NULL;
993     END IF;
994
995         -- Loop over the indexing entries
996         FOR idx IN SELECT * FROM config.biblio_fingerprint ORDER BY format, id LOOP
997
998                 SELECT INTO xfrm * from config.xml_transform WHERE name = idx.format;
999
1000                 -- See if we can skip the XSLT ... it's expensive
1001                 IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
1002                         -- Can't skip the transform
1003                         IF xfrm.xslt <> '---' THEN
1004                                 transformed_xml := oils_xslt_process(marc,xfrm.xslt);
1005                         ELSE
1006                                 transformed_xml := marc;
1007                         END IF;
1008
1009                         prev_xfrm := xfrm.name;
1010                 END IF;
1011
1012                 raw_text := COALESCE(
1013             naco_normalize(
1014                 ARRAY_TO_STRING(
1015                     oils_xpath(
1016                         '//text()',
1017                         (oils_xpath(
1018                             idx.xpath,
1019                             transformed_xml,
1020                             ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]] 
1021                         ))[1]
1022                     ),
1023                     ''
1024                 )
1025             ),
1026             ''
1027         );
1028
1029         raw_text := REGEXP_REPLACE(raw_text, E'\\[.+?\\]', E'');
1030         raw_text := REGEXP_REPLACE(raw_text, E'\\mthe\\M|\\man?d?d\\M', E'', 'g'); -- arg! the pain!
1031
1032         IF idx.first_word IS TRUE THEN
1033             raw_text := REGEXP_REPLACE(raw_text, E'^(\\w+).*?$', E'\\1');
1034         END IF;
1035
1036                 output_text := output_text || REGEXP_REPLACE(raw_text, E'\\s+', '', 'g');
1037
1038         END LOOP;
1039
1040     RETURN output_text;
1041
1042 END;
1043 $func$ LANGUAGE PLPGSQL;
1044
1045 -- BEFORE UPDATE OR INSERT trigger for biblio.record_entry
1046 CREATE OR REPLACE FUNCTION biblio.fingerprint_trigger () RETURNS TRIGGER AS $func$
1047 BEGIN
1048
1049     -- For TG_ARGV, first param is language (like 'eng'), second is record type (like 'BKS')
1050
1051     IF NEW.deleted IS TRUE THEN -- we don't much care, then, do we?
1052         RETURN NEW;
1053     END IF;
1054
1055     NEW.fingerprint := biblio.extract_fingerprint(NEW.marc);
1056     NEW.quality := biblio.extract_quality(NEW.marc, TG_ARGV[0], TG_ARGV[1]);
1057
1058     RETURN NEW;
1059
1060 END;
1061 $func$ LANGUAGE PLPGSQL;
1062
1063 CREATE OR REPLACE FUNCTION metabib.reingest_metabib_full_rec( bib_id BIGINT ) RETURNS VOID AS $func$
1064 BEGIN
1065     PERFORM * FROM config.internal_flag WHERE name = 'ingest.assume_inserts_only' AND enabled;
1066     IF NOT FOUND THEN
1067         DELETE FROM metabib.real_full_rec WHERE record = bib_id;
1068     END IF;
1069     INSERT INTO metabib.real_full_rec (record, tag, ind1, ind2, subfield, value)
1070         SELECT record, tag, ind1, ind2, subfield, value FROM biblio.flatten_marc( bib_id );
1071
1072     RETURN;
1073 END;
1074 $func$ LANGUAGE PLPGSQL;
1075
1076 CREATE OR REPLACE FUNCTION biblio.extract_located_uris( bib_id BIGINT, marcxml TEXT, editor_id INT ) RETURNS VOID AS $func$
1077 DECLARE
1078     uris            TEXT[];
1079     uri_xml         TEXT;
1080     uri_label       TEXT;
1081     uri_href        TEXT;
1082     uri_use         TEXT;
1083     uri_owner_list  TEXT[];
1084     uri_owner       TEXT;
1085     uri_owner_id    INT;
1086     uri_id          INT;
1087     uri_cn_id       INT;
1088     uri_map_id      INT;
1089 BEGIN
1090
1091     -- Clear any URI mappings and call numbers for this bib.
1092     -- This leads to acn / auricnm inflation, but also enables
1093     -- old acn/auricnm's to go away and for bibs to be deleted.
1094     FOR uri_cn_id IN SELECT id FROM asset.call_number WHERE record = bib_id AND label = '##URI##' AND NOT deleted LOOP
1095         DELETE FROM asset.uri_call_number_map WHERE call_number = uri_cn_id;
1096         DELETE FROM asset.call_number WHERE id = uri_cn_id;
1097     END LOOP;
1098
1099     uris := oils_xpath('//*[@tag="856" and (@ind1="4" or @ind1="1") and (@ind2="0" or @ind2="1")]',marcxml);
1100     IF ARRAY_UPPER(uris,1) > 0 THEN
1101         FOR i IN 1 .. ARRAY_UPPER(uris, 1) LOOP
1102             -- First we pull info out of the 856
1103             uri_xml     := uris[i];
1104
1105             uri_href    := (oils_xpath('//*[@code="u"]/text()',uri_xml))[1];
1106             uri_label   := (oils_xpath('//*[@code="y"]/text()|//*[@code="3"]/text()',uri_xml))[1];
1107             uri_use     := (oils_xpath('//*[@code="z"]/text()|//*[@code="2"]/text()|//*[@code="n"]/text()',uri_xml))[1];
1108
1109             IF uri_label IS NULL THEN
1110                 uri_label := uri_href;
1111             END IF;
1112             CONTINUE WHEN uri_href IS NULL;
1113
1114             -- Get the distinct list of libraries wanting to use 
1115             SELECT  ARRAY_AGG(
1116                         DISTINCT REGEXP_REPLACE(
1117                             x,
1118                             $re$^.*?\((\w+)\).*$$re$,
1119                             E'\\1'
1120                         )
1121                     ) INTO uri_owner_list
1122               FROM  UNNEST(
1123                         oils_xpath(
1124                             '//*[@code="9"]/text()|//*[@code="w"]/text()|//*[@code="n"]/text()',
1125                             uri_xml
1126                         )
1127                     )x;
1128
1129             IF ARRAY_UPPER(uri_owner_list,1) > 0 THEN
1130
1131                 -- look for a matching uri
1132                 IF uri_use IS NULL THEN
1133                     SELECT id INTO uri_id
1134                         FROM asset.uri
1135                         WHERE label = uri_label AND href = uri_href AND use_restriction IS NULL AND active
1136                         ORDER BY id LIMIT 1;
1137                     IF NOT FOUND THEN -- create one
1138                         INSERT INTO asset.uri (label, href, use_restriction) VALUES (uri_label, uri_href, uri_use);
1139                         SELECT id INTO uri_id
1140                             FROM asset.uri
1141                             WHERE label = uri_label AND href = uri_href AND use_restriction IS NULL AND active;
1142                     END IF;
1143                 ELSE
1144                     SELECT id INTO uri_id
1145                         FROM asset.uri
1146                         WHERE label = uri_label AND href = uri_href AND use_restriction = uri_use AND active
1147                         ORDER BY id LIMIT 1;
1148                     IF NOT FOUND THEN -- create one
1149                         INSERT INTO asset.uri (label, href, use_restriction) VALUES (uri_label, uri_href, uri_use);
1150                         SELECT id INTO uri_id
1151                             FROM asset.uri
1152                             WHERE label = uri_label AND href = uri_href AND use_restriction = uri_use AND active;
1153                     END IF;
1154                 END IF;
1155
1156                 FOR j IN 1 .. ARRAY_UPPER(uri_owner_list, 1) LOOP
1157                     uri_owner := uri_owner_list[j];
1158
1159                     SELECT id INTO uri_owner_id FROM actor.org_unit WHERE shortname = uri_owner;
1160                     CONTINUE WHEN NOT FOUND;
1161
1162                     -- we need a call number to link through
1163                     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;
1164                     IF NOT FOUND THEN
1165                         INSERT INTO asset.call_number (owning_lib, record, create_date, edit_date, creator, editor, label)
1166                             VALUES (uri_owner_id, bib_id, 'now', 'now', editor_id, editor_id, '##URI##');
1167                         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;
1168                     END IF;
1169
1170                     -- now, link them if they're not already
1171                     SELECT id INTO uri_map_id FROM asset.uri_call_number_map WHERE call_number = uri_cn_id AND uri = uri_id;
1172                     IF NOT FOUND THEN
1173                         INSERT INTO asset.uri_call_number_map (call_number, uri) VALUES (uri_cn_id, uri_id);
1174                     END IF;
1175
1176                 END LOOP;
1177
1178             END IF;
1179
1180         END LOOP;
1181     END IF;
1182
1183     RETURN;
1184 END;
1185 $func$ LANGUAGE PLPGSQL;
1186
1187 CREATE OR REPLACE FUNCTION metabib.remap_metarecord_for_bib( bib_id BIGINT, fp TEXT ) RETURNS BIGINT AS $func$
1188 DECLARE
1189     source_count    INT;
1190     old_mr          BIGINT;
1191     tmp_mr          metabib.metarecord%ROWTYPE;
1192     deleted_mrs     BIGINT[];
1193 BEGIN
1194
1195     DELETE FROM metabib.metarecord_source_map WHERE source = bib_id; -- Rid ourselves of the search-estimate-killing linkage
1196
1197     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
1198
1199         IF old_mr IS NULL AND fp = tmp_mr.fingerprint THEN -- Find the first fingerprint-matching
1200             old_mr := tmp_mr.id;
1201         ELSE
1202             SELECT COUNT(*) INTO source_count FROM metabib.metarecord_source_map WHERE metarecord = tmp_mr.id;
1203             IF source_count = 0 THEN -- No other records
1204                 deleted_mrs := ARRAY_APPEND(deleted_mrs, tmp_mr.id);
1205                 DELETE FROM metabib.metarecord WHERE id = tmp_mr.id;
1206             END IF;
1207         END IF;
1208
1209     END LOOP;
1210
1211     IF old_mr IS NULL THEN -- we found no suitable, preexisting MR based on old source maps
1212         SELECT id INTO old_mr FROM metabib.metarecord WHERE fingerprint = fp; -- is there one for our current fingerprint?
1213         IF old_mr IS NULL THEN -- nope, create one and grab its id
1214             INSERT INTO metabib.metarecord ( fingerprint, master_record ) VALUES ( fp, bib_id );
1215             SELECT id INTO old_mr FROM metabib.metarecord WHERE fingerprint = fp;
1216         ELSE -- indeed there is. update it with a null cache and recalcualated master record
1217             UPDATE  metabib.metarecord
1218               SET   mods = NULL,
1219                     master_record = ( SELECT id FROM biblio.record_entry WHERE fingerprint = fp ORDER BY quality DESC LIMIT 1)
1220               WHERE id = old_mr;
1221         END IF;
1222     ELSE -- there was one we already attached to, update its mods cache and master_record
1223         UPDATE  metabib.metarecord
1224           SET   mods = NULL,
1225                 master_record = ( SELECT id FROM biblio.record_entry WHERE fingerprint = fp ORDER BY quality DESC LIMIT 1)
1226           WHERE id = old_mr;
1227     END IF;
1228
1229     INSERT INTO metabib.metarecord_source_map (metarecord, source) VALUES (old_mr, bib_id); -- new source mapping
1230
1231     IF ARRAY_UPPER(deleted_mrs,1) > 0 THEN
1232         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
1233     END IF;
1234
1235     RETURN old_mr;
1236
1237 END;
1238 $func$ LANGUAGE PLPGSQL;
1239
1240 CREATE OR REPLACE FUNCTION biblio.map_authority_linking (bibid BIGINT, marc TEXT) RETURNS BIGINT AS $func$
1241     DELETE FROM authority.bib_linking WHERE bib = $1;
1242     INSERT INTO authority.bib_linking (bib, authority)
1243         SELECT  y.bib,
1244                 y.authority
1245           FROM (    SELECT  DISTINCT $1 AS bib,
1246                             BTRIM(remove_paren_substring(txt))::BIGINT AS authority
1247                       FROM  unnest(oils_xpath('//*[@code="0"]/text()',$2)) x(txt)
1248                       WHERE BTRIM(remove_paren_substring(txt)) ~ $re$^\d+$$re$
1249                 ) y JOIN authority.record_entry r ON r.id = y.authority;
1250     SELECT $1;
1251 $func$ LANGUAGE SQL;
1252
1253 -- AFTER UPDATE OR INSERT trigger for biblio.record_entry
1254 CREATE OR REPLACE FUNCTION biblio.indexing_ingest_or_delete () RETURNS TRIGGER AS $func$
1255 DECLARE
1256     transformed_xml TEXT;
1257     prev_xfrm       TEXT;
1258     normalizer      RECORD;
1259     xfrm            config.xml_transform%ROWTYPE;
1260     attr_value      TEXT;
1261     new_attrs       HSTORE := ''::HSTORE;
1262     attr_def        config.record_attr_definition%ROWTYPE;
1263 BEGIN
1264
1265     IF NEW.deleted IS TRUE THEN -- If this bib is deleted
1266         PERFORM * FROM config.internal_flag WHERE
1267             name = 'ingest.metarecord_mapping.preserve_on_delete' AND enabled;
1268         IF NOT FOUND THEN
1269             -- One needs to keep these around to support searches
1270             -- with the #deleted modifier, so one should turn on the named
1271             -- internal flag for that functionality.
1272             DELETE FROM metabib.metarecord_source_map WHERE source = NEW.id;
1273             DELETE FROM metabib.record_attr WHERE id = NEW.id;
1274         END IF;
1275
1276         DELETE FROM authority.bib_linking WHERE bib = NEW.id; -- Avoid updating fields in bibs that are no longer visible
1277         DELETE FROM biblio.peer_bib_copy_map WHERE peer_record = NEW.id; -- Separate any multi-homed items
1278         DELETE FROM metabib.browse_entry_def_map WHERE source = NEW.id; -- Don't auto-suggest deleted bibs
1279         RETURN NEW; -- and we're done
1280     END IF;
1281
1282     IF TG_OP = 'UPDATE' THEN -- re-ingest?
1283         PERFORM * FROM config.internal_flag WHERE name = 'ingest.reingest.force_on_same_marc' AND enabled;
1284
1285         IF NOT FOUND AND OLD.marc = NEW.marc THEN -- don't do anything if the MARC didn't change
1286             RETURN NEW;
1287         END IF;
1288     END IF;
1289
1290     -- Record authority linking
1291     PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_linking' AND enabled;
1292     IF NOT FOUND THEN
1293         PERFORM biblio.map_authority_linking( NEW.id, NEW.marc );
1294     END IF;
1295
1296     -- Flatten and insert the mfr data
1297     PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_metabib_full_rec' AND enabled;
1298     IF NOT FOUND THEN
1299         PERFORM metabib.reingest_metabib_full_rec(NEW.id);
1300
1301         -- Now we pull out attribute data, which is dependent on the mfr for all but XPath-based fields
1302         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_metabib_rec_descriptor' AND enabled;
1303         IF NOT FOUND THEN
1304             FOR attr_def IN SELECT * FROM config.record_attr_definition ORDER BY format LOOP
1305
1306                 IF attr_def.tag IS NOT NULL THEN -- tag (and optional subfield list) selection
1307                     SELECT  STRING_AGG(value, COALESCE(attr_def.joiner,' ')) INTO attr_value
1308                       FROM  (SELECT * FROM metabib.full_rec ORDER BY tag, subfield) AS x
1309                       WHERE record = NEW.id
1310                             AND tag LIKE attr_def.tag
1311                             AND CASE
1312                                 WHEN attr_def.sf_list IS NOT NULL 
1313                                     THEN POSITION(subfield IN attr_def.sf_list) > 0
1314                                 ELSE TRUE
1315                                 END
1316                       GROUP BY tag
1317                       ORDER BY tag
1318                       LIMIT 1;
1319
1320                 ELSIF attr_def.fixed_field IS NOT NULL THEN -- a named fixed field, see config.marc21_ff_pos_map.fixed_field
1321                     attr_value := biblio.marc21_extract_fixed_field(NEW.id, attr_def.fixed_field);
1322
1323                 ELSIF attr_def.xpath IS NOT NULL THEN -- and xpath expression
1324
1325                     SELECT INTO xfrm * FROM config.xml_transform WHERE name = attr_def.format;
1326             
1327                     -- See if we can skip the XSLT ... it's expensive
1328                     IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
1329                         -- Can't skip the transform
1330                         IF xfrm.xslt <> '---' THEN
1331                             transformed_xml := oils_xslt_process(NEW.marc,xfrm.xslt);
1332                         ELSE
1333                             transformed_xml := NEW.marc;
1334                         END IF;
1335             
1336                         prev_xfrm := xfrm.name;
1337                     END IF;
1338
1339                     IF xfrm.name IS NULL THEN
1340                         -- just grab the marcxml (empty) transform
1341                         SELECT INTO xfrm * FROM config.xml_transform WHERE xslt = '---' LIMIT 1;
1342                         prev_xfrm := xfrm.name;
1343                     END IF;
1344
1345                     attr_value := oils_xpath_string(attr_def.xpath, transformed_xml, COALESCE(attr_def.joiner,' '), ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]);
1346
1347                 ELSIF attr_def.phys_char_sf IS NOT NULL THEN -- a named Physical Characteristic, see config.marc21_physical_characteristic_*_map
1348                     SELECT  m.value INTO attr_value
1349                       FROM  biblio.marc21_physical_characteristics(NEW.id) v
1350                             JOIN config.marc21_physical_characteristic_value_map m ON (m.id = v.value)
1351                       WHERE v.subfield = attr_def.phys_char_sf
1352                       LIMIT 1; -- Just in case ...
1353
1354                 END IF;
1355
1356                 -- apply index normalizers to attr_value
1357                 FOR normalizer IN
1358                     SELECT  n.func AS func,
1359                             n.param_count AS param_count,
1360                             m.params AS params
1361                       FROM  config.index_normalizer n
1362                             JOIN config.record_attr_index_norm_map m ON (m.norm = n.id)
1363                       WHERE attr = attr_def.name
1364                       ORDER BY m.pos LOOP
1365                         EXECUTE 'SELECT ' || normalizer.func || '(' ||
1366                             COALESCE( quote_literal( attr_value ), 'NULL' ) ||
1367                             CASE
1368                                 WHEN normalizer.param_count > 0
1369                                     THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
1370                                     ELSE ''
1371                                 END ||
1372                             ')' INTO attr_value;
1373         
1374                 END LOOP;
1375
1376                 -- Add the new value to the hstore
1377                 new_attrs := new_attrs || hstore( attr_def.name, attr_value );
1378
1379             END LOOP;
1380
1381             IF TG_OP = 'INSERT' OR OLD.deleted THEN -- initial insert OR revivication
1382                 DELETE FROM metabib.record_attr WHERE id = NEW.id;
1383                 INSERT INTO metabib.record_attr (id, attrs) VALUES (NEW.id, new_attrs);
1384             ELSE
1385                 UPDATE metabib.record_attr SET attrs = new_attrs WHERE id = NEW.id;
1386             END IF;
1387
1388         END IF;
1389     END IF;
1390
1391     -- Gather and insert the field entry data
1392     PERFORM metabib.reingest_metabib_field_entries(NEW.id);
1393
1394     -- Located URI magic
1395     IF TG_OP = 'INSERT' THEN
1396         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_located_uri' AND enabled;
1397         IF NOT FOUND THEN
1398             PERFORM biblio.extract_located_uris( NEW.id, NEW.marc, NEW.editor );
1399         END IF;
1400     ELSE
1401         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_located_uri' AND enabled;
1402         IF NOT FOUND THEN
1403             PERFORM biblio.extract_located_uris( NEW.id, NEW.marc, NEW.editor );
1404         END IF;
1405     END IF;
1406
1407     -- (re)map metarecord-bib linking
1408     IF TG_OP = 'INSERT' THEN -- if not deleted and performing an insert, check for the flag
1409         PERFORM * FROM config.internal_flag WHERE name = 'ingest.metarecord_mapping.skip_on_insert' AND enabled;
1410         IF NOT FOUND THEN
1411             PERFORM metabib.remap_metarecord_for_bib( NEW.id, NEW.fingerprint );
1412         END IF;
1413     ELSE -- we're doing an update, and we're not deleted, remap
1414         PERFORM * FROM config.internal_flag WHERE name = 'ingest.metarecord_mapping.skip_on_update' AND enabled;
1415         IF NOT FOUND THEN
1416             PERFORM metabib.remap_metarecord_for_bib( NEW.id, NEW.fingerprint );
1417         END IF;
1418     END IF;
1419
1420     RETURN NEW;
1421 END;
1422 $func$ LANGUAGE PLPGSQL;
1423
1424 CREATE OR REPLACE FUNCTION metabib.browse_normalize(facet_text TEXT, mapped_field INT) RETURNS TEXT AS $$
1425 DECLARE
1426     normalizer  RECORD;
1427 BEGIN
1428
1429     FOR normalizer IN
1430         SELECT  n.func AS func,
1431                 n.param_count AS param_count,
1432                 m.params AS params
1433           FROM  config.index_normalizer n
1434                 JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
1435           WHERE m.field = mapped_field AND m.pos < 0
1436           ORDER BY m.pos LOOP
1437
1438             EXECUTE 'SELECT ' || normalizer.func || '(' ||
1439                 quote_literal( facet_text ) ||
1440                 CASE
1441                     WHEN normalizer.param_count > 0
1442                         THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
1443                         ELSE ''
1444                     END ||
1445                 ')' INTO facet_text;
1446
1447     END LOOP;
1448
1449     RETURN facet_text;
1450 END;
1451
1452 $$ LANGUAGE PLPGSQL;
1453
1454
1455 -- This mimics a specific part of QueryParser, turning the first part of a
1456 -- classed search (search_class) into a set of classes and possibly fields.
1457 -- search_class might look like "author" or "title|proper" or "ti|uniform"
1458 -- or "au" or "au|corporate|personal" or anything like that, where the first
1459 -- element of the list you get by separating on the "|" character is either
1460 -- a registered class (config.metabib_class) or an alias
1461 -- (config.metabib_search_alias), and the rest of any such elements are
1462 -- fields (config.metabib_field).
1463 CREATE OR REPLACE
1464     FUNCTION metabib.search_class_to_registered_components(search_class TEXT)
1465     RETURNS SETOF RECORD AS $func$
1466 DECLARE
1467     search_parts        TEXT[];
1468     field_name          TEXT;
1469     search_part_count   INTEGER;
1470     rec                 RECORD;
1471     registered_class    config.metabib_class%ROWTYPE;
1472     registered_alias    config.metabib_search_alias%ROWTYPE;
1473     registered_field    config.metabib_field%ROWTYPE;
1474 BEGIN
1475     search_parts := REGEXP_SPLIT_TO_ARRAY(search_class, E'\\|');
1476
1477     search_part_count := ARRAY_LENGTH(search_parts, 1);
1478     IF search_part_count = 0 THEN
1479         RETURN;
1480     ELSE
1481         SELECT INTO registered_class
1482             * FROM config.metabib_class WHERE name = search_parts[1];
1483         IF FOUND THEN
1484             IF search_part_count < 2 THEN   -- all fields
1485                 rec := (registered_class.name, NULL::INTEGER);
1486                 RETURN NEXT rec;
1487                 RETURN; -- done
1488             END IF;
1489             FOR field_name IN SELECT *
1490                 FROM UNNEST(search_parts[2:search_part_count]) LOOP
1491                 SELECT INTO registered_field
1492                     * FROM config.metabib_field
1493                     WHERE name = field_name AND
1494                         field_class = registered_class.name;
1495                 IF FOUND THEN
1496                     rec := (registered_class.name, registered_field.id);
1497                     RETURN NEXT rec;
1498                 END IF;
1499             END LOOP;
1500         ELSE
1501             -- maybe we have an alias?
1502             SELECT INTO registered_alias
1503                 * FROM config.metabib_search_alias WHERE alias=search_parts[1];
1504             IF NOT FOUND THEN
1505                 RETURN;
1506             ELSE
1507                 IF search_part_count < 2 THEN   -- return w/e the alias says
1508                     rec := (
1509                         registered_alias.field_class, registered_alias.field
1510                     );
1511                     RETURN NEXT rec;
1512                     RETURN; -- done
1513                 ELSE
1514                     FOR field_name IN SELECT *
1515                         FROM UNNEST(search_parts[2:search_part_count]) LOOP
1516                         SELECT INTO registered_field
1517                             * FROM config.metabib_field
1518                             WHERE name = field_name AND
1519                                 field_class = registered_alias.field_class;
1520                         IF FOUND THEN
1521                             rec := (
1522                                 registered_alias.field_class,
1523                                 registered_field.id
1524                             );
1525                             RETURN NEXT rec;
1526                         END IF;
1527                     END LOOP;
1528                 END IF;
1529             END IF;
1530         END IF;
1531     END IF;
1532 END;
1533 $func$ LANGUAGE PLPGSQL ROWS 1;
1534
1535
1536 -- Given a string such as a user might type into a search box, prepare
1537 -- two changed variants for TO_TSQUERY(). See
1538 -- http://www.postgresql.org/docs/9.0/static/textsearch-controls.html
1539 -- The first variant is normalized to match indexed documents regardless
1540 -- of diacritics.  The second variant keeps its diacritics for proper
1541 -- highlighting via TS_HEADLINE().
1542 CREATE OR REPLACE
1543     FUNCTION metabib.autosuggest_prepare_tsquery(orig TEXT) RETURNS TEXT[] AS
1544 $$
1545 DECLARE
1546     orig_ended_in_space     BOOLEAN;
1547     result                  RECORD;
1548     plain                   TEXT;
1549     normalized              TEXT;
1550 BEGIN
1551     orig_ended_in_space := orig ~ E'\\s$';
1552
1553     orig := ARRAY_TO_STRING(
1554         evergreen.regexp_split_to_array(orig, E'\\W+'), ' '
1555     );
1556
1557     normalized := public.naco_normalize(orig); -- also trim()s
1558     plain := trim(orig);
1559
1560     IF NOT orig_ended_in_space THEN
1561         plain := plain || ':*';
1562         normalized := normalized || ':*';
1563     END IF;
1564
1565     plain := ARRAY_TO_STRING(
1566         evergreen.regexp_split_to_array(plain, E'\\s+'), ' & '
1567     );
1568     normalized := ARRAY_TO_STRING(
1569         evergreen.regexp_split_to_array(normalized, E'\\s+'), ' & '
1570     );
1571
1572     RETURN ARRAY[normalized, plain];
1573 END;
1574 $$ LANGUAGE PLPGSQL;
1575
1576
1577 CREATE OR REPLACE
1578     FUNCTION metabib.suggest_browse_entries(
1579         raw_query_text  TEXT,   -- actually typed by humans at the UI level
1580         search_class    TEXT,   -- 'alias' or 'class' or 'class|field..', etc
1581         headline_opts   TEXT,   -- markup options for ts_headline()
1582         visibility_org  INTEGER,-- null if you don't want opac visibility test
1583         query_limit     INTEGER,-- use in LIMIT clause of interal query
1584         normalization   INTEGER -- argument to TS_RANK_CD()
1585     ) RETURNS TABLE (
1586         value                   TEXT,   -- plain
1587         field                   INTEGER,
1588         buoyant_and_class_match BOOL,
1589         field_match             BOOL,
1590         field_weight            INTEGER,
1591         rank                    REAL,
1592         buoyant                 BOOL,
1593         match                   TEXT    -- marked up
1594     ) AS $func$
1595 DECLARE
1596     prepared_query_texts    TEXT[];
1597     query                   TSQUERY;
1598     plain_query             TSQUERY;
1599     opac_visibility_join    TEXT;
1600     search_class_join       TEXT;
1601     r_fields                RECORD;
1602 BEGIN
1603     prepared_query_texts := metabib.autosuggest_prepare_tsquery(raw_query_text);
1604
1605     query := TO_TSQUERY('keyword', prepared_query_texts[1]);
1606     plain_query := TO_TSQUERY('keyword', prepared_query_texts[2]);
1607
1608     visibility_org := NULLIF(visibility_org,-1);
1609     IF visibility_org IS NOT NULL THEN
1610         opac_visibility_join := '
1611     JOIN asset.opac_visible_copies aovc ON (
1612         aovc.record = x.source AND
1613         aovc.circ_lib IN (SELECT id FROM actor.org_unit_descendants($4))
1614     )';
1615     ELSE
1616         opac_visibility_join := '';
1617     END IF;
1618
1619     -- The following determines whether we only provide suggestsons matching
1620     -- the user's selected search_class, or whether we show other suggestions
1621     -- too. The reason for MIN() is that for search_classes like
1622     -- 'title|proper|uniform' you would otherwise get multiple rows.  The
1623     -- implication is that if title as a class doesn't have restrict,
1624     -- nor does the proper field, but the uniform field does, you're going
1625     -- to get 'false' for your overall evaluation of 'should we restrict?'
1626     -- To invert that, change from MIN() to MAX().
1627
1628     SELECT
1629         INTO r_fields
1630             MIN(cmc.restrict::INT) AS restrict_class,
1631             MIN(cmf.restrict::INT) AS restrict_field
1632         FROM metabib.search_class_to_registered_components(search_class)
1633             AS _registered (field_class TEXT, field INT)
1634         JOIN
1635             config.metabib_class cmc ON (cmc.name = _registered.field_class)
1636         LEFT JOIN
1637             config.metabib_field cmf ON (cmf.id = _registered.field);
1638
1639     -- evaluate 'should we restrict?'
1640     IF r_fields.restrict_field::BOOL OR r_fields.restrict_class::BOOL THEN
1641         search_class_join := '
1642     JOIN
1643         metabib.search_class_to_registered_components($2)
1644         AS _registered (field_class TEXT, field INT) ON (
1645             (_registered.field IS NULL AND
1646                 _registered.field_class = cmf.field_class) OR
1647             (_registered.field = cmf.id)
1648         )
1649     ';
1650     ELSE
1651         search_class_join := '
1652     LEFT JOIN
1653         metabib.search_class_to_registered_components($2)
1654         AS _registered (field_class TEXT, field INT) ON (
1655             _registered.field_class = cmc.name
1656         )
1657     ';
1658     END IF;
1659
1660     RETURN QUERY EXECUTE '
1661 SELECT  DISTINCT
1662         x.value,
1663         x.id,
1664         x.push,
1665         x.restrict,
1666         x.weight,
1667         x.ts_rank_cd,
1668         x.buoyant,
1669         TS_HEADLINE(value, $7, $3)
1670   FROM  (SELECT DISTINCT
1671                 mbe.value,
1672                 cmf.id,
1673                 cmc.buoyant AND _registered.field_class IS NOT NULL AS push,
1674                 _registered.field = cmf.id AS restrict,
1675                 cmf.weight,
1676                 TS_RANK_CD(mbe.index_vector, $1, $6),
1677                 cmc.buoyant,
1678                 mbedm.source
1679           FROM  metabib.browse_entry_def_map mbedm
1680                 JOIN (SELECT * FROM metabib.browse_entry WHERE index_vector @@ $1 LIMIT 10000) mbe ON (mbe.id = mbedm.entry)
1681                 JOIN config.metabib_field cmf ON (cmf.id = mbedm.def)
1682                 JOIN config.metabib_class cmc ON (cmf.field_class = cmc.name)
1683                 '  || search_class_join || '
1684           ORDER BY 3 DESC, 4 DESC NULLS LAST, 5 DESC, 6 DESC, 7 DESC, 1 ASC
1685           LIMIT 1000) AS x
1686         ' || opac_visibility_join || '
1687   ORDER BY 3 DESC, 4 DESC NULLS LAST, 5 DESC, 6 DESC, 7 DESC, 1 ASC
1688   LIMIT $5
1689 '   -- sic, repeat the order by clause in the outer select too
1690     USING
1691         query, search_class, headline_opts,
1692         visibility_org, query_limit, normalization, plain_query
1693         ;
1694
1695     -- sort order:
1696     --  buoyant AND chosen class = match class
1697     --  chosen field = match field
1698     --  field weight
1699     --  rank
1700     --  buoyancy
1701     --  value itself
1702
1703 END;
1704 $func$ LANGUAGE PLPGSQL;
1705
1706 CREATE OR REPLACE FUNCTION public.oils_tsearch2 () RETURNS TRIGGER AS $$
1707 DECLARE
1708     normalizer      RECORD;
1709     value           TEXT := '';
1710     temp_vector     TEXT := '';
1711     ts_rec          RECORD;
1712     cur_weight      "char";
1713 BEGIN
1714
1715     value := NEW.value;
1716     NEW.index_vector = ''::tsvector;
1717
1718     IF TG_TABLE_NAME::TEXT ~ 'field_entry$' THEN
1719         FOR normalizer IN
1720             SELECT  n.func AS func,
1721                     n.param_count AS param_count,
1722                     m.params AS params
1723               FROM  config.index_normalizer n
1724                     JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
1725               WHERE field = NEW.field AND m.pos < 0
1726               ORDER BY m.pos LOOP
1727                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
1728                     quote_literal( value ) ||
1729                     CASE
1730                         WHEN normalizer.param_count > 0
1731                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
1732                             ELSE ''
1733                         END ||
1734                     ')' INTO value;
1735
1736         END LOOP;
1737
1738         NEW.value = value;
1739
1740         FOR normalizer IN
1741             SELECT  n.func AS func,
1742                     n.param_count AS param_count,
1743                     m.params AS params
1744               FROM  config.index_normalizer n
1745                     JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
1746               WHERE field = NEW.field AND m.pos >= 0
1747               ORDER BY m.pos LOOP
1748                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
1749                     quote_literal( value ) ||
1750                     CASE
1751                         WHEN normalizer.param_count > 0
1752                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
1753                             ELSE ''
1754                         END ||
1755                     ')' INTO value;
1756
1757         END LOOP;
1758    END IF;
1759
1760     IF TG_TABLE_NAME::TEXT ~ 'browse_entry$' THEN
1761         value :=  ARRAY_TO_STRING(
1762             evergreen.regexp_split_to_array(value, E'\\W+'), ' '
1763         );
1764         value := public.search_normalize(value);
1765         NEW.index_vector = to_tsvector(TG_ARGV[0]::regconfig, value);
1766     ELSIF TG_TABLE_NAME::TEXT ~ 'field_entry$' THEN
1767         FOR ts_rec IN
1768             SELECT ts_config, index_weight
1769             FROM config.metabib_class_ts_map
1770             WHERE field_class = TG_ARGV[0]
1771                 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'))
1772                 AND always OR NOT EXISTS (SELECT 1 FROM config.metabib_field_ts_map WHERE metabib_field = NEW.field)
1773             UNION
1774             SELECT ts_config, index_weight
1775             FROM config.metabib_field_ts_map
1776             WHERE metabib_field = NEW.field
1777                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'))
1778             ORDER BY index_weight ASC
1779         LOOP
1780             IF cur_weight IS NOT NULL AND cur_weight != ts_rec.index_weight THEN
1781                 NEW.index_vector = NEW.index_vector || setweight(temp_vector::tsvector,cur_weight);
1782                 temp_vector = '';
1783             END IF;
1784             cur_weight = ts_rec.index_weight;
1785             SELECT INTO temp_vector temp_vector || ' ' || to_tsvector(ts_rec.ts_config::regconfig, value)::TEXT;
1786         END LOOP;
1787         NEW.index_vector = NEW.index_vector || setweight(temp_vector::tsvector,cur_weight);
1788     ELSE
1789         NEW.index_vector = to_tsvector(TG_ARGV[0]::regconfig, value);
1790     END IF;
1791
1792     RETURN NEW;
1793 END;
1794 $$ LANGUAGE PLPGSQL;
1795
1796
1797 CREATE TYPE metabib.flat_browse_entry_appearance AS (
1798     browse_entry    BIGINT,
1799     value           TEXT,
1800     fields          TEXT,
1801     authorities     TEXT,
1802     sees            TEXT,
1803     sources         INT,        -- visible ones, that is
1804     asources        INT,        -- visible ones, that is
1805     row_number      INT,        -- internal use, sort of
1806     accurate        BOOL,       -- Count in sources field is accurate? Not
1807                                 -- if we had more than a browse superpage
1808                                 -- of records to look at.
1809     aaccurate       BOOL,       -- See previous comment...
1810     pivot_point     BIGINT
1811 );
1812
1813
1814 CREATE OR REPLACE FUNCTION metabib.browse_bib_pivot(
1815     INT[],
1816     TEXT
1817 ) RETURNS BIGINT AS $p$
1818     SELECT  mbe.id
1819       FROM  metabib.browse_entry mbe
1820             JOIN metabib.browse_entry_def_map mbedm ON (
1821                 mbedm.entry = mbe.id
1822                 AND mbedm.def = ANY($1)
1823             )
1824       WHERE mbe.sort_value >= public.naco_normalize($2)
1825       ORDER BY mbe.sort_value, mbe.value LIMIT 1;
1826 $p$ LANGUAGE SQL STABLE;
1827
1828 CREATE OR REPLACE FUNCTION metabib.browse_authority_pivot(
1829     INT[],
1830     TEXT
1831 ) RETURNS BIGINT AS $p$
1832     SELECT  mbe.id
1833       FROM  metabib.browse_entry mbe
1834             JOIN metabib.browse_entry_simple_heading_map mbeshm ON ( mbeshm.entry = mbe.id )
1835             JOIN authority.simple_heading ash ON ( mbeshm.simple_heading = ash.id )
1836             JOIN authority.control_set_auth_field_metabib_field_map_refs map ON (
1837                 ash.atag = map.authority_field
1838                 AND map.metabib_field = ANY($1)
1839             )
1840       WHERE mbe.sort_value >= public.naco_normalize($2)
1841       ORDER BY mbe.sort_value, mbe.value LIMIT 1;
1842 $p$ LANGUAGE SQL STABLE;
1843
1844 CREATE OR REPLACE FUNCTION metabib.browse_authority_refs_pivot(
1845     INT[],
1846     TEXT
1847 ) RETURNS BIGINT AS $p$
1848     SELECT  mbe.id
1849       FROM  metabib.browse_entry mbe
1850             JOIN metabib.browse_entry_simple_heading_map mbeshm ON ( mbeshm.entry = mbe.id )
1851             JOIN authority.simple_heading ash ON ( mbeshm.simple_heading = ash.id )
1852             JOIN authority.control_set_auth_field_metabib_field_map_refs_only map ON (
1853                 ash.atag = map.authority_field
1854                 AND map.metabib_field = ANY($1)
1855             )
1856       WHERE mbe.sort_value >= public.naco_normalize($2)
1857       ORDER BY mbe.sort_value, mbe.value LIMIT 1;
1858 $p$ LANGUAGE SQL STABLE;
1859
1860 CREATE OR REPLACE FUNCTION metabib.browse_pivot(
1861     INT[],
1862     TEXT
1863 ) RETURNS BIGINT AS $p$
1864     SELECT  id FROM metabib.browse_entry
1865       WHERE id IN (
1866                 metabib.browse_bib_pivot($1, $2),
1867                 metabib.browse_authority_refs_pivot($1,$2) -- only look in 4xx, 5xx, 7xx of authority
1868             )
1869       ORDER BY sort_value, value LIMIT 1;
1870 $p$ LANGUAGE SQL STABLE;
1871
1872
1873 CREATE OR REPLACE FUNCTION metabib.staged_browse(
1874     query                   TEXT,
1875     fields                  INT[],
1876     context_org             INT,
1877     context_locations       INT[],
1878     staff                   BOOL,
1879     browse_superpage_size   INT,
1880     count_up_from_zero      BOOL,   -- if false, count down from -1
1881     result_limit            INT,
1882     next_pivot_pos          INT
1883 ) RETURNS SETOF metabib.flat_browse_entry_appearance AS $p$
1884 DECLARE
1885     curs                    REFCURSOR;
1886     rec                     RECORD;
1887     qpfts_query             TEXT;
1888     aqpfts_query            TEXT;
1889     afields                 INT[];
1890     bfields                 INT[];
1891     result_row              metabib.flat_browse_entry_appearance%ROWTYPE;
1892     results_skipped         INT := 0;
1893     row_counter             INT := 0;
1894     row_number              INT;
1895     slice_start             INT;
1896     slice_end               INT;
1897     full_end                INT;
1898     all_records             BIGINT[];
1899     all_brecords             BIGINT[];
1900     all_arecords            BIGINT[];
1901     superpage_of_records    BIGINT[];
1902     superpage_size          INT;
1903 BEGIN
1904     IF count_up_from_zero THEN
1905         row_number := 0;
1906     ELSE
1907         row_number := -1;
1908     END IF;
1909
1910     OPEN curs FOR EXECUTE query;
1911
1912     LOOP
1913         FETCH curs INTO rec;
1914         IF NOT FOUND THEN
1915             IF result_row.pivot_point IS NOT NULL THEN
1916                 RETURN NEXT result_row;
1917             END IF;
1918             RETURN;
1919         END IF;
1920
1921
1922         -- Gather aggregate data based on the MBE row we're looking at now, authority axis
1923         SELECT INTO all_arecords, result_row.sees, afields
1924                 ARRAY_AGG(DISTINCT abl.bib), -- bibs to check for visibility
1925                 STRING_AGG(DISTINCT aal.source, $$,$$), -- authority record ids
1926                 ARRAY_AGG(DISTINCT map.metabib_field) -- authority-tag-linked CMF rows
1927
1928           FROM  metabib.browse_entry_simple_heading_map mbeshm
1929                 JOIN authority.simple_heading ash ON ( mbeshm.simple_heading = ash.id )
1930                 JOIN authority.authority_linking aal ON ( ash.record = aal.source )
1931                 JOIN authority.bib_linking abl ON ( aal.target = abl.authority )
1932                 JOIN authority.control_set_auth_field_metabib_field_map_refs map ON (
1933                     ash.atag = map.authority_field
1934                     AND map.metabib_field = ANY(fields)
1935                 )
1936           WHERE mbeshm.entry = rec.id;
1937
1938
1939         -- Gather aggregate data based on the MBE row we're looking at now, bib axis
1940         SELECT INTO all_brecords, result_row.authorities, bfields
1941                 ARRAY_AGG(DISTINCT source),
1942                 STRING_AGG(DISTINCT authority, $$,$$),
1943                 ARRAY_AGG(DISTINCT def)
1944           FROM  metabib.browse_entry_def_map
1945           WHERE entry = rec.id
1946                 AND def = ANY(fields);
1947
1948         SELECT INTO result_row.fields STRING_AGG(DISTINCT x, $$,$$) FROM UNNEST(afields || bfields) x;
1949
1950         result_row.sources := 0;
1951         result_row.asources := 0;
1952
1953         -- Bib-linked vis checking
1954         IF ARRAY_UPPER(all_brecords,1) IS NOT NULL THEN
1955
1956             full_end := ARRAY_LENGTH(all_brecords, 1);
1957             superpage_size := COALESCE(browse_superpage_size, full_end);
1958             slice_start := 1;
1959             slice_end := superpage_size;
1960
1961             WHILE result_row.sources = 0 AND slice_start <= full_end LOOP
1962                 superpage_of_records := all_brecords[slice_start:slice_end];
1963                 qpfts_query :=
1964                     'SELECT NULL::BIGINT AS id, ARRAY[r] AS records, ' ||
1965                     '1::INT AS rel FROM (SELECT UNNEST(' ||
1966                     quote_literal(superpage_of_records) || '::BIGINT[]) AS r) rr';
1967
1968                 -- We use search.query_parser_fts() for visibility testing.
1969                 -- We're calling it once per browse-superpage worth of records
1970                 -- out of the set of records related to a given mbe, until we've
1971                 -- either exhausted that set of records or found at least 1
1972                 -- visible record.
1973
1974                 SELECT INTO result_row.sources visible
1975                     FROM search.query_parser_fts(
1976                         context_org, NULL, qpfts_query, NULL,
1977                         context_locations, 0, NULL, NULL, FALSE, staff, FALSE
1978                     ) qpfts
1979                     WHERE qpfts.rel IS NULL;
1980
1981                 slice_start := slice_start + superpage_size;
1982                 slice_end := slice_end + superpage_size;
1983             END LOOP;
1984
1985             -- Accurate?  Well, probably.
1986             result_row.accurate := browse_superpage_size IS NULL OR
1987                 browse_superpage_size >= full_end;
1988
1989         END IF;
1990
1991         -- Authority-linked vis checking
1992         IF ARRAY_UPPER(all_arecords,1) IS NOT NULL THEN
1993
1994             full_end := ARRAY_LENGTH(all_arecords, 1);
1995             superpage_size := COALESCE(browse_superpage_size, full_end);
1996             slice_start := 1;
1997             slice_end := superpage_size;
1998
1999             WHILE result_row.asources = 0 AND slice_start <= full_end LOOP
2000                 superpage_of_records := all_arecords[slice_start:slice_end];
2001                 qpfts_query :=
2002                     'SELECT NULL::BIGINT AS id, ARRAY[r] AS records, ' ||
2003                     '1::INT AS rel FROM (SELECT UNNEST(' ||
2004                     quote_literal(superpage_of_records) || '::BIGINT[]) AS r) rr';
2005
2006                 -- We use search.query_parser_fts() for visibility testing.
2007                 -- We're calling it once per browse-superpage worth of records
2008                 -- out of the set of records related to a given mbe, via
2009                 -- authority until we've either exhausted that set of records
2010                 -- or found at least 1 visible record.
2011
2012                 SELECT INTO result_row.asources visible
2013                     FROM search.query_parser_fts(
2014                         context_org, NULL, qpfts_query, NULL,
2015                         context_locations, 0, NULL, NULL, FALSE, staff, FALSE
2016                     ) qpfts
2017                     WHERE qpfts.rel IS NULL;
2018
2019                 slice_start := slice_start + superpage_size;
2020                 slice_end := slice_end + superpage_size;
2021             END LOOP;
2022
2023
2024             -- Accurate?  Well, probably.
2025             result_row.aaccurate := browse_superpage_size IS NULL OR
2026                 browse_superpage_size >= full_end;
2027
2028         END IF;
2029
2030         IF result_row.sources > 0 OR result_row.asources > 0 THEN
2031
2032             -- The function that calls this function needs row_number in order
2033             -- to correctly order results from two different runs of this
2034             -- functions.
2035             result_row.row_number := row_number;
2036
2037             -- Now, if row_counter is still less than limit, return a row.  If
2038             -- not, but it is less than next_pivot_pos, continue on without
2039             -- returning actual result rows until we find
2040             -- that next pivot, and return it.
2041
2042             IF row_counter < result_limit THEN
2043                 result_row.browse_entry := rec.id;
2044                 result_row.value := rec.value;
2045
2046                 RETURN NEXT result_row;
2047             ELSE
2048                 result_row.browse_entry := NULL;
2049                 result_row.authorities := NULL;
2050                 result_row.fields := NULL;
2051                 result_row.value := NULL;
2052                 result_row.sources := NULL;
2053                 result_row.sees := NULL;
2054                 result_row.accurate := NULL;
2055                 result_row.aaccurate := NULL;
2056                 result_row.pivot_point := rec.id;
2057
2058                 IF row_counter >= next_pivot_pos THEN
2059                     RETURN NEXT result_row;
2060                     RETURN;
2061                 END IF;
2062             END IF;
2063
2064             IF count_up_from_zero THEN
2065                 row_number := row_number + 1;
2066             ELSE
2067                 row_number := row_number - 1;
2068             END IF;
2069
2070             -- row_counter is different from row_number.
2071             -- It simply counts up from zero so that we know when
2072             -- we've reached our limit.
2073             row_counter := row_counter + 1;
2074         END IF;
2075     END LOOP;
2076 END;
2077 $p$ LANGUAGE PLPGSQL;
2078
2079
2080 CREATE OR REPLACE FUNCTION metabib.browse(
2081     search_field            INT[],
2082     browse_term             TEXT,
2083     context_org             INT DEFAULT NULL,
2084     context_loc_group       INT DEFAULT NULL,
2085     staff                   BOOL DEFAULT FALSE,
2086     pivot_id                BIGINT DEFAULT NULL,
2087     result_limit            INT DEFAULT 10
2088 ) RETURNS SETOF metabib.flat_browse_entry_appearance AS $p$
2089 DECLARE
2090     core_query              TEXT;
2091     back_query              TEXT;
2092     forward_query           TEXT;
2093     pivot_sort_value        TEXT;
2094     pivot_sort_fallback     TEXT;
2095     context_locations       INT[];
2096     browse_superpage_size   INT;
2097     results_skipped         INT := 0;
2098     back_limit              INT;
2099     back_to_pivot           INT;
2100     forward_limit           INT;
2101     forward_to_pivot        INT;
2102 BEGIN
2103     -- First, find the pivot if we were given a browse term but not a pivot.
2104     IF pivot_id IS NULL THEN
2105         pivot_id := metabib.browse_pivot(search_field, browse_term);
2106     END IF;
2107
2108     SELECT INTO pivot_sort_value, pivot_sort_fallback
2109         sort_value, value FROM metabib.browse_entry WHERE id = pivot_id;
2110
2111     -- Bail if we couldn't find a pivot.
2112     IF pivot_sort_value IS NULL THEN
2113         RETURN;
2114     END IF;
2115
2116     -- Transform the context_loc_group argument (if any) (logc at the
2117     -- TPAC layer) into a form we'll be able to use.
2118     IF context_loc_group IS NOT NULL THEN
2119         SELECT INTO context_locations ARRAY_AGG(location)
2120             FROM asset.copy_location_group_map
2121             WHERE lgroup = context_loc_group;
2122     END IF;
2123
2124     -- Get the configured size of browse superpages.
2125     SELECT INTO browse_superpage_size value     -- NULL ok
2126         FROM config.global_flag
2127         WHERE enabled AND name = 'opac.browse.holdings_visibility_test_limit';
2128
2129     -- First we're going to search backward from the pivot, then we're going
2130     -- to search forward.  In each direction, we need two limits.  At the
2131     -- lesser of the two limits, we delineate the edge of the result set
2132     -- we're going to return.  At the greater of the two limits, we find the
2133     -- pivot value that would represent an offset from the current pivot
2134     -- at a distance of one "page" in either direction, where a "page" is a
2135     -- result set of the size specified in the "result_limit" argument.
2136     --
2137     -- The two limits in each direction make four derived values in total,
2138     -- and we calculate them now.
2139     back_limit := CEIL(result_limit::FLOAT / 2);
2140     back_to_pivot := result_limit;
2141     forward_limit := result_limit / 2;
2142     forward_to_pivot := result_limit - 1;
2143
2144     -- This is the meat of the SQL query that finds browse entries.  We'll
2145     -- pass this to a function which uses it with a cursor, so that individual
2146     -- rows may be fetched in a loop until some condition is satisfied, without
2147     -- waiting for a result set of fixed size to be collected all at once.
2148     core_query := '
2149 SELECT  mbe.id,
2150         mbe.value,
2151         mbe.sort_value
2152   FROM  metabib.browse_entry mbe
2153   WHERE (
2154             EXISTS ( -- are there any bibs using this mbe via the requested fields?
2155                 SELECT  1
2156                   FROM  metabib.browse_entry_def_map mbedm
2157                   WHERE mbedm.entry = mbe.id AND mbedm.def = ANY(' || quote_literal(search_field) || ')
2158                   LIMIT 1
2159             ) OR EXISTS ( -- are there any authorities using this mbe via the requested fields?
2160                 SELECT  1
2161                   FROM  metabib.browse_entry_simple_heading_map mbeshm
2162                         JOIN authority.simple_heading ash ON ( mbeshm.simple_heading = ash.id )
2163                         JOIN authority.control_set_auth_field_metabib_field_map_refs map ON (
2164                             ash.atag = map.authority_field
2165                             AND map.metabib_field = ANY(' || quote_literal(search_field) || ')
2166                         )
2167                   WHERE mbeshm.entry = mbe.id
2168             )
2169         ) AND ';
2170
2171     -- This is the variant of the query for browsing backward.
2172     back_query := core_query ||
2173         ' mbe.sort_value <= ' || quote_literal(pivot_sort_value) ||
2174     ' ORDER BY mbe.sort_value DESC, mbe.value DESC ';
2175
2176     -- This variant browses forward.
2177     forward_query := core_query ||
2178         ' mbe.sort_value > ' || quote_literal(pivot_sort_value) ||
2179     ' ORDER BY mbe.sort_value, mbe.value ';
2180
2181     -- We now call the function which applies a cursor to the provided
2182     -- queries, stopping at the appropriate limits and also giving us
2183     -- the next page's pivot.
2184     RETURN QUERY
2185         SELECT * FROM metabib.staged_browse(
2186             back_query, search_field, context_org, context_locations,
2187             staff, browse_superpage_size, TRUE, back_limit, back_to_pivot
2188         ) UNION
2189         SELECT * FROM metabib.staged_browse(
2190             forward_query, search_field, context_org, context_locations,
2191             staff, browse_superpage_size, FALSE, forward_limit, forward_to_pivot
2192         ) ORDER BY row_number DESC;
2193
2194 END;
2195 $p$ LANGUAGE PLPGSQL;
2196
2197 CREATE OR REPLACE FUNCTION metabib.browse(
2198     search_class        TEXT,
2199     browse_term         TEXT,
2200     context_org         INT DEFAULT NULL,
2201     context_loc_group   INT DEFAULT NULL,
2202     staff               BOOL DEFAULT FALSE,
2203     pivot_id            BIGINT DEFAULT NULL,
2204     result_limit        INT DEFAULT 10
2205 ) RETURNS SETOF metabib.flat_browse_entry_appearance AS $p$
2206 BEGIN
2207     RETURN QUERY SELECT * FROM metabib.browse(
2208         (SELECT COALESCE(ARRAY_AGG(id), ARRAY[]::INT[])
2209             FROM config.metabib_field WHERE field_class = search_class),
2210         browse_term,
2211         context_org,
2212         context_loc_group,
2213         staff,
2214         pivot_id,
2215         result_limit
2216     );
2217 END;
2218 $p$ LANGUAGE PLPGSQL;
2219
2220 COMMIT;