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