]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/020.schema.functions.sql
quickly, before anyone notices ... minor speed enhancement (aka, thinko)
[Evergreen.git] / Open-ILS / src / sql / Pg / 020.schema.functions.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 CREATE OR REPLACE FUNCTION public.non_filing_normalize ( TEXT, "char" ) RETURNS TEXT AS $$
19         SELECT  SUBSTRING(
20                         REGEXP_REPLACE(
21                                 REGEXP_REPLACE(
22                                         $1,
23                                         E'\W*$',
24                                         ''
25                                 ),
26                                 '  ',
27                                 ' '
28                         ),
29                         CASE
30                                 WHEN $2::INT NOT BETWEEN 48 AND 57 THEN 1
31                                 ELSE $2::TEXT::INT + 1
32                         END
33                 );
34 $$ LANGUAGE SQL STRICT IMMUTABLE;
35
36 CREATE OR REPLACE FUNCTION public.naco_normalize( TEXT, TEXT ) RETURNS TEXT AS $func$
37         use Unicode::Normalize;
38         use Encode;
39
40         # When working with Unicode data, the first step is to decode it to
41         # a byte string; after that, lowercasing is safe
42         my $txt = lc(decode_utf8(shift));
43         my $sf = shift;
44
45         $txt = NFD($txt);
46         $txt =~ s/\pM+//go;     # Remove diacritics
47
48         $txt =~ s/\xE6/AE/go;   # Convert ae digraph
49         $txt =~ s/\x{153}/OE/go;# Convert oe digraph
50         $txt =~ s/\xFE/TH/go;   # Convert Icelandic thorn
51
52         $txt =~ tr/\x{2070}\x{2071}\x{2072}\x{2073}\x{2074}\x{2075}\x{2076}\x{2077}\x{2078}\x{2079}\x{207A}\x{207B}/0123456789+-/;# Convert superscript numbers
53         $txt =~ tr/\x{2080}\x{2081}\x{2082}\x{2083}\x{2084}\x{2085}\x{2086}\x{2087}\x{2088}\x{2089}\x{208A}\x{208B}/0123456889+-/;# Convert subscript numbers
54
55         $txt =~ tr/\x{0251}\x{03B1}\x{03B2}\x{0262}\x{03B3}/AABGG/;             # Convert Latin and Greek
56         $txt =~ tr/\x{2113}\xF0\x{111}\!\"\(\)\-\{\}\<\>\;\:\.\?\xA1\xBF\/\\\@\*\%\=\xB1\+\xAE\xA9\x{2117}\$\xA3\x{FFE1}\xB0\^\_\~\`/LDD /;     # Convert Misc
57         $txt =~ tr/\'\[\]\|//d;                                                 # Remove Misc
58
59         if ($sf && $sf =~ /^a/o) {
60                 my $commapos = index($txt,',');
61                 if ($commapos > -1) {
62                         if ($commapos != length($txt) - 1) {
63                                 my @list = split /,/, $txt;
64                                 my $first = shift @list;
65                                 $txt = $first . ',' . join(' ', @list);
66                         } else {
67                                 $txt =~ s/,/ /go;
68                         }
69                 }
70         } else {
71                 $txt =~ s/,/ /go;
72         }
73
74         $txt =~ s/\s+/ /go;     # Compress multiple spaces
75         $txt =~ s/^\s+//o;      # Remove leading space
76         $txt =~ s/\s+$//o;      # Remove trailing space
77
78         # Encoding the outgoing string is good practice, but not strictly
79         # necessary in this case because we've stripped everything from it
80         return encode_utf8($txt);
81 $func$ LANGUAGE 'plperlu' STRICT IMMUTABLE;
82
83 CREATE OR REPLACE FUNCTION public.naco_normalize( TEXT ) RETURNS TEXT AS $func$
84         SELECT public.naco_normalize($1,'');
85 $func$ LANGUAGE 'sql' STRICT IMMUTABLE;
86
87 CREATE OR REPLACE FUNCTION public.first_word ( TEXT ) RETURNS TEXT AS $$
88         SELECT COALESCE(SUBSTRING( $1 FROM $_$^\S+$_$), '');
89 $$ LANGUAGE SQL STRICT IMMUTABLE;
90
91 CREATE OR REPLACE FUNCTION public.naco_normalize_keep_comma( TEXT ) RETURNS TEXT AS $func$
92         SELECT public.naco_normalize($1,'a');
93 $func$ LANGUAGE SQL STRICT IMMUTABLE;
94
95 CREATE OR REPLACE FUNCTION public.normalize_space( TEXT ) RETURNS TEXT AS $$
96     SELECT regexp_replace(regexp_replace(regexp_replace($1, E'\\n', ' ', 'g'), E'(?:^\\s+)|(\\s+$)', '', 'g'), E'\\s+', ' ', 'g');
97 $$ LANGUAGE SQL STRICT IMMUTABLE;
98
99 CREATE OR REPLACE FUNCTION public.remove_commas( TEXT ) RETURNS TEXT AS $$
100     SELECT regexp_replace($1, ',', '', 'g');
101 $$ LANGUAGE SQL STRICT IMMUTABLE;
102
103 CREATE OR REPLACE FUNCTION public.remove_paren_substring( TEXT ) RETURNS TEXT AS $func$
104     SELECT regexp_replace($1, $$\([^)]+\)$$, '', 'g');
105 $func$ LANGUAGE SQL STRICT IMMUTABLE;
106
107 CREATE OR REPLACE FUNCTION public.remove_whitespace( TEXT ) RETURNS TEXT AS $$
108     SELECT regexp_replace(normalize_space($1), E'\\s+', '', 'g');
109 $$ LANGUAGE SQL STRICT IMMUTABLE;
110
111 CREATE OR REPLACE FUNCTION public.lowercase( TEXT ) RETURNS TEXT AS $$
112     return lc(shift);
113 $$ LANGUAGE PLPERLU STRICT IMMUTABLE;
114
115 CREATE OR REPLACE FUNCTION public.uppercase( TEXT ) RETURNS TEXT AS $$
116     return uc(shift);
117 $$ LANGUAGE PLPERLU STRICT IMMUTABLE;
118
119 CREATE OR REPLACE FUNCTION public.remove_diacritics( TEXT ) RETURNS TEXT AS $$
120     use Unicode::Normalize;
121
122     my $x = NFD(shift);
123     $x =~ s/\pM+//go;
124     return $x;
125
126 $$ LANGUAGE PLPERLU STRICT IMMUTABLE;
127
128 CREATE OR REPLACE FUNCTION public.entityize( TEXT ) RETURNS TEXT AS $$
129     use Unicode::Normalize;
130
131     my $x = NFC(shift);
132     $x =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
133     return $x;
134
135 $$ LANGUAGE PLPERLU STRICT IMMUTABLE;
136
137 CREATE OR REPLACE FUNCTION public.call_number_dewey( TEXT ) RETURNS TEXT AS $$
138         my $txt = shift;
139         $txt =~ s/^\s+//o;
140         $txt =~ s/[\[\]\{\}\(\)`'"#<>\*\?\-\+\$\\]+//og;
141         $txt =~ s/\s+$//o;
142         if ($txt =~ /(\d{3}(?:\.\d+)?)/o) {
143                 return $1;
144         } else {
145                 return (split /\s+/, $txt)[0];
146         }
147 $$ LANGUAGE 'plperlu' STRICT IMMUTABLE;
148
149 CREATE OR REPLACE FUNCTION public.call_number_dewey( TEXT, INT ) RETURNS TEXT AS $$
150         SELECT SUBSTRING(call_number_dewey($1) FROM 1 FOR $2);
151 $$ LANGUAGE SQL STRICT IMMUTABLE;
152
153 CREATE OR REPLACE FUNCTION tableoid2name ( oid ) RETURNS TEXT AS $$
154         BEGIN
155                 RETURN $1::regclass;
156         END;
157 $$ language 'plpgsql';
158
159 CREATE OR REPLACE FUNCTION actor.org_unit_descendants( INT, INT ) RETURNS SETOF actor.org_unit AS $$
160     WITH RECURSIVE descendant_depth AS (
161         SELECT  ou.id,
162                 ou.parent_ou,
163                 out.depth
164           FROM  actor.org_unit ou
165                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
166                 JOIN anscestor_depth ad ON (ad.id = ou.id)
167           WHERE ad.depth = $2
168             UNION ALL
169         SELECT  ou.id,
170                 ou.parent_ou,
171                 out.depth
172           FROM  actor.org_unit ou
173                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
174                 JOIN descendant_depth ot ON (ot.id = ou.parent_ou)
175     ), anscestor_depth AS (
176         SELECT  ou.id,
177                 ou.parent_ou,
178                 out.depth
179           FROM  actor.org_unit ou
180                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
181           WHERE ou.id = $1
182             UNION ALL
183         SELECT  ou.id,
184                 ou.parent_ou,
185                 out.depth
186           FROM  actor.org_unit ou
187                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
188                 JOIN anscestor_depth ot ON (ot.parent_ou = ou.id)
189     ) SELECT ou.* FROM actor.org_unit ou JOIN descendant_depth USING (id);
190 $$ LANGUAGE SQL;
191
192 CREATE OR REPLACE FUNCTION actor.org_unit_descendants( INT ) RETURNS SETOF actor.org_unit AS $$
193     WITH RECURSIVE descendant_depth AS (
194         SELECT  ou.id,
195                 ou.parent_ou,
196                 out.depth
197           FROM  actor.org_unit ou
198                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
199           WHERE ou.id = $1
200             UNION ALL
201         SELECT  ou.id,
202                 ou.parent_ou,
203                 out.depth
204           FROM  actor.org_unit ou
205                 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
206                 JOIN descendant_depth ot ON (ot.id = ou.parent_ou)
207     ) SELECT ou.* FROM actor.org_unit ou JOIN descendant_depth USING (id);
208 $$ LANGUAGE SQL;
209
210 CREATE OR REPLACE FUNCTION actor.org_unit_ancestors( INT ) RETURNS SETOF actor.org_unit AS $$
211     WITH RECURSIVE anscestor_depth AS (
212         SELECT  ou.id,
213                 ou.parent_ou
214           FROM  actor.org_unit ou
215           WHERE ou.id = $1
216             UNION ALL
217         SELECT  ou.id,
218                 ou.parent_ou
219           FROM  actor.org_unit ou
220                 JOIN anscestor_depth ot ON (ot.parent_ou = ou.id)
221     ) SELECT ou.* FROM actor.org_unit ou JOIN anscestor_depth USING (id);
222 $$ LANGUAGE SQL;
223
224 CREATE OR REPLACE FUNCTION actor.org_unit_ancestor_at_depth ( INT,INT ) RETURNS actor.org_unit AS $$
225         SELECT  a.*
226           FROM  actor.org_unit a
227           WHERE id = ( SELECT FIRST(x.id)
228                          FROM   actor.org_unit_ancestors($1) x
229                                 JOIN actor.org_unit_type y
230                                         ON x.ou_type = y.id AND y.depth = $2);
231 $$ LANGUAGE SQL STABLE;
232
233 CREATE OR REPLACE FUNCTION actor.org_unit_full_path ( INT ) RETURNS SETOF actor.org_unit AS $$
234         SELECT  *
235           FROM  actor.org_unit_ancestors($1)
236                         UNION
237         SELECT  *
238           FROM  actor.org_unit_descendants($1);
239 $$ LANGUAGE SQL STABLE;
240
241 CREATE OR REPLACE FUNCTION actor.org_unit_full_path ( INT, INT ) RETURNS SETOF actor.org_unit AS $$
242         SELECT  * FROM actor.org_unit_full_path((actor.org_unit_ancestor_at_depth($1, $2)).id)
243 $$ LANGUAGE SQL STABLE;
244
245 CREATE OR REPLACE FUNCTION actor.org_unit_combined_ancestors ( INT, INT ) RETURNS SETOF actor.org_unit AS $$
246         SELECT  *
247           FROM  actor.org_unit_ancestors($1)
248                         UNION
249         SELECT  *
250           FROM  actor.org_unit_ancestors($2);
251 $$ LANGUAGE SQL STABLE;
252
253 CREATE OR REPLACE FUNCTION actor.org_unit_common_ancestors ( INT, INT ) RETURNS SETOF actor.org_unit AS $$
254         SELECT  *
255           FROM  actor.org_unit_ancestors($1)
256                         INTERSECT
257         SELECT  *
258           FROM  actor.org_unit_ancestors($2);
259 $$ LANGUAGE SQL STABLE;
260
261 CREATE OR REPLACE FUNCTION actor.org_unit_proximity ( INT, INT ) RETURNS INT AS $$
262         SELECT COUNT(id)::INT FROM (
263                 SELECT id FROM actor.org_unit_combined_ancestors($1, $2)
264                         EXCEPT
265                 SELECT id FROM actor.org_unit_common_ancestors($1, $2)
266         ) z;
267 $$ LANGUAGE SQL STABLE;
268
269 CREATE OR REPLACE FUNCTION actor.org_unit_ancestor_setting( setting_name TEXT, org_id INT ) RETURNS SETOF actor.org_unit_setting AS $$
270 DECLARE
271     setting RECORD;
272     cur_org INT;
273 BEGIN
274     cur_org := org_id;
275     LOOP
276         SELECT INTO setting * FROM actor.org_unit_setting WHERE org_unit = cur_org AND name = setting_name;
277         IF FOUND THEN
278             RETURN NEXT setting;
279         END IF;
280         SELECT INTO cur_org parent_ou FROM actor.org_unit WHERE id = cur_org;
281         EXIT WHEN cur_org IS NULL;
282     END LOOP;
283     RETURN;
284 END;
285 $$ LANGUAGE plpgsql STABLE;
286
287 COMMENT ON FUNCTION actor.org_unit_ancestor_setting( TEXT, INT) IS $$
288 /**
289 * Search "up" the org_unit tree until we find the first occurrence of an 
290 * org_unit_setting with the given name.
291 */
292 $$;
293
294 -- Intended to be used in a unique index on authority.record_entry like so:
295 -- CREATE UNIQUE INDEX unique_by_heading_and_thesaurus
296 --   ON authority.record_entry (authority.normalize_heading(marc))
297 --   WHERE deleted IS FALSE or deleted = FALSE;
298 CREATE OR REPLACE FUNCTION authority.normalize_heading( TEXT ) RETURNS TEXT AS $func$
299     use strict;
300     use warnings;
301
302     use utf8;
303     use MARC::Record;
304     use MARC::File::XML (BinaryEncoding => 'UTF8');
305     use UUID::Tiny ':std';
306
307     my $xml = shift() or return undef;
308
309     my $r;
310
311     # Prevent errors in XML parsing from blowing out ungracefully
312     eval {
313         $r = MARC::Record->new_from_xml( $xml );
314         1;
315     } or do {
316        return 'BAD_MARCXML_' . create_uuid_as_string(UUID_MD5, $xml);
317     };
318
319     if (!$r) {
320        return 'BAD_MARCXML_' . create_uuid_as_string(UUID_MD5, $xml);
321     }
322
323     # From http://www.loc.gov/standards/sourcelist/subject.html
324     my $thes_code_map = {
325         a => 'lcsh',
326         b => 'lcshac',
327         c => 'mesh',
328         d => 'nal',
329         k => 'cash',
330         n => 'notapplicable',
331         r => 'aat',
332         s => 'sears',
333         v => 'rvm',
334     };
335
336     # Default to "No attempt to code" if the leader is horribly broken
337     my $fixed_field = $r->field('008');
338     my $thes_char = '|';
339     if ($fixed_field) { 
340         $thes_char = substr($fixed_field->data(), 11, 1) || '|';
341     }
342
343     my $thes_code = 'UNDEFINED';
344
345     if ($thes_char eq 'z') {
346         # Grab the 040 $f per http://www.loc.gov/marc/authority/ad040.html
347         $thes_code = $r->subfield('040', 'f') || 'UNDEFINED';
348     } elsif ($thes_code_map->{$thes_char}) {
349         $thes_code = $thes_code_map->{$thes_char};
350     }
351
352     my $auth_txt = '';
353     my $head = $r->field('1..');
354     if ($head) {
355         # Concatenate all of these subfields together, prefixed by their code
356         # to prevent collisions along the lines of "Fiction, North Carolina"
357         foreach my $sf ($head->subfields()) {
358             $auth_txt .= '‡' . $sf->[0] . ' ' . $sf->[1];
359         }
360     }
361     
362     # Perhaps better to parameterize the spi and pass as a parameter
363     $auth_txt =~ s/'//go;
364
365     if ($auth_txt) {
366         my $result = spi_exec_query("SELECT public.naco_normalize('$auth_txt') AS norm_text");
367         my $norm_txt = $result->{rows}[0]->{norm_text};
368         return $head->tag() . "_" . $thes_code . " " . $norm_txt;
369     }
370
371     return 'NOHEADING_' . $thes_code . ' ' . create_uuid_as_string(UUID_MD5, $xml);
372 $func$ LANGUAGE 'plperlu' IMMUTABLE;
373
374 COMMENT ON FUNCTION authority.normalize_heading( TEXT ) IS $$
375 /**
376 * Extract the authority heading, thesaurus, and NACO-normalized values
377 * from an authority record. The primary purpose is to build a unique
378 * index to defend against duplicated authority records from the same
379 * thesaurus.
380 */
381 $$;