]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/002.schema.config.sql
Stamping upgrade for copy_location_alert
[working/Evergreen.git] / Open-ILS / src / sql / Pg / 002.schema.config.sql
1 /*
2  * Copyright (C) 2004-2008  Georgia Public Library Service
3  * Copyright (C) 2008-2011  Equinox Software, Inc.
4  * Mike Rylander <miker@esilibrary.com>
5  * Copyright (C) 2010 Merrimack Valley Library Consortium
6  * Jason Stephenson <jstephenson@mvlc.org>
7  * Copyright (C) 2010 Laurentian University
8  * Dan Scott <dscott@laurentian.ca>
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  */
21
22
23
24 DROP SCHEMA IF EXISTS stats CASCADE;
25 DROP SCHEMA IF EXISTS config CASCADE;
26
27 BEGIN;
28 CREATE SCHEMA stats;
29
30 CREATE SCHEMA config;
31 COMMENT ON SCHEMA config IS $$
32 The config schema holds static configuration data for the
33 Evergreen installation.
34 $$;
35
36 CREATE TABLE config.internal_flag (
37     name    TEXT    PRIMARY KEY,
38     value   TEXT,
39     enabled BOOL    NOT NULL DEFAULT FALSE
40 );
41 INSERT INTO config.internal_flag (name) VALUES ('ingest.metarecord_mapping.skip_on_insert');
42 INSERT INTO config.internal_flag (name) VALUES ('ingest.metarecord_mapping.skip_on_update');
43 INSERT INTO config.internal_flag (name) VALUES ('ingest.reingest.force_on_same_marc');
44 INSERT INTO config.internal_flag (name) VALUES ('ingest.disable_located_uri');
45 INSERT INTO config.internal_flag (name) VALUES ('ingest.disable_metabib_full_rec');
46 INSERT INTO config.internal_flag (name) VALUES ('ingest.disable_metabib_rec_descriptor');
47 INSERT INTO config.internal_flag (name) VALUES ('ingest.disable_metabib_field_entry');
48 INSERT INTO config.internal_flag (name) VALUES ('ingest.assume_inserts_only');
49
50 CREATE TABLE config.global_flag (
51     label   TEXT    NOT NULL
52 ) INHERITS (config.internal_flag);
53 ALTER TABLE config.global_flag ADD PRIMARY KEY (name);
54
55 CREATE TABLE config.upgrade_log (
56     version         TEXT    PRIMARY KEY,
57     install_date    TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
58     applied_to      TEXT
59 );
60
61 CREATE TABLE config.db_patch_dependencies (
62   db_patch      TEXT PRIMARY KEY,
63   supersedes    TEXT[],
64   deprecates    TEXT[]
65 );
66
67 CREATE OR REPLACE FUNCTION evergreen.array_overlap_check (/* field */) RETURNS TRIGGER AS $$
68 DECLARE
69     fld     TEXT;
70     cnt     INT;
71 BEGIN
72     fld := TG_ARGV[1];
73     EXECUTE 'SELECT COUNT(*) FROM '|| TG_TABLE_SCHEMA ||'.'|| TG_TABLE_NAME ||' WHERE '|| fld ||' && ($1).'|| fld INTO cnt USING NEW;
74     IF cnt > 0 THEN
75         RAISE EXCEPTION 'Cannot insert duplicate array into field % of table %', fld, TG_TABLE_SCHEMA ||'.'|| TG_TABLE_NAME;
76     END IF;
77     RETURN NEW;
78 END;
79 $$ LANGUAGE PLPGSQL;
80
81 CREATE TRIGGER no_overlapping_sups
82     BEFORE INSERT OR UPDATE ON config.db_patch_dependencies
83     FOR EACH ROW EXECUTE PROCEDURE evergreen.array_overlap_check ('supersedes');
84
85 CREATE TRIGGER no_overlapping_deps
86     BEFORE INSERT OR UPDATE ON config.db_patch_dependencies
87     FOR EACH ROW EXECUTE PROCEDURE evergreen.array_overlap_check ('deprecates');
88
89 INSERT INTO config.upgrade_log (version, applied_to) VALUES ('0671', :eg_version); -- tsbere/berick
90
91 CREATE TABLE config.bib_source (
92         id              SERIAL  PRIMARY KEY,
93         quality         INT     CHECK ( quality BETWEEN 0 AND 100 ),
94         source          TEXT    NOT NULL UNIQUE,
95         transcendant    BOOL    NOT NULL DEFAULT FALSE,
96         can_have_copies BOOL    NOT NULL DEFAULT TRUE
97 );
98 COMMENT ON TABLE config.bib_source IS $$
99 This is table is used to set up the relative "quality" of each
100 MARC source, such as OCLC.  Also identifies "transcendant" sources,
101 i.e., sources of bib records that should display in the OPAC
102 even if no copies or located URIs are attached. Also indicates if
103 the source is allowed to have actual copies on its bibs. Volumes
104 for targeted URIs are unaffected by this setting.
105 $$;
106
107 CREATE TABLE config.standing (
108         id              SERIAL  PRIMARY KEY,
109         value           TEXT    NOT NULL UNIQUE
110 );
111 COMMENT ON TABLE config.standing IS $$
112 Patron Standings
113
114 This table contains the values that can be applied to a patron
115 by a staff member.  These values should not be changed, other
116 than for translation, as the ID column is currently a "magic
117 number" in the source. :(
118 $$;
119
120 CREATE TABLE config.standing_penalty (
121         id                      SERIAL  PRIMARY KEY,
122         name            TEXT    NOT NULL UNIQUE,
123         label           TEXT    NOT NULL,
124         block_list      TEXT,
125         staff_alert     BOOL    NOT NULL DEFAULT FALSE,
126         org_depth       INTEGER
127 );
128
129 CREATE TABLE config.xml_transform (
130         name            TEXT    PRIMARY KEY,
131         namespace_uri   TEXT    NOT NULL,
132         prefix          TEXT    NOT NULL,
133         xslt            TEXT    NOT NULL
134 );
135
136 CREATE TABLE config.biblio_fingerprint (
137         id                      SERIAL  PRIMARY KEY,
138         name            TEXT    NOT NULL, 
139         xpath           TEXT    NOT NULL,
140     first_word  BOOL    NOT NULL DEFAULT FALSE,
141         format          TEXT    NOT NULL DEFAULT 'marcxml'
142 );
143
144 INSERT INTO config.biblio_fingerprint (name, xpath, format)
145     VALUES (
146         'Title',
147         '//marc:datafield[@tag="700"]/marc:subfield[@code="t"]|' ||
148             '//marc:datafield[@tag="240"]/marc:subfield[@code="a"]|' ||
149             '//marc:datafield[@tag="242"]/marc:subfield[@code="a"]|' ||
150             '//marc:datafield[@tag="246"]/marc:subfield[@code="a"]|' ||
151             '//marc:datafield[@tag="245"]/marc:subfield[@code="a"]',
152         'marcxml'
153     );
154
155 INSERT INTO config.biblio_fingerprint (name, xpath, format, first_word)
156     VALUES (
157         'Author',
158         '//marc:datafield[@tag="700" and ./*[@code="t"]]/marc:subfield[@code="a"]|'
159             '//marc:datafield[@tag="100"]/marc:subfield[@code="a"]|'
160             '//marc:datafield[@tag="110"]/marc:subfield[@code="a"]|'
161             '//marc:datafield[@tag="111"]/marc:subfield[@code="a"]|'
162             '//marc:datafield[@tag="260"]/marc:subfield[@code="b"]',
163         'marcxml',
164         TRUE
165     );
166
167 CREATE TABLE config.metabib_class (
168     name    TEXT    PRIMARY KEY,
169     label   TEXT    NOT NULL UNIQUE
170 );
171
172 CREATE TABLE config.metabib_field (
173         id              SERIAL  PRIMARY KEY,
174         field_class     TEXT    NOT NULL REFERENCES config.metabib_class (name),
175         name            TEXT    NOT NULL,
176         label           TEXT    NOT NULL,
177         xpath           TEXT    NOT NULL,
178         weight          INT     NOT NULL DEFAULT 1,
179         format          TEXT    NOT NULL REFERENCES config.xml_transform (name) DEFAULT 'mods33',
180         search_field    BOOL    NOT NULL DEFAULT TRUE,
181         facet_field     BOOL    NOT NULL DEFAULT FALSE,
182     facet_xpath TEXT
183 );
184 COMMENT ON TABLE config.metabib_field IS $$
185 XPath used for record indexing ingest
186
187 This table contains the XPath used to chop up MODS into its
188 indexable parts.  Each XPath entry is named and assigned to
189 a "class" of either title, subject, author, keyword, series
190 or identifier.
191 $$;
192
193 CREATE UNIQUE INDEX config_metabib_field_class_name_idx ON config.metabib_field (field_class, name);
194
195 CREATE TABLE config.metabib_search_alias (
196     alias       TEXT    PRIMARY KEY,
197     field_class TEXT    NOT NULL REFERENCES config.metabib_class (name),
198     field       INT     REFERENCES config.metabib_field (id)
199 );
200
201 CREATE TABLE config.non_cataloged_type (
202         id              SERIAL          PRIMARY KEY,
203         owning_lib      INT             NOT NULL, -- REFERENCES actor.org_unit (id),
204         name            TEXT            NOT NULL,
205         circ_duration   INTERVAL        NOT NULL DEFAULT '14 days'::INTERVAL,
206         in_house        BOOL            NOT NULL DEFAULT FALSE,
207         CONSTRAINT noncat_once_per_lib UNIQUE (owning_lib,name)
208 );
209 COMMENT ON TABLE config.non_cataloged_type IS $$
210 Types of valid non-cataloged items.
211 $$;
212
213 CREATE TABLE config.identification_type (
214         id              SERIAL  PRIMARY KEY,
215         name            TEXT    NOT NULL UNIQUE
216 );
217 COMMENT ON TABLE config.identification_type IS $$
218 Types of valid patron identification.
219
220 Each patron must display at least one valid form of identification
221 in order to get a library card.  This table lists those forms.
222 $$;
223
224 CREATE TABLE config.rule_circ_duration (
225         id              SERIAL          PRIMARY KEY,
226         name            TEXT            NOT NULL UNIQUE CHECK ( name ~ E'^\\w+$' ),
227         extended        INTERVAL        NOT NULL,
228         normal          INTERVAL        NOT NULL,
229         shrt            INTERVAL        NOT NULL,
230         max_renewals    INT             NOT NULL
231 );
232 COMMENT ON TABLE config.rule_circ_duration IS $$
233 Circulation Duration rules
234
235 Each circulation is given a duration based on one of these rules.
236 $$;
237
238 CREATE TABLE config.hard_due_date (
239     id                  SERIAL      PRIMARY KEY,
240     name                TEXT        NOT NULL UNIQUE,
241     ceiling_date        TIMESTAMPTZ NOT NULL,
242     forceto             BOOL        NOT NULL,
243     owner               INT         NOT NULL   -- REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
244 );
245
246 CREATE TABLE config.hard_due_date_values (
247     id                  SERIAL      PRIMARY KEY,
248     hard_due_date       INT         NOT NULL REFERENCES config.hard_due_date (id)
249                                     DEFERRABLE INITIALLY DEFERRED,
250     ceiling_date        TIMESTAMPTZ NOT NULL,
251     active_date         TIMESTAMPTZ NOT NULL
252 );
253
254 CREATE OR REPLACE FUNCTION config.update_hard_due_dates () RETURNS INT AS $func$
255 DECLARE
256     temp_value  config.hard_due_date_values%ROWTYPE;
257     updated     INT := 0;
258 BEGIN
259     FOR temp_value IN
260       SELECT  DISTINCT ON (hard_due_date) *
261         FROM  config.hard_due_date_values
262         WHERE active_date <= NOW() -- We've passed (or are at) the rollover time
263         ORDER BY hard_due_date, active_date DESC -- Latest (nearest to us) active time
264    LOOP
265         UPDATE  config.hard_due_date
266           SET   ceiling_date = temp_value.ceiling_date
267           WHERE id = temp_value.hard_due_date
268                 AND ceiling_date <> temp_value.ceiling_date; -- Time is equal if we've already updated the chdd
269
270         IF FOUND THEN
271             updated := updated + 1;
272         END IF;
273     END LOOP;
274
275     RETURN updated;
276 END;
277 $func$ LANGUAGE plpgsql;
278
279 CREATE TABLE config.rule_max_fine (
280     id          SERIAL          PRIMARY KEY,
281     name        TEXT            NOT NULL UNIQUE CHECK ( name ~ E'^\\w+$' ),
282     amount      NUMERIC(6,2)    NOT NULL,
283     is_percent  BOOL            NOT NULL DEFAULT FALSE
284 );
285 COMMENT ON TABLE config.rule_max_fine IS $$
286 Circulation Max Fine rules
287
288 Each circulation is given a maximum fine based on one of
289 these rules.
290 $$;
291
292 CREATE TABLE config.rule_recurring_fine (
293         id                      SERIAL          PRIMARY KEY,
294         name                    TEXT            NOT NULL UNIQUE CHECK ( name ~ E'^\\w+$' ),
295         high                    NUMERIC(6,2)    NOT NULL,
296         normal                  NUMERIC(6,2)    NOT NULL,
297         low                     NUMERIC(6,2)    NOT NULL,
298         recurrence_interval     INTERVAL        NOT NULL DEFAULT '1 day'::INTERVAL,
299     grace_period       INTERVAL         NOT NULL DEFAULT '1 day'::INTERVAL
300 );
301 COMMENT ON TABLE config.rule_recurring_fine IS $$
302 Circulation Recurring Fine rules
303
304 Each circulation is given a recurring fine amount based on one of
305 these rules.  Note that it is recommended to run the fine generator
306 (from cron) at least as frequently as the lowest recurrence interval
307 used by your circulation rules so that accrued fines will be up
308 to date.
309 $$;
310
311
312 CREATE TABLE config.rule_age_hold_protect (
313         id      SERIAL          PRIMARY KEY,
314         name    TEXT            NOT NULL UNIQUE CHECK ( name ~ E'^\\w+$' ),
315         age     INTERVAL        NOT NULL,
316         prox    INT             NOT NULL
317 );
318 COMMENT ON TABLE config.rule_age_hold_protect IS $$
319 Hold Item Age Protection rules
320
321 A hold request can only capture new(ish) items when they are
322 within a particular proximity of the pickup_lib of the request.
323 The proximity ('prox' column) is calculated by counting
324 the number of tree edges between the pickup_lib and either the
325 owning_lib or circ_lib of the copy that could fulfill the hold,
326 as determined by the distance_is_from_owner value of the hold matrix
327 rule controlling the hold request.
328 $$;
329
330 CREATE TABLE config.copy_status (
331         id              SERIAL  PRIMARY KEY,
332         name            TEXT    NOT NULL UNIQUE,
333         holdable        BOOL    NOT NULL DEFAULT FALSE,
334         opac_visible    BOOL    NOT NULL DEFAULT FALSE,
335     copy_active  BOOL    NOT NULL DEFAULT FALSE
336 );
337 COMMENT ON TABLE config.copy_status IS $$
338 Copy Statuses
339
340 The available copy statuses, and whether a copy in that
341 status is available for hold request capture.  0 (zero) is
342 the only special number in this set, meaning that the item
343 is available for immediate checkout, and is counted as available
344 in the OPAC.
345
346 Statuses with an ID below 100 are not removable, and have special
347 meaning in the code.  Do not change them except to translate the
348 textual name.
349
350 You may add and remove statuses above 100, and these can be used
351 to remove items from normal circulation without affecting the rest
352 of the copy's values or its location.
353 $$;
354
355 CREATE TABLE config.net_access_level (
356         id      SERIAL          PRIMARY KEY,
357         name    TEXT            NOT NULL UNIQUE
358 );
359 COMMENT ON TABLE config.net_access_level IS $$
360 Patron Network Access level
361
362 This will be used to inform the in-library firewall of how much
363 internet access the using patron should be allowed.
364 $$;
365
366
367 CREATE TABLE config.remote_account (
368     id          SERIAL  PRIMARY KEY,
369     label       TEXT    NOT NULL,
370     host        TEXT    NOT NULL,   -- name or IP, :port optional
371     username    TEXT,               -- optional, since we could default to $USER
372     password    TEXT,               -- optional, since we could use SSH keys, or anonymous login.
373     account     TEXT,               -- aka profile or FTP "account" command
374     path        TEXT,               -- aka directory
375     owner       INT     NOT NULL,   -- REFERENCES actor.org_unit (id) DEFERRABLE INITIALLY DEFERRED,
376     last_activity TIMESTAMP WITH TIME ZONE
377 );
378
379 CREATE TABLE config.marc21_rec_type_map (
380     code        TEXT    PRIMARY KEY,
381     type_val    TEXT    NOT NULL,
382     blvl_val    TEXT    NOT NULL
383 );
384
385 CREATE TABLE config.marc21_ff_pos_map (
386     id          SERIAL  PRIMARY KEY,
387     fixed_field TEXT    NOT NULL,
388     tag         TEXT    NOT NULL,
389     rec_type    TEXT    NOT NULL,
390     start_pos   INT     NOT NULL,
391     length      INT     NOT NULL,
392     default_val TEXT    NOT NULL DEFAULT ' '
393 );
394
395 CREATE TABLE config.marc21_physical_characteristic_type_map (
396     ptype_key   TEXT    PRIMARY KEY,
397     label       TEXT    NOT NULL -- I18N
398 );
399
400 CREATE TABLE config.marc21_physical_characteristic_subfield_map (
401     id          SERIAL  PRIMARY KEY,
402     ptype_key   TEXT    NOT NULL REFERENCES config.marc21_physical_characteristic_type_map (ptype_key) ON DELETE CASCADE ON UPDATE CASCADE,
403     subfield    TEXT    NOT NULL,
404     start_pos   INT     NOT NULL,
405     length      INT     NOT NULL,
406     label       TEXT    NOT NULL -- I18N
407 );
408
409 CREATE TABLE config.marc21_physical_characteristic_value_map (
410     id              SERIAL  PRIMARY KEY,
411     value           TEXT    NOT NULL,
412     ptype_subfield  INT     NOT NULL REFERENCES config.marc21_physical_characteristic_subfield_map (id),
413     label           TEXT    NOT NULL -- I18N
414 );
415
416
417 CREATE TABLE config.z3950_source (
418     name                TEXT    PRIMARY KEY,
419     label               TEXT    NOT NULL UNIQUE,
420     host                TEXT    NOT NULL,
421     port                INT     NOT NULL,
422     db                  TEXT    NOT NULL,
423     record_format       TEXT    NOT NULL DEFAULT 'FI',
424     transmission_format TEXT    NOT NULL DEFAULT 'usmarc',
425     auth                BOOL    NOT NULL DEFAULT TRUE,
426     use_perm            INT     -- REFERENCES permission.perm_list (id)
427 );
428
429 COMMENT ON TABLE config.z3950_source IS $$
430 Z39.50 Sources
431
432 Each row in this table represents a database searchable via Z39.50.
433 $$;
434
435 COMMENT ON COLUMN config.z3950_source.record_format IS $$
436 Z39.50 element set.
437 $$;
438
439 COMMENT ON COLUMN config.z3950_source.transmission_format IS $$
440 Z39.50 preferred record syntax..
441 $$;
442
443 COMMENT ON COLUMN config.z3950_source.use_perm IS $$
444 If set, this permission is required for the source to be listed in the staff
445 client Z39.50 interface.  Similar to permission.grp_tree.application_perm.
446 $$;
447
448 CREATE TABLE config.z3950_attr (
449     id          SERIAL  PRIMARY KEY,
450     source      TEXT    NOT NULL REFERENCES config.z3950_source (name) DEFERRABLE INITIALLY DEFERRED,
451     name        TEXT    NOT NULL,
452     label       TEXT    NOT NULL,
453     code        INT     NOT NULL,
454     format      INT     NOT NULL,
455     truncation  INT     NOT NULL DEFAULT 0,
456     CONSTRAINT z_code_format_once_per_source UNIQUE (code,format,source)
457 );
458
459 CREATE TABLE config.i18n_locale (
460     code        TEXT    PRIMARY KEY,
461     marc_code   TEXT    NOT NULL, -- should exist in config.coded_value_map WHERE ctype = 'item_lang'
462     name        TEXT    UNIQUE NOT NULL,
463     description TEXT
464 );
465
466 CREATE TABLE config.i18n_core (
467     id              BIGSERIAL   PRIMARY KEY,
468     fq_field        TEXT        NOT NULL,
469     identity_value  TEXT        NOT NULL,
470     translation     TEXT        NOT NULL    REFERENCES config.i18n_locale (code) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
471     string          TEXT        NOT NULL
472 );
473
474 CREATE UNIQUE INDEX i18n_identity ON config.i18n_core (fq_field,identity_value,translation);
475
476 CREATE OR REPLACE FUNCTION oils_i18n_update_apply(old_ident TEXT, new_ident TEXT, hint TEXT) RETURNS VOID AS $_$
477 BEGIN
478
479     EXECUTE $$
480         UPDATE  config.i18n_core
481           SET   identity_value = $$ || quote_literal(new_ident) || $$ 
482           WHERE fq_field LIKE '$$ || hint || $$.%' 
483                 AND identity_value = $$ || quote_literal(old_ident) || $$::TEXT;$$;
484
485     RETURN;
486
487 END;
488 $_$ LANGUAGE PLPGSQL;
489
490 CREATE OR REPLACE FUNCTION oils_i18n_id_tracking(/* hint */) RETURNS TRIGGER AS $_$
491 BEGIN
492     PERFORM oils_i18n_update_apply( OLD.id::TEXT, NEW.id::TEXT, TG_ARGV[0]::TEXT );
493     RETURN NEW;
494 END;
495 $_$ LANGUAGE PLPGSQL;
496
497 CREATE OR REPLACE FUNCTION oils_i18n_code_tracking(/* hint */) RETURNS TRIGGER AS $_$
498 BEGIN
499     PERFORM oils_i18n_update_apply( OLD.code::TEXT, NEW.code::TEXT, TG_ARGV[0]::TEXT );
500     RETURN NEW;
501 END;
502 $_$ LANGUAGE PLPGSQL;
503
504 CREATE TABLE config.billing_type (
505     id              SERIAL  PRIMARY KEY,
506     name            TEXT    NOT NULL,
507     owner           INT     NOT NULL, -- REFERENCES actor.org_unit (id)
508     default_price   NUMERIC(6,2),
509     CONSTRAINT billing_type_once_per_lib UNIQUE (name, owner)
510 );
511
512 CREATE TABLE config.settings_group (
513     name    TEXT PRIMARY KEY,
514     label   TEXT UNIQUE NOT NULL -- I18N
515 );
516
517 CREATE TABLE config.org_unit_setting_type (
518     name            TEXT    PRIMARY KEY,
519     label           TEXT    UNIQUE NOT NULL,
520     grp             TEXT    REFERENCES config.settings_group (name),
521     description     TEXT,
522     datatype        TEXT    NOT NULL DEFAULT 'string',
523     fm_class        TEXT,
524     view_perm       INT,
525     update_perm     INT,
526     --
527     -- define valid datatypes
528     --
529     CONSTRAINT coust_valid_datatype CHECK ( datatype IN
530     ( 'bool', 'integer', 'float', 'currency', 'interval',
531       'date', 'string', 'object', 'array', 'link' ) ),
532     --
533     -- fm_class is meaningful only for 'link' datatype
534     --
535     CONSTRAINT coust_no_empty_link CHECK
536     ( ( datatype =  'link' AND fm_class IS NOT NULL ) OR
537       ( datatype <> 'link' AND fm_class IS NULL ) )
538 );
539
540 CREATE TABLE config.usr_setting_type (
541
542     name TEXT PRIMARY KEY,
543     opac_visible BOOL NOT NULL DEFAULT FALSE,
544     label TEXT UNIQUE NOT NULL,
545     description TEXT,
546     grp             TEXT    REFERENCES config.settings_group (name),
547     datatype TEXT NOT NULL DEFAULT 'string',
548     fm_class TEXT,
549
550     --
551     -- define valid datatypes
552     --
553     CONSTRAINT coust_valid_datatype CHECK ( datatype IN
554     ( 'bool', 'integer', 'float', 'currency', 'interval',
555         'date', 'string', 'object', 'array', 'link' ) ),
556
557     --
558     -- fm_class is meaningful only for 'link' datatype
559     --
560     CONSTRAINT coust_no_empty_link CHECK
561     ( ( datatype = 'link' AND fm_class IS NOT NULL ) OR
562         ( datatype <> 'link' AND fm_class IS NULL ) )
563
564 );
565
566 -- Some handy functions, based on existing ones, to provide optional ingest normalization
567
568 CREATE OR REPLACE FUNCTION public.left_trunc( TEXT, INT ) RETURNS TEXT AS $func$
569         SELECT SUBSTRING($1,$2);
570 $func$ LANGUAGE SQL STRICT IMMUTABLE;
571
572 CREATE OR REPLACE FUNCTION public.right_trunc( TEXT, INT ) RETURNS TEXT AS $func$
573         SELECT SUBSTRING($1,1,$2);
574 $func$ LANGUAGE SQL STRICT IMMUTABLE;
575
576 CREATE OR REPLACE FUNCTION public.split_date_range( TEXT ) RETURNS TEXT AS $func$
577         SELECT REGEXP_REPLACE( $1, E'(\\d{4})-(\\d{4})', E'\\1 \\2', 'g' );
578 $func$ LANGUAGE SQL STRICT IMMUTABLE;
579
580 CREATE OR REPLACE FUNCTION public.approximate_date( TEXT, TEXT ) RETURNS TEXT AS $func$
581         SELECT REGEXP_REPLACE( $1, E'\\D', $2, 'g' );
582 $func$ LANGUAGE SQL STRICT IMMUTABLE;
583
584 CREATE OR REPLACE FUNCTION public.approximate_low_date( TEXT ) RETURNS TEXT AS $func$
585         SELECT approximate_date( $1, '0');
586 $func$ LANGUAGE SQL STRICT IMMUTABLE;
587
588 CREATE OR REPLACE FUNCTION public.approximate_high_date( TEXT ) RETURNS TEXT AS $func$
589         SELECT approximate_date( $1, '9');
590 $func$ LANGUAGE SQL STRICT IMMUTABLE;
591
592 CREATE OR REPLACE FUNCTION public.content_or_null( TEXT ) RETURNS TEXT AS $func$
593         SELECT CASE WHEN $1 ~ E'^\\s*$' THEN NULL ELSE $1 END
594 $func$ LANGUAGE SQL STRICT IMMUTABLE;
595
596 CREATE OR REPLACE FUNCTION public.integer_or_null( TEXT ) RETURNS TEXT AS $func$
597         SELECT CASE WHEN $1 ~ E'^\\d+$' THEN $1 ELSE NULL END
598 $func$ LANGUAGE SQL STRICT IMMUTABLE;
599
600 CREATE OR REPLACE FUNCTION public.force_to_isbn13( TEXT ) RETURNS TEXT AS $func$
601     use Business::ISBN;
602     use strict;
603     use warnings;
604
605     # Find the first ISBN, force it to ISBN13 and return it
606
607     my $input = shift;
608
609     foreach my $word (split(/\s/, $input)) {
610         my $isbn = Business::ISBN->new($word);
611
612         # First check the checksum; if it is not valid, fix it and add the original
613         # bad-checksum ISBN to the output
614         if ($isbn && $isbn->is_valid_checksum() == Business::ISBN::BAD_CHECKSUM) {
615             $isbn->fix_checksum();
616         }
617
618         # If we now have a valid ISBN, force it to ISBN13 and return it
619         return $isbn->as_isbn13->isbn if ($isbn && $isbn->is_valid());
620     }
621     return undef;
622 $func$ LANGUAGE PLPERLU;
623
624 COMMENT ON FUNCTION public.force_to_isbn13(TEXT) IS $$
625 Inspired by translate_isbn1013
626
627 The force_to_isbn13 function takes an input ISBN and returns the ISBN13
628 version without hypens and with a repaired checksum if the checksum was bad
629 $$;
630
631
632 CREATE OR REPLACE FUNCTION public.translate_isbn1013( TEXT ) RETURNS TEXT AS $func$
633     use Business::ISBN;
634     use strict;
635     use warnings;
636
637     # For each ISBN found in a single string containing a set of ISBNs:
638     #   * Normalize an incoming ISBN to have the correct checksum and no hyphens
639     #   * Convert an incoming ISBN10 or ISBN13 to its counterpart and return
640
641     my $input = shift;
642     my $output = '';
643
644     foreach my $word (split(/\s/, $input)) {
645         my $isbn = Business::ISBN->new($word);
646
647         # First check the checksum; if it is not valid, fix it and add the original
648         # bad-checksum ISBN to the output
649         if ($isbn && $isbn->is_valid_checksum() == Business::ISBN::BAD_CHECKSUM) {
650             $output .= $isbn->isbn() . " ";
651             $isbn->fix_checksum();
652         }
653
654         # If we now have a valid ISBN, convert it to its counterpart ISBN10/ISBN13
655         # and add the normalized original ISBN to the output
656         if ($isbn && $isbn->is_valid()) {
657             my $isbn_xlated = ($isbn->type eq "ISBN13") ? $isbn->as_isbn10 : $isbn->as_isbn13;
658             $output .= $isbn->isbn . " ";
659
660             # If we successfully converted the ISBN to its counterpart, add the
661             # converted ISBN to the output as well
662             $output .= ($isbn_xlated->isbn . " ") if ($isbn_xlated);
663         }
664     }
665     return $output if $output;
666
667     # If there were no valid ISBNs, just return the raw input
668     return $input;
669 $func$ LANGUAGE PLPERLU;
670
671 COMMENT ON FUNCTION public.translate_isbn1013(TEXT) IS $$
672 The translate_isbn1013 function takes an input ISBN and returns the
673 following in a single space-delimited string if the input ISBN is valid:
674   - The normalized input ISBN (hyphens stripped)
675   - The normalized input ISBN with a fixed checksum if the checksum was bad
676   - The ISBN converted to its ISBN10 or ISBN13 counterpart, if possible
677 $$;
678
679 -- And ... a table in which to register them
680
681 CREATE TABLE config.index_normalizer (
682         id              SERIAL  PRIMARY KEY,
683         name            TEXT    UNIQUE NOT NULL,
684         description     TEXT,
685         func            TEXT    NOT NULL,
686         param_count     INT     NOT NULL DEFAULT 0
687 );
688
689 CREATE TABLE config.metabib_field_index_norm_map (
690         id      SERIAL  PRIMARY KEY,
691         field   INT     NOT NULL REFERENCES config.metabib_field (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
692         norm    INT     NOT NULL REFERENCES config.index_normalizer (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
693         params  TEXT,
694         pos     INT     NOT NULL DEFAULT 0
695 );
696
697 CREATE TABLE config.record_attr_definition (
698     name        TEXT    PRIMARY KEY,
699     label       TEXT    NOT NULL, -- I18N
700     description TEXT,
701     filter      BOOL    NOT NULL DEFAULT TRUE,  -- becomes QP filter if true
702     sorter      BOOL    NOT NULL DEFAULT FALSE, -- becomes QP sort() axis if true
703
704 -- For pre-extracted fields. Takes the first occurance, uses naive subfield ordering
705     tag         TEXT, -- LIKE format
706     sf_list     TEXT, -- pile-o-values, like 'abcd' for a and b and c and d
707
708 -- This is used for both tag/sf and xpath entries
709     joiner      TEXT,
710
711 -- For xpath-extracted attrs
712     xpath       TEXT,
713     format      TEXT    REFERENCES config.xml_transform (name) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
714     start_pos   INT,
715     string_len  INT,
716
717 -- For fixed fields
718     fixed_field TEXT, -- should exist in config.marc21_ff_pos_map.fixed_field
719
720 -- For phys-char fields
721     phys_char_sf    INT REFERENCES config.marc21_physical_characteristic_subfield_map (id)
722 );
723
724 CREATE TABLE config.record_attr_index_norm_map (
725     id      SERIAL  PRIMARY KEY,
726     attr    TEXT    NOT NULL REFERENCES config.record_attr_definition (name) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
727     norm    INT     NOT NULL REFERENCES config.index_normalizer (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
728     params  TEXT,
729     pos     INT     NOT NULL DEFAULT 0
730 );
731
732 CREATE TABLE config.coded_value_map (
733     id          SERIAL  PRIMARY KEY,
734     ctype       TEXT    NOT NULL REFERENCES config.record_attr_definition (name) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
735     code        TEXT    NOT NULL,
736     value       TEXT    NOT NULL,
737     description TEXT
738 );
739
740 CREATE VIEW config.language_map AS SELECT code, value FROM config.coded_value_map WHERE ctype = 'item_lang';
741 CREATE VIEW config.bib_level_map AS SELECT code, value FROM config.coded_value_map WHERE ctype = 'bib_level';
742 CREATE VIEW config.item_form_map AS SELECT code, value FROM config.coded_value_map WHERE ctype = 'item_form';
743 CREATE VIEW config.item_type_map AS SELECT code, value FROM config.coded_value_map WHERE ctype = 'item_type';
744 CREATE VIEW config.lit_form_map AS SELECT code, value, description FROM config.coded_value_map WHERE ctype = 'lit_form';
745 CREATE VIEW config.audience_map AS SELECT code, value, description FROM config.coded_value_map WHERE ctype = 'audience';
746 CREATE VIEW config.videorecording_format_map AS SELECT code, value FROM config.coded_value_map WHERE ctype = 'vr_format';
747
748 CREATE OR REPLACE FUNCTION oils_tsearch2 () RETURNS TRIGGER AS $$
749 DECLARE
750     normalizer      RECORD;
751     value           TEXT := '';
752 BEGIN
753
754     value := NEW.value;
755
756     IF TG_TABLE_NAME::TEXT ~ 'field_entry$' THEN
757         FOR normalizer IN
758             SELECT  n.func AS func,
759                     n.param_count AS param_count,
760                     m.params AS params
761               FROM  config.index_normalizer n
762                     JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
763               WHERE field = NEW.field AND m.pos < 0
764               ORDER BY m.pos LOOP
765                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
766                     quote_literal( value ) ||
767                     CASE
768                         WHEN normalizer.param_count > 0
769                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
770                             ELSE ''
771                         END ||
772                     ')' INTO value;
773
774         END LOOP;
775
776         NEW.value := value;
777     END IF;
778
779     IF NEW.index_vector = ''::tsvector THEN
780         RETURN NEW;
781     END IF;
782
783     IF TG_TABLE_NAME::TEXT ~ 'field_entry$' THEN
784         FOR normalizer IN
785             SELECT  n.func AS func,
786                     n.param_count AS param_count,
787                     m.params AS params
788               FROM  config.index_normalizer n
789                     JOIN config.metabib_field_index_norm_map m ON (m.norm = n.id)
790               WHERE field = NEW.field AND m.pos >= 0
791               ORDER BY m.pos LOOP
792                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
793                     quote_literal( value ) ||
794                     CASE
795                         WHEN normalizer.param_count > 0
796                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
797                             ELSE ''
798                         END ||
799                     ')' INTO value;
800
801         END LOOP;
802     END IF;
803
804     IF REGEXP_REPLACE(VERSION(),E'^.+?(\\d+\\.\\d+).*?$',E'\\1')::FLOAT > 8.2 THEN
805         NEW.index_vector = to_tsvector((TG_ARGV[0])::regconfig, value);
806     ELSE
807         NEW.index_vector = to_tsvector(TG_ARGV[0], value);
808     END IF;
809
810     RETURN NEW;
811 END;
812 $$ LANGUAGE PLPGSQL;
813
814 -- List applied db patches that are deprecated by (and block the application of) my_db_patch
815 CREATE OR REPLACE FUNCTION evergreen.upgrade_list_applied_deprecates ( my_db_patch TEXT ) RETURNS SETOF evergreen.patch AS $$
816     SELECT  DISTINCT l.version
817       FROM  config.upgrade_log l
818             JOIN config.db_patch_dependencies d ON (l.version::TEXT[] && d.deprecates)
819       WHERE d.db_patch = $1
820 $$ LANGUAGE SQL;
821
822 -- List applied db patches that are superseded by (and block the application of) my_db_patch
823 CREATE OR REPLACE FUNCTION evergreen.upgrade_list_applied_supersedes ( my_db_patch TEXT ) RETURNS SETOF evergreen.patch AS $$
824     SELECT  DISTINCT l.version
825       FROM  config.upgrade_log l
826             JOIN config.db_patch_dependencies d ON (l.version::TEXT[] && d.supersedes)
827       WHERE d.db_patch = $1
828 $$ LANGUAGE SQL;
829
830 -- List applied db patches that deprecates (and block the application of) my_db_patch
831 CREATE FUNCTION evergreen.upgrade_list_applied_deprecated ( my_db_patch TEXT ) RETURNS SETOF TEXT AS $$
832     SELECT  db_patch
833       FROM  config.db_patch_dependencies
834       WHERE ARRAY[$1]::TEXT[] && deprecates
835 $$ LANGUAGE SQL;
836
837 -- List applied db patches that supersedes (and block the application of) my_db_patch
838 CREATE FUNCTION evergreen.upgrade_list_applied_superseded ( my_db_patch TEXT ) RETURNS SETOF TEXT AS $$
839     SELECT  db_patch
840       FROM  config.db_patch_dependencies
841       WHERE ARRAY[$1]::TEXT[] && supersedes
842 $$ LANGUAGE SQL;
843
844 -- Make sure that no deprecated or superseded db patches are currently applied
845 CREATE OR REPLACE FUNCTION evergreen.upgrade_verify_no_dep_conflicts ( my_db_patch TEXT ) RETURNS BOOL AS $$
846     SELECT  COUNT(*) = 0
847       FROM  (SELECT * FROM evergreen.upgrade_list_applied_deprecates( $1 )
848                 UNION
849              SELECT * FROM evergreen.upgrade_list_applied_supersedes( $1 )
850                 UNION
851              SELECT * FROM evergreen.upgrade_list_applied_deprecated( $1 )
852                 UNION
853              SELECT * FROM evergreen.upgrade_list_applied_superseded( $1 ))x
854 $$ LANGUAGE SQL;
855
856 -- Raise an exception if there are, in fact, dep/sup conflict
857 CREATE OR REPLACE FUNCTION evergreen.upgrade_deps_block_check ( my_db_patch TEXT, my_applied_to TEXT ) RETURNS BOOL AS $$
858 DECLARE 
859     deprecates TEXT;
860     supersedes TEXT;
861 BEGIN
862     IF NOT evergreen.upgrade_verify_no_dep_conflicts( my_db_patch ) THEN
863         SELECT  STRING_AGG(patch, ', ') INTO deprecates FROM evergreen.upgrade_list_applied_deprecates(my_db_patch);
864         SELECT  STRING_AGG(patch, ', ') INTO supersedes FROM evergreen.upgrade_list_applied_supersedes(my_db_patch);
865         RAISE EXCEPTION '
866 Upgrade script % can not be applied:
867   applied deprecated scripts %
868   applied superseded scripts %
869   deprecated by %
870   superseded by %',
871             my_db_patch,
872             ARRAY_AGG(evergreen.upgrade_list_applied_deprecates(my_db_patch)),
873             ARRAY_AGG(evergreen.upgrade_list_applied_supersedes(my_db_patch)),
874             evergreen.upgrade_list_applied_deprecated(my_db_patch),
875             evergreen.upgrade_list_applied_superseded(my_db_patch);
876     END IF;
877
878     INSERT INTO config.upgrade_log (version, applied_to) VALUES (my_db_patch, my_applied_to);
879     RETURN TRUE;
880 END;
881 $$ LANGUAGE PLPGSQL;
882
883 CREATE TABLE config.barcode_completion (
884     id          SERIAL PRIMARY KEY,
885     active      BOOL NOT NULL DEFAULT true,
886     org_unit    INT NOT NULL, -- REFERENCES actor.org_unit(id) DEFERRABLE INITIALLY DEFERRED,
887     prefix      TEXT,
888     suffix      TEXT,
889     length      INT NOT NULL DEFAULT 0,
890     padding     TEXT,
891     padding_end BOOL NOT NULL DEFAULT false,
892     asset       BOOL NOT NULL DEFAULT true,
893     actor       BOOL NOT NULL DEFAULT true
894 );
895
896 CREATE TYPE evergreen.barcode_set AS (type TEXT, id BIGINT, barcode TEXT);
897
898 -- Add support for logging, only keep the most recent five rows for each category. 
899
900
901 CREATE TABLE config.org_unit_setting_type_log (
902     id              BIGSERIAL   PRIMARY KEY,
903     date_applied    TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
904     org             INT,   --REFERENCES actor.org_unit (id),
905     original_value  TEXT,
906     new_value       TEXT,
907     field_name      TEXT      REFERENCES config.org_unit_setting_type (name)
908 );
909
910 COMMENT ON TABLE config.org_unit_setting_type_log IS $$
911 Org Unit setting Logs
912
913 This table contains the most recent changes to each setting 
914 in actor.org_unit_setting, allowing for mistakes to be undone.
915 This is NOT meant to be an auditor, but rather an undo/redo.
916 $$;
917
918 CREATE OR REPLACE FUNCTION limit_oustl() RETURNS TRIGGER AS $oustl_limit$
919     BEGIN
920         -- Only keeps the most recent five settings changes.
921         DELETE FROM config.org_unit_setting_type_log WHERE field_name = NEW.field_name AND date_applied NOT IN 
922         (SELECT date_applied FROM config.org_unit_setting_type_log WHERE field_name = NEW.field_name ORDER BY date_applied DESC LIMIT 4);
923         
924         IF (TG_OP = 'UPDATE') THEN
925             RETURN NEW;
926         ELSIF (TG_OP = 'INSERT') THEN
927             RETURN NEW;
928         END IF;
929         RETURN NULL;
930     END;
931 $oustl_limit$ LANGUAGE plpgsql;
932
933 CREATE TRIGGER limit_logs_oust
934     BEFORE INSERT OR UPDATE ON config.org_unit_setting_type_log
935     FOR EACH ROW EXECUTE PROCEDURE limit_oustl();
936
937 CREATE TABLE config.sms_carrier (
938     id              SERIAL PRIMARY KEY,
939     region          TEXT,
940     name            TEXT,
941     email_gateway   TEXT,
942     active          BOOLEAN DEFAULT TRUE
943 );
944
945 COMMIT;