diff options
Diffstat (limited to 'contrib/fuzzystrmatch')
-rw-r--r-- | contrib/fuzzystrmatch/.gitignore | 4 | ||||
-rw-r--r-- | contrib/fuzzystrmatch/Makefile | 24 | ||||
-rw-r--r-- | contrib/fuzzystrmatch/dmetaphone.c | 1438 | ||||
-rw-r--r-- | contrib/fuzzystrmatch/expected/fuzzystrmatch.out | 73 | ||||
-rw-r--r-- | contrib/fuzzystrmatch/fuzzystrmatch--1.0--1.1.sql | 15 | ||||
-rw-r--r-- | contrib/fuzzystrmatch/fuzzystrmatch--1.1.sql | 44 | ||||
-rw-r--r-- | contrib/fuzzystrmatch/fuzzystrmatch.c | 793 | ||||
-rw-r--r-- | contrib/fuzzystrmatch/fuzzystrmatch.control | 6 | ||||
-rw-r--r-- | contrib/fuzzystrmatch/sql/fuzzystrmatch.sql | 22 |
9 files changed, 2419 insertions, 0 deletions
diff --git a/contrib/fuzzystrmatch/.gitignore b/contrib/fuzzystrmatch/.gitignore new file mode 100644 index 0000000..5dcb3ff --- /dev/null +++ b/contrib/fuzzystrmatch/.gitignore @@ -0,0 +1,4 @@ +# Generated subdirectories +/log/ +/results/ +/tmp_check/ diff --git a/contrib/fuzzystrmatch/Makefile b/contrib/fuzzystrmatch/Makefile new file mode 100644 index 0000000..0704894 --- /dev/null +++ b/contrib/fuzzystrmatch/Makefile @@ -0,0 +1,24 @@ +# contrib/fuzzystrmatch/Makefile + +MODULE_big = fuzzystrmatch +OBJS = \ + $(WIN32RES) \ + dmetaphone.o \ + fuzzystrmatch.o + +EXTENSION = fuzzystrmatch +DATA = fuzzystrmatch--1.1.sql fuzzystrmatch--1.0--1.1.sql +PGFILEDESC = "fuzzystrmatch - similarities and distance between strings" + +REGRESS = fuzzystrmatch + +ifdef USE_PGXS +PG_CONFIG = pg_config +PGXS := $(shell $(PG_CONFIG) --pgxs) +include $(PGXS) +else +subdir = contrib/fuzzystrmatch +top_builddir = ../.. +include $(top_builddir)/src/Makefile.global +include $(top_srcdir)/contrib/contrib-global.mk +endif diff --git a/contrib/fuzzystrmatch/dmetaphone.c b/contrib/fuzzystrmatch/dmetaphone.c new file mode 100644 index 0000000..6f4d2b7 --- /dev/null +++ b/contrib/fuzzystrmatch/dmetaphone.c @@ -0,0 +1,1438 @@ +/* + * This is a port of the Double Metaphone algorithm for use in PostgreSQL. + * + * contrib/fuzzystrmatch/dmetaphone.c + * + * Double Metaphone computes 2 "sounds like" strings - a primary and an + * alternate. In most cases they are the same, but for foreign names + * especially they can be a bit different, depending on pronunciation. + * + * Information on using Double Metaphone can be found at + * http://www.codeproject.com/string/dmetaphone1.asp + * and the original article describing it can be found at + * http://drdobbs.com/184401251 + * + * For PostgreSQL we provide 2 functions - one for the primary and one for + * the alternate. That way the functions are pure text->text mappings that + * are useful in functional indexes. These are 'dmetaphone' for the + * primary and 'dmetaphone_alt' for the alternate. + * + * Assuming that dmetaphone.so is in $libdir, the SQL to set up the + * functions looks like this: + * + * CREATE FUNCTION dmetaphone (text) RETURNS text + * LANGUAGE C IMMUTABLE STRICT + * AS '$libdir/dmetaphone', 'dmetaphone'; + * + * CREATE FUNCTION dmetaphone_alt (text) RETURNS text + * LANGUAGE C IMMUTABLE STRICT + * AS '$libdir/dmetaphone', 'dmetaphone_alt'; + * + * Note that you have to declare the functions IMMUTABLE if you want to + * use them in functional indexes, and you have to declare them as STRICT + * as they do not check for NULL input, and will segfault if given NULL input. + * (See below for alternative ) Declaring them as STRICT means PostgreSQL + * will never call them with NULL, but instead assume the result is NULL, + * which is what we (I) want. + * + * Alternatively, compile with -DDMETAPHONE_NOSTRICT and the functions + * will detect NULL input and return NULL. The you don't have to declare them + * as STRICT. + * + * There is a small inefficiency here - each function call actually computes + * both the primary and the alternate and then throws away the one it doesn't + * need. That's the way the perl module was written, because perl can handle + * a list return more easily than we can in PostgreSQL. The result has been + * fast enough for my needs, but it could maybe be optimized a bit to remove + * that behaviour. + * + */ + + +/***************************** COPYRIGHT NOTICES *********************** + +Most of this code is directly from the Text::DoubleMetaphone perl module +version 0.05 available from https://www.cpan.org/. +It bears this copyright notice: + + + Copyright 2000, Maurice Aubrey <maurice@hevanet.com>. + All rights reserved. + + This code is based heavily on the C++ implementation by + Lawrence Philips and incorporates several bug fixes courtesy + of Kevin Atkinson <kevina@users.sourceforge.net>. + + This module is free software; you may redistribute it and/or + modify it under the same terms as Perl itself. + +The remaining code is authored by Andrew Dunstan <amdunstan@ncshp.org> and +<andrew@dunslane.net> and is covered this copyright: + + Copyright 2003, North Carolina State Highway Patrol. + All rights reserved. + + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose, without fee, and without a written agreement + is hereby granted, provided that the above copyright notice and this + paragraph and the following two paragraphs appear in all copies. + + IN NO EVENT SHALL THE NORTH CAROLINA STATE HIGHWAY PATROL BE LIABLE TO ANY + PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, + INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS + DOCUMENTATION, EVEN IF THE NORTH CAROLINA STATE HIGHWAY PATROL HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + THE NORTH CAROLINA STATE HIGHWAY PATROL SPECIFICALLY DISCLAIMS ANY + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED + HEREUNDER IS ON AN "AS IS" BASIS, AND THE NORTH CAROLINA STATE HIGHWAY PATROL + HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR + MODIFICATIONS. + +***********************************************************************/ + + +/* include these first, according to the docs */ +#ifndef DMETAPHONE_MAIN + +#include "postgres.h" + +#include "utils/builtins.h" + +/* turn off assertions for embedded function */ +#define NDEBUG + +#else /* DMETAPHONE_MAIN */ + +/* we need these if we didn't get them from postgres.h */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <stdarg.h> + +#endif /* DMETAPHONE_MAIN */ + +#include <assert.h> +#include <ctype.h> + +/* prototype for the main function we got from the perl module */ +static void DoubleMetaphone(char *, char **); + +#ifndef DMETAPHONE_MAIN + +/* + * The PostgreSQL visible dmetaphone function. + */ + +PG_FUNCTION_INFO_V1(dmetaphone); + +Datum +dmetaphone(PG_FUNCTION_ARGS) +{ + text *arg; + char *aptr, + *codes[2], + *code; + +#ifdef DMETAPHONE_NOSTRICT + if (PG_ARGISNULL(0)) + PG_RETURN_NULL(); +#endif + arg = PG_GETARG_TEXT_PP(0); + aptr = text_to_cstring(arg); + + DoubleMetaphone(aptr, codes); + code = codes[0]; + if (!code) + code = ""; + + PG_RETURN_TEXT_P(cstring_to_text(code)); +} + +/* + * The PostgreSQL visible dmetaphone_alt function. + */ + +PG_FUNCTION_INFO_V1(dmetaphone_alt); + +Datum +dmetaphone_alt(PG_FUNCTION_ARGS) +{ + text *arg; + char *aptr, + *codes[2], + *code; + +#ifdef DMETAPHONE_NOSTRICT + if (PG_ARGISNULL(0)) + PG_RETURN_NULL(); +#endif + arg = PG_GETARG_TEXT_PP(0); + aptr = text_to_cstring(arg); + + DoubleMetaphone(aptr, codes); + code = codes[1]; + if (!code) + code = ""; + + PG_RETURN_TEXT_P(cstring_to_text(code)); +} + + +/* here is where we start the code imported from the perl module */ + +/* all memory handling is done with these macros */ + +#define META_MALLOC(v,n,t) \ + (v = (t*)palloc(((n)*sizeof(t)))) + +#define META_REALLOC(v,n,t) \ + (v = (t*)repalloc((v),((n)*sizeof(t)))) + +/* + * Don't do pfree - it seems to cause a SIGSEGV sometimes - which might have just + * been caused by reloading the module in development. + * So we rely on context cleanup - Tom Lane says pfree shouldn't be necessary + * in a case like this. + */ + +#define META_FREE(x) ((void)true) /* pfree((x)) */ +#else /* not defined DMETAPHONE_MAIN */ + +/* use the standard malloc library when not running in PostgreSQL */ + +#define META_MALLOC(v,n,t) \ + (v = (t*)malloc(((n)*sizeof(t)))) + +#define META_REALLOC(v,n,t) \ + (v = (t*)realloc((v),((n)*sizeof(t)))) + +#define META_FREE(x) free((x)) +#endif /* defined DMETAPHONE_MAIN */ + + + +/* this typedef was originally in the perl module's .h file */ + +typedef struct +{ + char *str; + int length; + int bufsize; + int free_string_on_destroy; +} + +metastring; + +/* + * remaining perl module funcs unchanged except for declaring them static + * and reformatting to PostgreSQL indentation and to fit in 80 cols. + * + */ + +static metastring * +NewMetaString(const char *init_str) +{ + metastring *s; + char empty_string[] = ""; + + META_MALLOC(s, 1, metastring); + assert(s != NULL); + + if (init_str == NULL) + init_str = empty_string; + s->length = strlen(init_str); + /* preallocate a bit more for potential growth */ + s->bufsize = s->length + 7; + + META_MALLOC(s->str, s->bufsize, char); + assert(s->str != NULL); + + memcpy(s->str, init_str, s->length + 1); + s->free_string_on_destroy = 1; + + return s; +} + + +static void +DestroyMetaString(metastring *s) +{ + if (s == NULL) + return; + + if (s->free_string_on_destroy && (s->str != NULL)) + META_FREE(s->str); + + META_FREE(s); +} + + +static void +IncreaseBuffer(metastring *s, int chars_needed) +{ + META_REALLOC(s->str, (s->bufsize + chars_needed + 10), char); + assert(s->str != NULL); + s->bufsize = s->bufsize + chars_needed + 10; +} + + +static void +MakeUpper(metastring *s) +{ + char *i; + + for (i = s->str; *i; i++) + *i = toupper((unsigned char) *i); +} + + +static int +IsVowel(metastring *s, int pos) +{ + char c; + + if ((pos < 0) || (pos >= s->length)) + return 0; + + c = *(s->str + pos); + if ((c == 'A') || (c == 'E') || (c == 'I') || (c == 'O') || + (c == 'U') || (c == 'Y')) + return 1; + + return 0; +} + + +static int +SlavoGermanic(metastring *s) +{ + if ((char *) strstr(s->str, "W")) + return 1; + else if ((char *) strstr(s->str, "K")) + return 1; + else if ((char *) strstr(s->str, "CZ")) + return 1; + else if ((char *) strstr(s->str, "WITZ")) + return 1; + else + return 0; +} + + +static char +GetAt(metastring *s, int pos) +{ + if ((pos < 0) || (pos >= s->length)) + return '\0'; + + return ((char) *(s->str + pos)); +} + + +static void +SetAt(metastring *s, int pos, char c) +{ + if ((pos < 0) || (pos >= s->length)) + return; + + *(s->str + pos) = c; +} + + +/* + Caveats: the START value is 0 based +*/ +static int +StringAt(metastring *s, int start, int length,...) +{ + char *test; + char *pos; + va_list ap; + + if ((start < 0) || (start >= s->length)) + return 0; + + pos = (s->str + start); + va_start(ap, length); + + do + { + test = va_arg(ap, char *); + if (*test && (strncmp(pos, test, length) == 0)) + { + va_end(ap); + return 1; + } + } + while (strcmp(test, "") != 0); + + va_end(ap); + + return 0; +} + + +static void +MetaphAdd(metastring *s, const char *new_str) +{ + int add_length; + + if (new_str == NULL) + return; + + add_length = strlen(new_str); + if ((s->length + add_length) > (s->bufsize - 1)) + IncreaseBuffer(s, add_length); + + strcat(s->str, new_str); + s->length += add_length; +} + + +static void +DoubleMetaphone(char *str, char **codes) +{ + int length; + metastring *original; + metastring *primary; + metastring *secondary; + int current; + int last; + + current = 0; + /* we need the real length and last prior to padding */ + length = strlen(str); + last = length - 1; + original = NewMetaString(str); + /* Pad original so we can index beyond end */ + MetaphAdd(original, " "); + + primary = NewMetaString(""); + secondary = NewMetaString(""); + primary->free_string_on_destroy = 0; + secondary->free_string_on_destroy = 0; + + MakeUpper(original); + + /* skip these when at start of word */ + if (StringAt(original, 0, 2, "GN", "KN", "PN", "WR", "PS", "")) + current += 1; + + /* Initial 'X' is pronounced 'Z' e.g. 'Xavier' */ + if (GetAt(original, 0) == 'X') + { + MetaphAdd(primary, "S"); /* 'Z' maps to 'S' */ + MetaphAdd(secondary, "S"); + current += 1; + } + + /* main loop */ + while ((primary->length < 4) || (secondary->length < 4)) + { + if (current >= length) + break; + + switch (GetAt(original, current)) + { + case 'A': + case 'E': + case 'I': + case 'O': + case 'U': + case 'Y': + if (current == 0) + { + /* all init vowels now map to 'A' */ + MetaphAdd(primary, "A"); + MetaphAdd(secondary, "A"); + } + current += 1; + break; + + case 'B': + + /* "-mb", e.g", "dumb", already skipped over... */ + MetaphAdd(primary, "P"); + MetaphAdd(secondary, "P"); + + if (GetAt(original, current + 1) == 'B') + current += 2; + else + current += 1; + break; + + case '\xc7': /* C with cedilla */ + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "S"); + current += 1; + break; + + case 'C': + /* various germanic */ + if ((current > 1) + && !IsVowel(original, current - 2) + && StringAt(original, (current - 1), 3, "ACH", "") + && ((GetAt(original, current + 2) != 'I') + && ((GetAt(original, current + 2) != 'E') + || StringAt(original, (current - 2), 6, "BACHER", + "MACHER", "")))) + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + current += 2; + break; + } + + /* special case 'caesar' */ + if ((current == 0) + && StringAt(original, current, 6, "CAESAR", "")) + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "S"); + current += 2; + break; + } + + /* italian 'chianti' */ + if (StringAt(original, current, 4, "CHIA", "")) + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + current += 2; + break; + } + + if (StringAt(original, current, 2, "CH", "")) + { + /* find 'michael' */ + if ((current > 0) + && StringAt(original, current, 4, "CHAE", "")) + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "X"); + current += 2; + break; + } + + /* greek roots e.g. 'chemistry', 'chorus' */ + if ((current == 0) + && (StringAt(original, (current + 1), 5, + "HARAC", "HARIS", "") + || StringAt(original, (current + 1), 3, "HOR", + "HYM", "HIA", "HEM", "")) + && !StringAt(original, 0, 5, "CHORE", "")) + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + current += 2; + break; + } + + /* germanic, greek, or otherwise 'ch' for 'kh' sound */ + if ((StringAt(original, 0, 4, "VAN ", "VON ", "") + || StringAt(original, 0, 3, "SCH", "")) + /* 'architect but not 'arch', 'orchestra', 'orchid' */ + || StringAt(original, (current - 2), 6, "ORCHES", + "ARCHIT", "ORCHID", "") + || StringAt(original, (current + 2), 1, "T", "S", + "") + || ((StringAt(original, (current - 1), 1, + "A", "O", "U", "E", "") + || (current == 0)) + + /* + * e.g., 'wachtler', 'wechsler', but not 'tichner' + */ + && StringAt(original, (current + 2), 1, "L", "R", + "N", "M", "B", "H", "F", "V", "W", + " ", ""))) + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + } + else + { + if (current > 0) + { + if (StringAt(original, 0, 2, "MC", "")) + { + /* e.g., "McHugh" */ + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + } + else + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "K"); + } + } + else + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "X"); + } + } + current += 2; + break; + } + /* e.g, 'czerny' */ + if (StringAt(original, current, 2, "CZ", "") + && !StringAt(original, (current - 2), 4, "WICZ", "")) + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "X"); + current += 2; + break; + } + + /* e.g., 'focaccia' */ + if (StringAt(original, (current + 1), 3, "CIA", "")) + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "X"); + current += 3; + break; + } + + /* double 'C', but not if e.g. 'McClellan' */ + if (StringAt(original, current, 2, "CC", "") + && !((current == 1) && (GetAt(original, 0) == 'M'))) + { + /* 'bellocchio' but not 'bacchus' */ + if (StringAt(original, (current + 2), 1, "I", "E", "H", "") + && !StringAt(original, (current + 2), 2, "HU", "")) + { + /* 'accident', 'accede' 'succeed' */ + if (((current == 1) + && (GetAt(original, current - 1) == 'A')) + || StringAt(original, (current - 1), 5, "UCCEE", + "UCCES", "")) + { + MetaphAdd(primary, "KS"); + MetaphAdd(secondary, "KS"); + /* 'bacci', 'bertucci', other italian */ + } + else + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "X"); + } + current += 3; + break; + } + else + { /* Pierce's rule */ + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + current += 2; + break; + } + } + + if (StringAt(original, current, 2, "CK", "CG", "CQ", "")) + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + current += 2; + break; + } + + if (StringAt(original, current, 2, "CI", "CE", "CY", "")) + { + /* italian vs. english */ + if (StringAt + (original, current, 3, "CIO", "CIE", "CIA", "")) + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "X"); + } + else + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "S"); + } + current += 2; + break; + } + + /* else */ + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + + /* name sent in 'mac caffrey', 'mac gregor */ + if (StringAt(original, (current + 1), 2, " C", " Q", " G", "")) + current += 3; + else if (StringAt(original, (current + 1), 1, "C", "K", "Q", "") + && !StringAt(original, (current + 1), 2, + "CE", "CI", "")) + current += 2; + else + current += 1; + break; + + case 'D': + if (StringAt(original, current, 2, "DG", "")) + { + if (StringAt(original, (current + 2), 1, + "I", "E", "Y", "")) + { + /* e.g. 'edge' */ + MetaphAdd(primary, "J"); + MetaphAdd(secondary, "J"); + current += 3; + break; + } + else + { + /* e.g. 'edgar' */ + MetaphAdd(primary, "TK"); + MetaphAdd(secondary, "TK"); + current += 2; + break; + } + } + + if (StringAt(original, current, 2, "DT", "DD", "")) + { + MetaphAdd(primary, "T"); + MetaphAdd(secondary, "T"); + current += 2; + break; + } + + /* else */ + MetaphAdd(primary, "T"); + MetaphAdd(secondary, "T"); + current += 1; + break; + + case 'F': + if (GetAt(original, current + 1) == 'F') + current += 2; + else + current += 1; + MetaphAdd(primary, "F"); + MetaphAdd(secondary, "F"); + break; + + case 'G': + if (GetAt(original, current + 1) == 'H') + { + if ((current > 0) && !IsVowel(original, current - 1)) + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + current += 2; + break; + } + + if (current < 3) + { + /* 'ghislane', ghiradelli */ + if (current == 0) + { + if (GetAt(original, current + 2) == 'I') + { + MetaphAdd(primary, "J"); + MetaphAdd(secondary, "J"); + } + else + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + } + current += 2; + break; + } + } + + /* + * Parker's rule (with some further refinements) - e.g., + * 'hugh' + */ + if (((current > 1) + && StringAt(original, (current - 2), 1, + "B", "H", "D", "")) + /* e.g., 'bough' */ + || ((current > 2) + && StringAt(original, (current - 3), 1, + "B", "H", "D", "")) + /* e.g., 'broughton' */ + || ((current > 3) + && StringAt(original, (current - 4), 1, + "B", "H", ""))) + { + current += 2; + break; + } + else + { + /* + * e.g., 'laugh', 'McLaughlin', 'cough', 'gough', + * 'rough', 'tough' + */ + if ((current > 2) + && (GetAt(original, current - 1) == 'U') + && StringAt(original, (current - 3), 1, "C", + "G", "L", "R", "T", "")) + { + MetaphAdd(primary, "F"); + MetaphAdd(secondary, "F"); + } + else if ((current > 0) + && GetAt(original, current - 1) != 'I') + { + + + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + } + + current += 2; + break; + } + } + + if (GetAt(original, current + 1) == 'N') + { + if ((current == 1) && IsVowel(original, 0) + && !SlavoGermanic(original)) + { + MetaphAdd(primary, "KN"); + MetaphAdd(secondary, "N"); + } + else + /* not e.g. 'cagney' */ + if (!StringAt(original, (current + 2), 2, "EY", "") + && (GetAt(original, current + 1) != 'Y') + && !SlavoGermanic(original)) + { + MetaphAdd(primary, "N"); + MetaphAdd(secondary, "KN"); + } + else + { + MetaphAdd(primary, "KN"); + MetaphAdd(secondary, "KN"); + } + current += 2; + break; + } + + /* 'tagliaro' */ + if (StringAt(original, (current + 1), 2, "LI", "") + && !SlavoGermanic(original)) + { + MetaphAdd(primary, "KL"); + MetaphAdd(secondary, "L"); + current += 2; + break; + } + + /* -ges-,-gep-,-gel-, -gie- at beginning */ + if ((current == 0) + && ((GetAt(original, current + 1) == 'Y') + || StringAt(original, (current + 1), 2, "ES", "EP", + "EB", "EL", "EY", "IB", "IL", "IN", "IE", + "EI", "ER", ""))) + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "J"); + current += 2; + break; + } + + /* -ger-, -gy- */ + if ((StringAt(original, (current + 1), 2, "ER", "") + || (GetAt(original, current + 1) == 'Y')) + && !StringAt(original, 0, 6, + "DANGER", "RANGER", "MANGER", "") + && !StringAt(original, (current - 1), 1, "E", "I", "") + && !StringAt(original, (current - 1), 3, "RGY", "OGY", "")) + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "J"); + current += 2; + break; + } + + /* italian e.g, 'biaggi' */ + if (StringAt(original, (current + 1), 1, "E", "I", "Y", "") + || StringAt(original, (current - 1), 4, + "AGGI", "OGGI", "")) + { + /* obvious germanic */ + if ((StringAt(original, 0, 4, "VAN ", "VON ", "") + || StringAt(original, 0, 3, "SCH", "")) + || StringAt(original, (current + 1), 2, "ET", "")) + { + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + } + else + { + /* always soft if french ending */ + if (StringAt + (original, (current + 1), 4, "IER ", "")) + { + MetaphAdd(primary, "J"); + MetaphAdd(secondary, "J"); + } + else + { + MetaphAdd(primary, "J"); + MetaphAdd(secondary, "K"); + } + } + current += 2; + break; + } + + if (GetAt(original, current + 1) == 'G') + current += 2; + else + current += 1; + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + break; + + case 'H': + /* only keep if first & before vowel or btw. 2 vowels */ + if (((current == 0) || IsVowel(original, current - 1)) + && IsVowel(original, current + 1)) + { + MetaphAdd(primary, "H"); + MetaphAdd(secondary, "H"); + current += 2; + } + else + /* also takes care of 'HH' */ + current += 1; + break; + + case 'J': + /* obvious spanish, 'jose', 'san jacinto' */ + if (StringAt(original, current, 4, "JOSE", "") + || StringAt(original, 0, 4, "SAN ", "")) + { + if (((current == 0) + && (GetAt(original, current + 4) == ' ')) + || StringAt(original, 0, 4, "SAN ", "")) + { + MetaphAdd(primary, "H"); + MetaphAdd(secondary, "H"); + } + else + { + MetaphAdd(primary, "J"); + MetaphAdd(secondary, "H"); + } + current += 1; + break; + } + + if ((current == 0) + && !StringAt(original, current, 4, "JOSE", "")) + { + MetaphAdd(primary, "J"); /* Yankelovich/Jankelowicz */ + MetaphAdd(secondary, "A"); + } + else + { + /* spanish pron. of e.g. 'bajador' */ + if (IsVowel(original, current - 1) + && !SlavoGermanic(original) + && ((GetAt(original, current + 1) == 'A') + || (GetAt(original, current + 1) == 'O'))) + { + MetaphAdd(primary, "J"); + MetaphAdd(secondary, "H"); + } + else + { + if (current == last) + { + MetaphAdd(primary, "J"); + MetaphAdd(secondary, ""); + } + else + { + if (!StringAt(original, (current + 1), 1, "L", "T", + "K", "S", "N", "M", "B", "Z", "") + && !StringAt(original, (current - 1), 1, + "S", "K", "L", "")) + { + MetaphAdd(primary, "J"); + MetaphAdd(secondary, "J"); + } + } + } + } + + if (GetAt(original, current + 1) == 'J') /* it could happen! */ + current += 2; + else + current += 1; + break; + + case 'K': + if (GetAt(original, current + 1) == 'K') + current += 2; + else + current += 1; + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + break; + + case 'L': + if (GetAt(original, current + 1) == 'L') + { + /* spanish e.g. 'cabrillo', 'gallegos' */ + if (((current == (length - 3)) + && StringAt(original, (current - 1), 4, "ILLO", + "ILLA", "ALLE", "")) + || ((StringAt(original, (last - 1), 2, "AS", "OS", "") + || StringAt(original, last, 1, "A", "O", "")) + && StringAt(original, (current - 1), 4, + "ALLE", ""))) + { + MetaphAdd(primary, "L"); + MetaphAdd(secondary, ""); + current += 2; + break; + } + current += 2; + } + else + current += 1; + MetaphAdd(primary, "L"); + MetaphAdd(secondary, "L"); + break; + + case 'M': + if ((StringAt(original, (current - 1), 3, "UMB", "") + && (((current + 1) == last) + || StringAt(original, (current + 2), 2, "ER", ""))) + /* 'dumb','thumb' */ + || (GetAt(original, current + 1) == 'M')) + current += 2; + else + current += 1; + MetaphAdd(primary, "M"); + MetaphAdd(secondary, "M"); + break; + + case 'N': + if (GetAt(original, current + 1) == 'N') + current += 2; + else + current += 1; + MetaphAdd(primary, "N"); + MetaphAdd(secondary, "N"); + break; + + case '\xd1': /* N with tilde */ + current += 1; + MetaphAdd(primary, "N"); + MetaphAdd(secondary, "N"); + break; + + case 'P': + if (GetAt(original, current + 1) == 'H') + { + MetaphAdd(primary, "F"); + MetaphAdd(secondary, "F"); + current += 2; + break; + } + + /* also account for "campbell", "raspberry" */ + if (StringAt(original, (current + 1), 1, "P", "B", "")) + current += 2; + else + current += 1; + MetaphAdd(primary, "P"); + MetaphAdd(secondary, "P"); + break; + + case 'Q': + if (GetAt(original, current + 1) == 'Q') + current += 2; + else + current += 1; + MetaphAdd(primary, "K"); + MetaphAdd(secondary, "K"); + break; + + case 'R': + /* french e.g. 'rogier', but exclude 'hochmeier' */ + if ((current == last) + && !SlavoGermanic(original) + && StringAt(original, (current - 2), 2, "IE", "") + && !StringAt(original, (current - 4), 2, "ME", "MA", "")) + { + MetaphAdd(primary, ""); + MetaphAdd(secondary, "R"); + } + else + { + MetaphAdd(primary, "R"); + MetaphAdd(secondary, "R"); + } + + if (GetAt(original, current + 1) == 'R') + current += 2; + else + current += 1; + break; + + case 'S': + /* special cases 'island', 'isle', 'carlisle', 'carlysle' */ + if (StringAt(original, (current - 1), 3, "ISL", "YSL", "")) + { + current += 1; + break; + } + + /* special case 'sugar-' */ + if ((current == 0) + && StringAt(original, current, 5, "SUGAR", "")) + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "S"); + current += 1; + break; + } + + if (StringAt(original, current, 2, "SH", "")) + { + /* germanic */ + if (StringAt + (original, (current + 1), 4, "HEIM", "HOEK", "HOLM", + "HOLZ", "")) + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "S"); + } + else + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "X"); + } + current += 2; + break; + } + + /* italian & armenian */ + if (StringAt(original, current, 3, "SIO", "SIA", "") + || StringAt(original, current, 4, "SIAN", "")) + { + if (!SlavoGermanic(original)) + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "X"); + } + else + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "S"); + } + current += 3; + break; + } + + /* + * german & anglicisations, e.g. 'smith' match 'schmidt', + * 'snider' match 'schneider' also, -sz- in slavic language + * although in hungarian it is pronounced 's' + */ + if (((current == 0) + && StringAt(original, (current + 1), 1, + "M", "N", "L", "W", "")) + || StringAt(original, (current + 1), 1, "Z", "")) + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "X"); + if (StringAt(original, (current + 1), 1, "Z", "")) + current += 2; + else + current += 1; + break; + } + + if (StringAt(original, current, 2, "SC", "")) + { + /* Schlesinger's rule */ + if (GetAt(original, current + 2) == 'H') + { + /* dutch origin, e.g. 'school', 'schooner' */ + if (StringAt(original, (current + 3), 2, + "OO", "ER", "EN", + "UY", "ED", "EM", "")) + { + /* 'schermerhorn', 'schenker' */ + if (StringAt(original, (current + 3), 2, + "ER", "EN", "")) + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "SK"); + } + else + { + MetaphAdd(primary, "SK"); + MetaphAdd(secondary, "SK"); + } + current += 3; + break; + } + else + { + if ((current == 0) && !IsVowel(original, 3) + && (GetAt(original, 3) != 'W')) + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "S"); + } + else + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "X"); + } + current += 3; + break; + } + } + + if (StringAt(original, (current + 2), 1, + "I", "E", "Y", "")) + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "S"); + current += 3; + break; + } + /* else */ + MetaphAdd(primary, "SK"); + MetaphAdd(secondary, "SK"); + current += 3; + break; + } + + /* french e.g. 'resnais', 'artois' */ + if ((current == last) + && StringAt(original, (current - 2), 2, "AI", "OI", "")) + { + MetaphAdd(primary, ""); + MetaphAdd(secondary, "S"); + } + else + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "S"); + } + + if (StringAt(original, (current + 1), 1, "S", "Z", "")) + current += 2; + else + current += 1; + break; + + case 'T': + if (StringAt(original, current, 4, "TION", "")) + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "X"); + current += 3; + break; + } + + if (StringAt(original, current, 3, "TIA", "TCH", "")) + { + MetaphAdd(primary, "X"); + MetaphAdd(secondary, "X"); + current += 3; + break; + } + + if (StringAt(original, current, 2, "TH", "") + || StringAt(original, current, 3, "TTH", "")) + { + /* special case 'thomas', 'thames' or germanic */ + if (StringAt(original, (current + 2), 2, "OM", "AM", "") + || StringAt(original, 0, 4, "VAN ", "VON ", "") + || StringAt(original, 0, 3, "SCH", "")) + { + MetaphAdd(primary, "T"); + MetaphAdd(secondary, "T"); + } + else + { + MetaphAdd(primary, "0"); + MetaphAdd(secondary, "T"); + } + current += 2; + break; + } + + if (StringAt(original, (current + 1), 1, "T", "D", "")) + current += 2; + else + current += 1; + MetaphAdd(primary, "T"); + MetaphAdd(secondary, "T"); + break; + + case 'V': + if (GetAt(original, current + 1) == 'V') + current += 2; + else + current += 1; + MetaphAdd(primary, "F"); + MetaphAdd(secondary, "F"); + break; + + case 'W': + /* can also be in middle of word */ + if (StringAt(original, current, 2, "WR", "")) + { + MetaphAdd(primary, "R"); + MetaphAdd(secondary, "R"); + current += 2; + break; + } + + if ((current == 0) + && (IsVowel(original, current + 1) + || StringAt(original, current, 2, "WH", ""))) + { + /* Wasserman should match Vasserman */ + if (IsVowel(original, current + 1)) + { + MetaphAdd(primary, "A"); + MetaphAdd(secondary, "F"); + } + else + { + /* need Uomo to match Womo */ + MetaphAdd(primary, "A"); + MetaphAdd(secondary, "A"); + } + } + + /* Arnow should match Arnoff */ + if (((current == last) && IsVowel(original, current - 1)) + || StringAt(original, (current - 1), 5, "EWSKI", "EWSKY", + "OWSKI", "OWSKY", "") + || StringAt(original, 0, 3, "SCH", "")) + { + MetaphAdd(primary, ""); + MetaphAdd(secondary, "F"); + current += 1; + break; + } + + /* polish e.g. 'filipowicz' */ + if (StringAt(original, current, 4, "WICZ", "WITZ", "")) + { + MetaphAdd(primary, "TS"); + MetaphAdd(secondary, "FX"); + current += 4; + break; + } + + /* else skip it */ + current += 1; + break; + + case 'X': + /* french e.g. breaux */ + if (!((current == last) + && (StringAt(original, (current - 3), 3, + "IAU", "EAU", "") + || StringAt(original, (current - 2), 2, + "AU", "OU", "")))) + { + MetaphAdd(primary, "KS"); + MetaphAdd(secondary, "KS"); + } + + + if (StringAt(original, (current + 1), 1, "C", "X", "")) + current += 2; + else + current += 1; + break; + + case 'Z': + /* chinese pinyin e.g. 'zhao' */ + if (GetAt(original, current + 1) == 'H') + { + MetaphAdd(primary, "J"); + MetaphAdd(secondary, "J"); + current += 2; + break; + } + else if (StringAt(original, (current + 1), 2, + "ZO", "ZI", "ZA", "") + || (SlavoGermanic(original) + && ((current > 0) + && GetAt(original, current - 1) != 'T'))) + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "TS"); + } + else + { + MetaphAdd(primary, "S"); + MetaphAdd(secondary, "S"); + } + + if (GetAt(original, current + 1) == 'Z') + current += 2; + else + current += 1; + break; + + default: + current += 1; + } + + /* + * printf("PRIMARY: %s\n", primary->str); printf("SECONDARY: %s\n", + * secondary->str); + */ + } + + + if (primary->length > 4) + SetAt(primary, 4, '\0'); + + if (secondary->length > 4) + SetAt(secondary, 4, '\0'); + + *codes = primary->str; + *++codes = secondary->str; + + DestroyMetaString(original); + DestroyMetaString(primary); + DestroyMetaString(secondary); +} + +#ifdef DMETAPHONE_MAIN + +/* just for testing - not part of the perl code */ + +main(int argc, char **argv) +{ + char *codes[2]; + + if (argc > 1) + { + DoubleMetaphone(argv[1], codes); + printf("%s|%s\n", codes[0], codes[1]); + } +} + +#endif diff --git a/contrib/fuzzystrmatch/expected/fuzzystrmatch.out b/contrib/fuzzystrmatch/expected/fuzzystrmatch.out new file mode 100644 index 0000000..2827e81 --- /dev/null +++ b/contrib/fuzzystrmatch/expected/fuzzystrmatch.out @@ -0,0 +1,73 @@ +CREATE EXTENSION fuzzystrmatch; +SELECT soundex('hello world!'); + soundex +--------- + H464 +(1 row) + +SELECT soundex('Anne'), soundex('Ann'), difference('Anne', 'Ann'); + soundex | soundex | difference +---------+---------+------------ + A500 | A500 | 4 +(1 row) + +SELECT soundex('Anne'), soundex('Andrew'), difference('Anne', 'Andrew'); + soundex | soundex | difference +---------+---------+------------ + A500 | A536 | 2 +(1 row) + +SELECT soundex('Anne'), soundex('Margaret'), difference('Anne', 'Margaret'); + soundex | soundex | difference +---------+---------+------------ + A500 | M626 | 0 +(1 row) + +SELECT soundex(''), difference('', ''); + soundex | difference +---------+------------ + | 4 +(1 row) + +SELECT levenshtein('GUMBO', 'GAMBOL'); + levenshtein +------------- + 2 +(1 row) + +SELECT levenshtein('GUMBO', 'GAMBOL', 2, 1, 1); + levenshtein +------------- + 3 +(1 row) + +SELECT levenshtein_less_equal('extensive', 'exhaustive', 2); + levenshtein_less_equal +------------------------ + 3 +(1 row) + +SELECT levenshtein_less_equal('extensive', 'exhaustive', 4); + levenshtein_less_equal +------------------------ + 4 +(1 row) + +SELECT metaphone('GUMBO', 4); + metaphone +----------- + KM +(1 row) + +SELECT dmetaphone('gumbo'); + dmetaphone +------------ + KMP +(1 row) + +SELECT dmetaphone_alt('gumbo'); + dmetaphone_alt +---------------- + KMP +(1 row) + diff --git a/contrib/fuzzystrmatch/fuzzystrmatch--1.0--1.1.sql b/contrib/fuzzystrmatch/fuzzystrmatch--1.0--1.1.sql new file mode 100644 index 0000000..f2b1555 --- /dev/null +++ b/contrib/fuzzystrmatch/fuzzystrmatch--1.0--1.1.sql @@ -0,0 +1,15 @@ +/* contrib/fuzzystrmatch/fuzzystrmatch--1.0--1.1.sql */ + +-- complain if script is sourced in psql, rather than via ALTER EXTENSION +\echo Use "ALTER EXTENSION fuzzystrmatch UPDATE TO '1.1'" to load this file. \quit + +ALTER FUNCTION levenshtein(text, text) PARALLEL SAFE; +ALTER FUNCTION levenshtein(text, text, int, int, int) PARALLEL SAFE; +ALTER FUNCTION levenshtein_less_equal(text, text, int) PARALLEL SAFE; +ALTER FUNCTION levenshtein_less_equal(text, text, int, int, int, int) PARALLEL SAFE; +ALTER FUNCTION metaphone(text, int) PARALLEL SAFE; +ALTER FUNCTION soundex(text) PARALLEL SAFE; +ALTER FUNCTION text_soundex(text) PARALLEL SAFE; +ALTER FUNCTION difference(text, text) PARALLEL SAFE; +ALTER FUNCTION dmetaphone(text) PARALLEL SAFE; +ALTER FUNCTION dmetaphone_alt(text) PARALLEL SAFE; diff --git a/contrib/fuzzystrmatch/fuzzystrmatch--1.1.sql b/contrib/fuzzystrmatch/fuzzystrmatch--1.1.sql new file mode 100644 index 0000000..41de9d9 --- /dev/null +++ b/contrib/fuzzystrmatch/fuzzystrmatch--1.1.sql @@ -0,0 +1,44 @@ +/* contrib/fuzzystrmatch/fuzzystrmatch--1.1.sql */ + +-- complain if script is sourced in psql, rather than via CREATE EXTENSION +\echo Use "CREATE EXTENSION fuzzystrmatch" to load this file. \quit + +CREATE FUNCTION levenshtein (text,text) RETURNS int +AS 'MODULE_PATHNAME','levenshtein' +LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION levenshtein (text,text,int,int,int) RETURNS int +AS 'MODULE_PATHNAME','levenshtein_with_costs' +LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION levenshtein_less_equal (text,text,int) RETURNS int +AS 'MODULE_PATHNAME','levenshtein_less_equal' +LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION levenshtein_less_equal (text,text,int,int,int,int) RETURNS int +AS 'MODULE_PATHNAME','levenshtein_less_equal_with_costs' +LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION metaphone (text,int) RETURNS text +AS 'MODULE_PATHNAME','metaphone' +LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION soundex(text) RETURNS text +AS 'MODULE_PATHNAME', 'soundex' +LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION text_soundex(text) RETURNS text +AS 'MODULE_PATHNAME', 'soundex' +LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION difference(text,text) RETURNS int +AS 'MODULE_PATHNAME', 'difference' +LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION dmetaphone (text) RETURNS text +AS 'MODULE_PATHNAME', 'dmetaphone' +LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION dmetaphone_alt (text) RETURNS text +AS 'MODULE_PATHNAME', 'dmetaphone_alt' +LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; diff --git a/contrib/fuzzystrmatch/fuzzystrmatch.c b/contrib/fuzzystrmatch/fuzzystrmatch.c new file mode 100644 index 0000000..18177d1 --- /dev/null +++ b/contrib/fuzzystrmatch/fuzzystrmatch.c @@ -0,0 +1,793 @@ +/* + * fuzzystrmatch.c + * + * Functions for "fuzzy" comparison of strings + * + * Joe Conway <mail@joeconway.com> + * + * contrib/fuzzystrmatch/fuzzystrmatch.c + * Copyright (c) 2001-2022, PostgreSQL Global Development Group + * ALL RIGHTS RESERVED; + * + * metaphone() + * ----------- + * Modified for PostgreSQL by Joe Conway. + * Based on CPAN's "Text-Metaphone-1.96" by Michael G Schwern <schwern@pobox.com> + * Code slightly modified for use as PostgreSQL function (palloc, elog, etc). + * Metaphone was originally created by Lawrence Philips and presented in article + * in "Computer Language" December 1990 issue. + * + * Permission to use, copy, modify, and distribute this software and its + * documentation for any purpose, without fee, and without a written agreement + * is hereby granted, provided that the above copyright notice and this + * paragraph and the following two paragraphs appear in all copies. + * + * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING + * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS + * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + */ + +#include "postgres.h" + +#include <ctype.h> + +#include "mb/pg_wchar.h" +#include "utils/builtins.h" +#include "utils/varlena.h" + +PG_MODULE_MAGIC; + +/* + * Soundex + */ +static void _soundex(const char *instr, char *outstr); + +#define SOUNDEX_LEN 4 + +/* ABCDEFGHIJKLMNOPQRSTUVWXYZ */ +static const char *soundex_table = "01230120022455012623010202"; + +static char +soundex_code(char letter) +{ + letter = toupper((unsigned char) letter); + /* Defend against non-ASCII letters */ + if (letter >= 'A' && letter <= 'Z') + return soundex_table[letter - 'A']; + return letter; +} + +/* + * Metaphone + */ +#define MAX_METAPHONE_STRLEN 255 + +/* + * Original code by Michael G Schwern starts here. + * Code slightly modified for use as PostgreSQL function. + */ + + +/************************************************************************** + metaphone -- Breaks english phrases down into their phonemes. + + Input + word -- An english word to be phonized + max_phonemes -- How many phonemes to calculate. If 0, then it + will phonize the entire phrase. + phoned_word -- The final phonized word. (We'll allocate the + memory.) + Output + error -- A simple error flag, returns true or false + + NOTES: ALL non-alpha characters are ignored, this includes whitespace, + although non-alpha characters will break up phonemes. +****************************************************************************/ + + +/* I add modifications to the traditional metaphone algorithm that you + might find in books. Define this if you want metaphone to behave + traditionally */ +#undef USE_TRADITIONAL_METAPHONE + +/* Special encodings */ +#define SH 'X' +#define TH '0' + +static char Lookahead(char *word, int how_far); +static void _metaphone(char *word, int max_phonemes, char **phoned_word); + +/* Metachar.h ... little bits about characters for metaphone */ + + +/*-- Character encoding array & accessing macros --*/ +/* Stolen directly out of the book... */ +static const char _codes[26] = { + 1, 16, 4, 16, 9, 2, 4, 16, 9, 2, 0, 2, 2, 2, 1, 4, 0, 2, 4, 4, 1, 0, 0, 0, 8, 0 +/* a b c d e f g h i j k l m n o p q r s t u v w x y z */ +}; + +static int +getcode(char c) +{ + if (isalpha((unsigned char) c)) + { + c = toupper((unsigned char) c); + /* Defend against non-ASCII letters */ + if (c >= 'A' && c <= 'Z') + return _codes[c - 'A']; + } + return 0; +} + +#define isvowel(c) (getcode(c) & 1) /* AEIOU */ + +/* These letters are passed through unchanged */ +#define NOCHANGE(c) (getcode(c) & 2) /* FJMNR */ + +/* These form diphthongs when preceding H */ +#define AFFECTH(c) (getcode(c) & 4) /* CGPST */ + +/* These make C and G soft */ +#define MAKESOFT(c) (getcode(c) & 8) /* EIY */ + +/* These prevent GH from becoming F */ +#define NOGHTOF(c) (getcode(c) & 16) /* BDH */ + +PG_FUNCTION_INFO_V1(levenshtein_with_costs); +Datum +levenshtein_with_costs(PG_FUNCTION_ARGS) +{ + text *src = PG_GETARG_TEXT_PP(0); + text *dst = PG_GETARG_TEXT_PP(1); + int ins_c = PG_GETARG_INT32(2); + int del_c = PG_GETARG_INT32(3); + int sub_c = PG_GETARG_INT32(4); + const char *s_data; + const char *t_data; + int s_bytes, + t_bytes; + + /* Extract a pointer to the actual character data */ + s_data = VARDATA_ANY(src); + t_data = VARDATA_ANY(dst); + /* Determine length of each string in bytes */ + s_bytes = VARSIZE_ANY_EXHDR(src); + t_bytes = VARSIZE_ANY_EXHDR(dst); + + PG_RETURN_INT32(varstr_levenshtein(s_data, s_bytes, t_data, t_bytes, + ins_c, del_c, sub_c, false)); +} + + +PG_FUNCTION_INFO_V1(levenshtein); +Datum +levenshtein(PG_FUNCTION_ARGS) +{ + text *src = PG_GETARG_TEXT_PP(0); + text *dst = PG_GETARG_TEXT_PP(1); + const char *s_data; + const char *t_data; + int s_bytes, + t_bytes; + + /* Extract a pointer to the actual character data */ + s_data = VARDATA_ANY(src); + t_data = VARDATA_ANY(dst); + /* Determine length of each string in bytes */ + s_bytes = VARSIZE_ANY_EXHDR(src); + t_bytes = VARSIZE_ANY_EXHDR(dst); + + PG_RETURN_INT32(varstr_levenshtein(s_data, s_bytes, t_data, t_bytes, + 1, 1, 1, false)); +} + + +PG_FUNCTION_INFO_V1(levenshtein_less_equal_with_costs); +Datum +levenshtein_less_equal_with_costs(PG_FUNCTION_ARGS) +{ + text *src = PG_GETARG_TEXT_PP(0); + text *dst = PG_GETARG_TEXT_PP(1); + int ins_c = PG_GETARG_INT32(2); + int del_c = PG_GETARG_INT32(3); + int sub_c = PG_GETARG_INT32(4); + int max_d = PG_GETARG_INT32(5); + const char *s_data; + const char *t_data; + int s_bytes, + t_bytes; + + /* Extract a pointer to the actual character data */ + s_data = VARDATA_ANY(src); + t_data = VARDATA_ANY(dst); + /* Determine length of each string in bytes */ + s_bytes = VARSIZE_ANY_EXHDR(src); + t_bytes = VARSIZE_ANY_EXHDR(dst); + + PG_RETURN_INT32(varstr_levenshtein_less_equal(s_data, s_bytes, + t_data, t_bytes, + ins_c, del_c, sub_c, + max_d, false)); +} + + +PG_FUNCTION_INFO_V1(levenshtein_less_equal); +Datum +levenshtein_less_equal(PG_FUNCTION_ARGS) +{ + text *src = PG_GETARG_TEXT_PP(0); + text *dst = PG_GETARG_TEXT_PP(1); + int max_d = PG_GETARG_INT32(2); + const char *s_data; + const char *t_data; + int s_bytes, + t_bytes; + + /* Extract a pointer to the actual character data */ + s_data = VARDATA_ANY(src); + t_data = VARDATA_ANY(dst); + /* Determine length of each string in bytes */ + s_bytes = VARSIZE_ANY_EXHDR(src); + t_bytes = VARSIZE_ANY_EXHDR(dst); + + PG_RETURN_INT32(varstr_levenshtein_less_equal(s_data, s_bytes, + t_data, t_bytes, + 1, 1, 1, + max_d, false)); +} + + +/* + * Calculates the metaphone of an input string. + * Returns number of characters requested + * (suggested value is 4) + */ +PG_FUNCTION_INFO_V1(metaphone); +Datum +metaphone(PG_FUNCTION_ARGS) +{ + char *str_i = TextDatumGetCString(PG_GETARG_DATUM(0)); + size_t str_i_len = strlen(str_i); + int reqlen; + char *metaph; + + /* return an empty string if we receive one */ + if (!(str_i_len > 0)) + PG_RETURN_TEXT_P(cstring_to_text("")); + + if (str_i_len > MAX_METAPHONE_STRLEN) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("argument exceeds the maximum length of %d bytes", + MAX_METAPHONE_STRLEN))); + + reqlen = PG_GETARG_INT32(1); + if (reqlen > MAX_METAPHONE_STRLEN) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("output exceeds the maximum length of %d bytes", + MAX_METAPHONE_STRLEN))); + + if (!(reqlen > 0)) + ereport(ERROR, + (errcode(ERRCODE_ZERO_LENGTH_CHARACTER_STRING), + errmsg("output cannot be empty string"))); + + _metaphone(str_i, reqlen, &metaph); + PG_RETURN_TEXT_P(cstring_to_text(metaph)); +} + + +/* + * Original code by Michael G Schwern starts here. + * Code slightly modified for use as PostgreSQL + * function (palloc, etc). + */ + +/* I suppose I could have been using a character pointer instead of + * accessing the array directly... */ + +/* Look at the next letter in the word */ +#define Next_Letter (toupper((unsigned char) word[w_idx+1])) +/* Look at the current letter in the word */ +#define Curr_Letter (toupper((unsigned char) word[w_idx])) +/* Go N letters back. */ +#define Look_Back_Letter(n) \ + (w_idx >= (n) ? toupper((unsigned char) word[w_idx-(n)]) : '\0') +/* Previous letter. I dunno, should this return null on failure? */ +#define Prev_Letter (Look_Back_Letter(1)) +/* Look two letters down. It makes sure you don't walk off the string. */ +#define After_Next_Letter \ + (Next_Letter != '\0' ? toupper((unsigned char) word[w_idx+2]) : '\0') +#define Look_Ahead_Letter(n) toupper((unsigned char) Lookahead(word+w_idx, n)) + + +/* Allows us to safely look ahead an arbitrary # of letters */ +/* I probably could have just used strlen... */ +static char +Lookahead(char *word, int how_far) +{ + char letter_ahead = '\0'; /* null by default */ + int idx; + + for (idx = 0; word[idx] != '\0' && idx < how_far; idx++); + /* Edge forward in the string... */ + + letter_ahead = word[idx]; /* idx will be either == to how_far or at the + * end of the string */ + return letter_ahead; +} + + +/* phonize one letter */ +#define Phonize(c) do {(*phoned_word)[p_idx++] = c;} while (0) +/* Slap a null character on the end of the phoned word */ +#define End_Phoned_Word do {(*phoned_word)[p_idx] = '\0';} while (0) +/* How long is the phoned word? */ +#define Phone_Len (p_idx) + +/* Note is a letter is a 'break' in the word */ +#define Isbreak(c) (!isalpha((unsigned char) (c))) + + +static void +_metaphone(char *word, /* IN */ + int max_phonemes, + char **phoned_word) /* OUT */ +{ + int w_idx = 0; /* point in the phonization we're at. */ + int p_idx = 0; /* end of the phoned phrase */ + + /*-- Parameter checks --*/ + + /* + * Shouldn't be necessary, but left these here anyway jec Aug 3, 2001 + */ + + /* Negative phoneme length is meaningless */ + if (!(max_phonemes > 0)) + /* internal error */ + elog(ERROR, "metaphone: Requested output length must be > 0"); + + /* Empty/null string is meaningless */ + if ((word == NULL) || !(strlen(word) > 0)) + /* internal error */ + elog(ERROR, "metaphone: Input string length must be > 0"); + + /*-- Allocate memory for our phoned_phrase --*/ + if (max_phonemes == 0) + { /* Assume largest possible */ + *phoned_word = palloc(sizeof(char) * strlen(word) + 1); + } + else + { + *phoned_word = palloc(sizeof(char) * max_phonemes + 1); + } + + /*-- The first phoneme has to be processed specially. --*/ + /* Find our first letter */ + for (; !isalpha((unsigned char) (Curr_Letter)); w_idx++) + { + /* On the off chance we were given nothing but crap... */ + if (Curr_Letter == '\0') + { + End_Phoned_Word; + return; + } + } + + switch (Curr_Letter) + { + /* AE becomes E */ + case 'A': + if (Next_Letter == 'E') + { + Phonize('E'); + w_idx += 2; + } + /* Remember, preserve vowels at the beginning */ + else + { + Phonize('A'); + w_idx++; + } + break; + /* [GKP]N becomes N */ + case 'G': + case 'K': + case 'P': + if (Next_Letter == 'N') + { + Phonize('N'); + w_idx += 2; + } + break; + + /* + * WH becomes H, WR becomes R W if followed by a vowel + */ + case 'W': + if (Next_Letter == 'H' || + Next_Letter == 'R') + { + Phonize(Next_Letter); + w_idx += 2; + } + else if (isvowel(Next_Letter)) + { + Phonize('W'); + w_idx += 2; + } + /* else ignore */ + break; + /* X becomes S */ + case 'X': + Phonize('S'); + w_idx++; + break; + /* Vowels are kept */ + + /* + * We did A already case 'A': case 'a': + */ + case 'E': + case 'I': + case 'O': + case 'U': + Phonize(Curr_Letter); + w_idx++; + break; + default: + /* do nothing */ + break; + } + + + + /* On to the metaphoning */ + for (; Curr_Letter != '\0' && + (max_phonemes == 0 || Phone_Len < max_phonemes); + w_idx++) + { + /* + * How many letters to skip because an earlier encoding handled + * multiple letters + */ + unsigned short int skip_letter = 0; + + + /* + * THOUGHT: It would be nice if, rather than having things like... + * well, SCI. For SCI you encode the S, then have to remember to skip + * the C. So the phonome SCI invades both S and C. It would be + * better, IMHO, to skip the C from the S part of the encoding. Hell, + * I'm trying it. + */ + + /* Ignore non-alphas */ + if (!isalpha((unsigned char) (Curr_Letter))) + continue; + + /* Drop duplicates, except CC */ + if (Curr_Letter == Prev_Letter && + Curr_Letter != 'C') + continue; + + switch (Curr_Letter) + { + /* B -> B unless in MB */ + case 'B': + if (Prev_Letter != 'M') + Phonize('B'); + break; + + /* + * 'sh' if -CIA- or -CH, but not SCH, except SCHW. (SCHW is + * handled in S) S if -CI-, -CE- or -CY- dropped if -SCI-, + * SCE-, -SCY- (handed in S) else K + */ + case 'C': + if (MAKESOFT(Next_Letter)) + { /* C[IEY] */ + if (After_Next_Letter == 'A' && + Next_Letter == 'I') + { /* CIA */ + Phonize(SH); + } + /* SC[IEY] */ + else if (Prev_Letter == 'S') + { + /* Dropped */ + } + else + Phonize('S'); + } + else if (Next_Letter == 'H') + { +#ifndef USE_TRADITIONAL_METAPHONE + if (After_Next_Letter == 'R' || + Prev_Letter == 'S') + { /* Christ, School */ + Phonize('K'); + } + else + Phonize(SH); +#else + Phonize(SH); +#endif + skip_letter++; + } + else + Phonize('K'); + break; + + /* + * J if in -DGE-, -DGI- or -DGY- else T + */ + case 'D': + if (Next_Letter == 'G' && + MAKESOFT(After_Next_Letter)) + { + Phonize('J'); + skip_letter++; + } + else + Phonize('T'); + break; + + /* + * F if in -GH and not B--GH, D--GH, -H--GH, -H---GH else + * dropped if -GNED, -GN, else dropped if -DGE-, -DGI- or + * -DGY- (handled in D) else J if in -GE-, -GI, -GY and not GG + * else K + */ + case 'G': + if (Next_Letter == 'H') + { + if (!(NOGHTOF(Look_Back_Letter(3)) || + Look_Back_Letter(4) == 'H')) + { + Phonize('F'); + skip_letter++; + } + else + { + /* silent */ + } + } + else if (Next_Letter == 'N') + { + if (Isbreak(After_Next_Letter) || + (After_Next_Letter == 'E' && + Look_Ahead_Letter(3) == 'D')) + { + /* dropped */ + } + else + Phonize('K'); + } + else if (MAKESOFT(Next_Letter) && + Prev_Letter != 'G') + Phonize('J'); + else + Phonize('K'); + break; + /* H if before a vowel and not after C,G,P,S,T */ + case 'H': + if (isvowel(Next_Letter) && + !AFFECTH(Prev_Letter)) + Phonize('H'); + break; + + /* + * dropped if after C else K + */ + case 'K': + if (Prev_Letter != 'C') + Phonize('K'); + break; + + /* + * F if before H else P + */ + case 'P': + if (Next_Letter == 'H') + Phonize('F'); + else + Phonize('P'); + break; + + /* + * K + */ + case 'Q': + Phonize('K'); + break; + + /* + * 'sh' in -SH-, -SIO- or -SIA- or -SCHW- else S + */ + case 'S': + if (Next_Letter == 'I' && + (After_Next_Letter == 'O' || + After_Next_Letter == 'A')) + Phonize(SH); + else if (Next_Letter == 'H') + { + Phonize(SH); + skip_letter++; + } +#ifndef USE_TRADITIONAL_METAPHONE + else if (Next_Letter == 'C' && + Look_Ahead_Letter(2) == 'H' && + Look_Ahead_Letter(3) == 'W') + { + Phonize(SH); + skip_letter += 2; + } +#endif + else + Phonize('S'); + break; + + /* + * 'sh' in -TIA- or -TIO- else 'th' before H else T + */ + case 'T': + if (Next_Letter == 'I' && + (After_Next_Letter == 'O' || + After_Next_Letter == 'A')) + Phonize(SH); + else if (Next_Letter == 'H') + { + Phonize(TH); + skip_letter++; + } + else + Phonize('T'); + break; + /* F */ + case 'V': + Phonize('F'); + break; + /* W before a vowel, else dropped */ + case 'W': + if (isvowel(Next_Letter)) + Phonize('W'); + break; + /* KS */ + case 'X': + Phonize('K'); + if (max_phonemes == 0 || Phone_Len < max_phonemes) + Phonize('S'); + break; + /* Y if followed by a vowel */ + case 'Y': + if (isvowel(Next_Letter)) + Phonize('Y'); + break; + /* S */ + case 'Z': + Phonize('S'); + break; + /* No transformation */ + case 'F': + case 'J': + case 'L': + case 'M': + case 'N': + case 'R': + Phonize(Curr_Letter); + break; + default: + /* nothing */ + break; + } /* END SWITCH */ + + w_idx += skip_letter; + } /* END FOR */ + + End_Phoned_Word; +} /* END metaphone */ + + +/* + * SQL function: soundex(text) returns text + */ +PG_FUNCTION_INFO_V1(soundex); + +Datum +soundex(PG_FUNCTION_ARGS) +{ + char outstr[SOUNDEX_LEN + 1]; + char *arg; + + arg = text_to_cstring(PG_GETARG_TEXT_PP(0)); + + _soundex(arg, outstr); + + PG_RETURN_TEXT_P(cstring_to_text(outstr)); +} + +static void +_soundex(const char *instr, char *outstr) +{ + int count; + + AssertArg(instr); + AssertArg(outstr); + + /* Skip leading non-alphabetic characters */ + while (*instr && !isalpha((unsigned char) *instr)) + ++instr; + + /* If no string left, return all-zeroes buffer */ + if (!*instr) + { + memset(outstr, '\0', SOUNDEX_LEN + 1); + return; + } + + /* Take the first letter as is */ + *outstr++ = (char) toupper((unsigned char) *instr++); + + count = 1; + while (*instr && count < SOUNDEX_LEN) + { + if (isalpha((unsigned char) *instr) && + soundex_code(*instr) != soundex_code(*(instr - 1))) + { + *outstr = soundex_code(*instr); + if (*outstr != '0') + { + ++outstr; + ++count; + } + } + ++instr; + } + + /* Fill with 0's */ + while (count < SOUNDEX_LEN) + { + *outstr = '0'; + ++outstr; + ++count; + } + + /* And null-terminate */ + *outstr = '\0'; +} + +PG_FUNCTION_INFO_V1(difference); + +Datum +difference(PG_FUNCTION_ARGS) +{ + char sndx1[SOUNDEX_LEN + 1], + sndx2[SOUNDEX_LEN + 1]; + int i, + result; + + _soundex(text_to_cstring(PG_GETARG_TEXT_PP(0)), sndx1); + _soundex(text_to_cstring(PG_GETARG_TEXT_PP(1)), sndx2); + + result = 0; + for (i = 0; i < SOUNDEX_LEN; i++) + { + if (sndx1[i] == sndx2[i]) + result++; + } + + PG_RETURN_INT32(result); +} diff --git a/contrib/fuzzystrmatch/fuzzystrmatch.control b/contrib/fuzzystrmatch/fuzzystrmatch.control new file mode 100644 index 0000000..3cd6660 --- /dev/null +++ b/contrib/fuzzystrmatch/fuzzystrmatch.control @@ -0,0 +1,6 @@ +# fuzzystrmatch extension +comment = 'determine similarities and distance between strings' +default_version = '1.1' +module_pathname = '$libdir/fuzzystrmatch' +relocatable = true +trusted = true diff --git a/contrib/fuzzystrmatch/sql/fuzzystrmatch.sql b/contrib/fuzzystrmatch/sql/fuzzystrmatch.sql new file mode 100644 index 0000000..1d0e219 --- /dev/null +++ b/contrib/fuzzystrmatch/sql/fuzzystrmatch.sql @@ -0,0 +1,22 @@ +CREATE EXTENSION fuzzystrmatch; + + +SELECT soundex('hello world!'); + +SELECT soundex('Anne'), soundex('Ann'), difference('Anne', 'Ann'); +SELECT soundex('Anne'), soundex('Andrew'), difference('Anne', 'Andrew'); +SELECT soundex('Anne'), soundex('Margaret'), difference('Anne', 'Margaret'); +SELECT soundex(''), difference('', ''); + + +SELECT levenshtein('GUMBO', 'GAMBOL'); +SELECT levenshtein('GUMBO', 'GAMBOL', 2, 1, 1); +SELECT levenshtein_less_equal('extensive', 'exhaustive', 2); +SELECT levenshtein_less_equal('extensive', 'exhaustive', 4); + + +SELECT metaphone('GUMBO', 4); + + +SELECT dmetaphone('gumbo'); +SELECT dmetaphone_alt('gumbo'); |