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