PostgreSQL Source Code git master
Loading...
Searching...
No Matches
fuzzystrmatch.c
Go to the documentation of this file.
1/*
2 * fuzzystrmatch.c
3 *
4 * Functions for "fuzzy" comparison of strings
5 *
6 * Joe Conway <mail@joeconway.com>
7 *
8 * contrib/fuzzystrmatch/fuzzystrmatch.c
9 * Copyright (c) 2001-2026, PostgreSQL Global Development Group
10 * ALL RIGHTS RESERVED;
11 *
12 * metaphone()
13 * -----------
14 * Modified for PostgreSQL by Joe Conway.
15 * Based on CPAN's "Text-Metaphone-1.96" by Michael G Schwern <schwern@pobox.com>
16 * Code slightly modified for use as PostgreSQL function (palloc, elog, etc).
17 * Metaphone was originally created by Lawrence Philips and presented in article
18 * in "Computer Language" December 1990 issue.
19 *
20 * Permission to use, copy, modify, and distribute this software and its
21 * documentation for any purpose, without fee, and without a written agreement
22 * is hereby granted, provided that the above copyright notice and this
23 * paragraph and the following two paragraphs appear in all copies.
24 *
25 * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
26 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
27 * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
28 * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 *
31 * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
32 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
33 * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
34 * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
35 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
36 *
37 */
38
39#include "postgres.h"
40
41#include <ctype.h>
42
43#include "utils/builtins.h"
44#include "utils/varlena.h"
45#include "varatt.h"
46
48 .name = "fuzzystrmatch",
49 .version = PG_VERSION
50);
51
52/*
53 * Soundex
54 */
55static void _soundex(const char *instr, char *outstr);
56
57#define SOUNDEX_LEN 4
58
59/* ABCDEFGHIJKLMNOPQRSTUVWXYZ */
60static const char *const soundex_table = "01230120022455012623010202";
61
62static char
64{
65 letter = pg_ascii_toupper((unsigned char) letter);
66 /* Defend against non-ASCII letters */
67 if (letter >= 'A' && letter <= 'Z')
68 return soundex_table[letter - 'A'];
69 return letter;
70}
71
72/*
73 * Metaphone
74 */
75#define MAX_METAPHONE_STRLEN 255
76
77/*
78 * Original code by Michael G Schwern starts here.
79 * Code slightly modified for use as PostgreSQL function.
80 */
81
82
83/**************************************************************************
84 metaphone -- Breaks english phrases down into their phonemes.
85
86 Input
87 word -- An english word to be phonized
88 max_phonemes -- How many phonemes to calculate. If 0, then it
89 will phonize the entire phrase.
90 phoned_word -- The final phonized word. (We'll allocate the
91 memory.)
92 Output
93 error -- A simple error flag, returns true or false
94
95 NOTES: ALL non-alpha characters are ignored, this includes whitespace,
96 although non-alpha characters will break up phonemes.
97****************************************************************************/
98
99
100/*
101 * I add modifications to the traditional metaphone algorithm that you
102 * might find in books. Define this if you want metaphone to behave
103 * traditionally
104 */
105#undef USE_TRADITIONAL_METAPHONE
106
107/* Special encodings */
108#define SH 'X'
109#define TH '0'
110
111static char Lookahead(char *word, int how_far);
112static void _metaphone(char *word, int max_phonemes, char **phoned_word);
113
114/* Metachar.h ... little bits about characters for metaphone */
115
116
117/*-- Character encoding array & accessing macros --*/
118/* Stolen directly out of the book... */
119static const char _codes[26] = {
120 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
121/* 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 */
122};
123
124static int
126{
127 c = pg_ascii_toupper((unsigned char) c);
128 /* Defend against non-ASCII letters */
129 if (c >= 'A' && c <= 'Z')
130 return _codes[c - 'A'];
131
132 return 0;
133}
134
135static bool
137{
138 return (c >= 'A' && c <= 'Z') ||
139 (c >= 'a' && c <= 'z');
140}
141
142#define isvowel(c) (getcode(c) & 1) /* AEIOU */
143
144/* These letters are passed through unchanged */
145#define NOCHANGE(c) (getcode(c) & 2) /* FJMNR */
146
147/* These form diphthongs when preceding H */
148#define AFFECTH(c) (getcode(c) & 4) /* CGPST */
149
150/* These make C and G soft */
151#define MAKESOFT(c) (getcode(c) & 8) /* EIY */
152
153/* These prevent GH from becoming F */
154#define NOGHTOF(c) (getcode(c) & 16) /* BDH */
155
157Datum
159{
160 text *src = PG_GETARG_TEXT_PP(0);
162 int ins_c = PG_GETARG_INT32(2);
163 int del_c = PG_GETARG_INT32(3);
164 int sub_c = PG_GETARG_INT32(4);
165 const char *s_data;
166 const char *t_data;
167 int s_bytes,
168 t_bytes;
169
170 /* Extract a pointer to the actual character data */
171 s_data = VARDATA_ANY(src);
172 t_data = VARDATA_ANY(dst);
173 /* Determine length of each string in bytes */
176
178 ins_c, del_c, sub_c, false));
179}
180
181
183Datum
185{
186 text *src = PG_GETARG_TEXT_PP(0);
188 const char *s_data;
189 const char *t_data;
190 int s_bytes,
191 t_bytes;
192
193 /* Extract a pointer to the actual character data */
194 s_data = VARDATA_ANY(src);
195 t_data = VARDATA_ANY(dst);
196 /* Determine length of each string in bytes */
199
201 1, 1, 1, false));
202}
203
204
206Datum
208{
209 text *src = PG_GETARG_TEXT_PP(0);
211 int ins_c = PG_GETARG_INT32(2);
212 int del_c = PG_GETARG_INT32(3);
213 int sub_c = PG_GETARG_INT32(4);
214 int max_d = PG_GETARG_INT32(5);
215 const char *s_data;
216 const char *t_data;
217 int s_bytes,
218 t_bytes;
219
220 /* Extract a pointer to the actual character data */
221 s_data = VARDATA_ANY(src);
222 t_data = VARDATA_ANY(dst);
223 /* Determine length of each string in bytes */
226
228 t_data, t_bytes,
229 ins_c, del_c, sub_c,
230 max_d, false));
231}
232
233
235Datum
237{
238 text *src = PG_GETARG_TEXT_PP(0);
240 int max_d = PG_GETARG_INT32(2);
241 const char *s_data;
242 const char *t_data;
243 int s_bytes,
244 t_bytes;
245
246 /* Extract a pointer to the actual character data */
247 s_data = VARDATA_ANY(src);
248 t_data = VARDATA_ANY(dst);
249 /* Determine length of each string in bytes */
252
254 t_data, t_bytes,
255 1, 1, 1,
256 max_d, false));
257}
258
259
260/*
261 * Calculates the metaphone of an input string.
262 * Returns number of characters requested
263 * (suggested value is 4)
264 */
266Datum
268{
270 size_t str_i_len = strlen(str_i);
271 int reqlen;
272 char *metaph;
273
274 /* return an empty string if we receive one */
275 if (!(str_i_len > 0))
277
281 errmsg("argument exceeds the maximum length of %d bytes",
283
288 errmsg("output exceeds the maximum length of %d bytes",
290
291 if (!(reqlen > 0))
294 errmsg("output cannot be empty string")));
295
298}
299
300
301/*
302 * Original code by Michael G Schwern starts here.
303 * Code slightly modified for use as PostgreSQL
304 * function (palloc, etc).
305 */
306
307/*
308 * I suppose I could have been using a character pointer instead of
309 * accessing the array directly...
310 */
311
312/* Look at the next letter in the word */
313#define Next_Letter (pg_ascii_toupper((unsigned char) word[w_idx+1]))
314/* Look at the current letter in the word */
315#define Curr_Letter (pg_ascii_toupper((unsigned char) word[w_idx]))
316/* Go N letters back. */
317#define Look_Back_Letter(n) \
318 (w_idx >= (n) ? pg_ascii_toupper((unsigned char) word[w_idx-(n)]) : '\0')
319/* Previous letter. I dunno, should this return null on failure? */
320#define Prev_Letter (Look_Back_Letter(1))
321/* Look two letters down. It makes sure you don't walk off the string. */
322#define After_Next_Letter \
323 (Next_Letter != '\0' ? pg_ascii_toupper((unsigned char) word[w_idx+2]) : '\0')
324#define Look_Ahead_Letter(n) pg_ascii_toupper((unsigned char) Lookahead(word+w_idx, n))
325
326
327/* Allows us to safely look ahead an arbitrary # of letters */
328/* I probably could have just used strlen... */
329static char
331{
332 char letter_ahead = '\0'; /* null by default */
333 int idx;
334
335 for (idx = 0; word[idx] != '\0' && idx < how_far; idx++);
336 /* Edge forward in the string... */
337
338 letter_ahead = word[idx]; /* idx will be either == to how_far or at the
339 * end of the string */
340 return letter_ahead;
341}
342
343
344/* phonize one letter */
345#define Phonize(c) do {(*phoned_word)[p_idx++] = c;} while (0)
346/* Slap a null character on the end of the phoned word */
347#define End_Phoned_Word do {(*phoned_word)[p_idx] = '\0';} while (0)
348/* How long is the phoned word? */
349#define Phone_Len (p_idx)
350
351/* Note is a letter is a 'break' in the word */
352#define Isbreak(c) (!ascii_isalpha((unsigned char) (c)))
353
354
355static void
356_metaphone(char *word, /* IN */
357 int max_phonemes,
358 char **phoned_word) /* OUT */
359{
360 int w_idx = 0; /* point in the phonization we're at. */
361 int p_idx = 0; /* end of the phoned phrase */
362
363 /*-- Parameter checks --*/
364
365 /*
366 * Shouldn't be necessary, but left these here anyway jec Aug 3, 2001
367 */
368
369 /* Negative phoneme length is meaningless */
370 if (!(max_phonemes > 0))
371 /* internal error */
372 elog(ERROR, "metaphone: Requested output length must be > 0");
373
374 /* Empty/null string is meaningless */
375 if ((word == NULL) || !(strlen(word) > 0))
376 /* internal error */
377 elog(ERROR, "metaphone: Input string length must be > 0");
378
379 /*-- Allocate memory for our phoned_phrase --*/
380 if (max_phonemes == 0)
381 { /* Assume largest possible */
382 *phoned_word = palloc(sizeof(char) * strlen(word) + 1);
383 }
384 else
385 {
386 *phoned_word = palloc(sizeof(char) * max_phonemes + 1);
387 }
388
389 /*-- The first phoneme has to be processed specially. --*/
390 /* Find our first letter */
391 for (; !ascii_isalpha((unsigned char) (Curr_Letter)); w_idx++)
392 {
393 /* On the off chance we were given nothing but crap... */
394 if (Curr_Letter == '\0')
395 {
397 return;
398 }
399 }
400
401 switch (Curr_Letter)
402 {
403 /* AE becomes E */
404 case 'A':
405 if (Next_Letter == 'E')
406 {
407 Phonize('E');
408 w_idx += 2;
409 }
410 /* Remember, preserve vowels at the beginning */
411 else
412 {
413 Phonize('A');
414 w_idx++;
415 }
416 break;
417 /* [GKP]N becomes N */
418 case 'G':
419 case 'K':
420 case 'P':
421 if (Next_Letter == 'N')
422 {
423 Phonize('N');
424 w_idx += 2;
425 }
426 break;
427
428 /*
429 * WH becomes H, WR becomes R W if followed by a vowel
430 */
431 case 'W':
432 if (Next_Letter == 'H' ||
433 Next_Letter == 'R')
434 {
436 w_idx += 2;
437 }
438 else if (isvowel(Next_Letter))
439 {
440 Phonize('W');
441 w_idx += 2;
442 }
443 /* else ignore */
444 break;
445 /* X becomes S */
446 case 'X':
447 Phonize('S');
448 w_idx++;
449 break;
450 /* Vowels are kept */
451
452 /*
453 * We did A already case 'A': case 'a':
454 */
455 case 'E':
456 case 'I':
457 case 'O':
458 case 'U':
460 w_idx++;
461 break;
462 default:
463 /* do nothing */
464 break;
465 }
466
467
468
469 /* On to the metaphoning */
470 for (; Curr_Letter != '\0' &&
472 w_idx++)
473 {
474 /*
475 * How many letters to skip because an earlier encoding handled
476 * multiple letters
477 */
478 unsigned short int skip_letter = 0;
479
480
481 /*
482 * THOUGHT: It would be nice if, rather than having things like...
483 * well, SCI. For SCI you encode the S, then have to remember to skip
484 * the C. So the phonome SCI invades both S and C. It would be
485 * better, IMHO, to skip the C from the S part of the encoding. Hell,
486 * I'm trying it.
487 */
488
489 /* Ignore non-alphas */
490 if (!ascii_isalpha((unsigned char) (Curr_Letter)))
491 continue;
492
493 /* Drop duplicates, except CC */
494 if (Curr_Letter == Prev_Letter &&
495 Curr_Letter != 'C')
496 continue;
497
498 switch (Curr_Letter)
499 {
500 /* B -> B unless in MB */
501 case 'B':
502 if (Prev_Letter != 'M')
503 Phonize('B');
504 break;
505
506 /*
507 * 'sh' if -CIA- or -CH, but not SCH, except SCHW. (SCHW is
508 * handled in S) S if -CI-, -CE- or -CY- dropped if -SCI-,
509 * SCE-, -SCY- (handed in S) else K
510 */
511 case 'C':
513 { /* C[IEY] */
514 if (After_Next_Letter == 'A' &&
515 Next_Letter == 'I')
516 { /* CIA */
517 Phonize(SH);
518 }
519 /* SC[IEY] */
520 else if (Prev_Letter == 'S')
521 {
522 /* Dropped */
523 }
524 else
525 Phonize('S');
526 }
527 else if (Next_Letter == 'H')
528 {
529#ifndef USE_TRADITIONAL_METAPHONE
530 if (After_Next_Letter == 'R' ||
531 Prev_Letter == 'S')
532 { /* Christ, School */
533 Phonize('K');
534 }
535 else
536 Phonize(SH);
537#else
538 Phonize(SH);
539#endif
540 skip_letter++;
541 }
542 else
543 Phonize('K');
544 break;
545
546 /*
547 * J if in -DGE-, -DGI- or -DGY- else T
548 */
549 case 'D':
550 if (Next_Letter == 'G' &&
552 {
553 Phonize('J');
554 skip_letter++;
555 }
556 else
557 Phonize('T');
558 break;
559
560 /*
561 * F if in -GH and not B--GH, D--GH, -H--GH, -H---GH else
562 * dropped if -GNED, -GN, else dropped if -DGE-, -DGI- or
563 * -DGY- (handled in D) else J if in -GE-, -GI, -GY and not GG
564 * else K
565 */
566 case 'G':
567 if (Next_Letter == 'H')
568 {
569 if (!(NOGHTOF(Look_Back_Letter(3)) ||
570 Look_Back_Letter(4) == 'H'))
571 {
572 Phonize('F');
573 skip_letter++;
574 }
575 else
576 {
577 /* silent */
578 }
579 }
580 else if (Next_Letter == 'N')
581 {
583 (After_Next_Letter == 'E' &&
584 Look_Ahead_Letter(3) == 'D'))
585 {
586 /* dropped */
587 }
588 else
589 Phonize('K');
590 }
591 else if (MAKESOFT(Next_Letter) &&
592 Prev_Letter != 'G')
593 Phonize('J');
594 else
595 Phonize('K');
596 break;
597 /* H if before a vowel and not after C,G,P,S,T */
598 case 'H':
599 if (isvowel(Next_Letter) &&
601 Phonize('H');
602 break;
603
604 /*
605 * dropped if after C else K
606 */
607 case 'K':
608 if (Prev_Letter != 'C')
609 Phonize('K');
610 break;
611
612 /*
613 * F if before H else P
614 */
615 case 'P':
616 if (Next_Letter == 'H')
617 Phonize('F');
618 else
619 Phonize('P');
620 break;
621
622 /*
623 * K
624 */
625 case 'Q':
626 Phonize('K');
627 break;
628
629 /*
630 * 'sh' in -SH-, -SIO- or -SIA- or -SCHW- else S
631 */
632 case 'S':
633 if (Next_Letter == 'I' &&
634 (After_Next_Letter == 'O' ||
635 After_Next_Letter == 'A'))
636 Phonize(SH);
637 else if (Next_Letter == 'H')
638 {
639 Phonize(SH);
640 skip_letter++;
641 }
642#ifndef USE_TRADITIONAL_METAPHONE
643 else if (Next_Letter == 'C' &&
644 Look_Ahead_Letter(2) == 'H' &&
645 Look_Ahead_Letter(3) == 'W')
646 {
647 Phonize(SH);
648 skip_letter += 2;
649 }
650#endif
651 else
652 Phonize('S');
653 break;
654
655 /*
656 * 'sh' in -TIA- or -TIO- else 'th' before H else T
657 */
658 case 'T':
659 if (Next_Letter == 'I' &&
660 (After_Next_Letter == 'O' ||
661 After_Next_Letter == 'A'))
662 Phonize(SH);
663 else if (Next_Letter == 'H')
664 {
665 Phonize(TH);
666 skip_letter++;
667 }
668 else
669 Phonize('T');
670 break;
671 /* F */
672 case 'V':
673 Phonize('F');
674 break;
675 /* W before a vowel, else dropped */
676 case 'W':
677 if (isvowel(Next_Letter))
678 Phonize('W');
679 break;
680 /* KS */
681 case 'X':
682 Phonize('K');
683 if (max_phonemes == 0 || Phone_Len < max_phonemes)
684 Phonize('S');
685 break;
686 /* Y if followed by a vowel */
687 case 'Y':
688 if (isvowel(Next_Letter))
689 Phonize('Y');
690 break;
691 /* S */
692 case 'Z':
693 Phonize('S');
694 break;
695 /* No transformation */
696 case 'F':
697 case 'J':
698 case 'L':
699 case 'M':
700 case 'N':
701 case 'R':
703 break;
704 default:
705 /* nothing */
706 break;
707 } /* END SWITCH */
708
710 } /* END FOR */
711
713} /* END metaphone */
714
715
716/*
717 * SQL function: soundex(text) returns text
718 */
720
721Datum
733
734static void
735_soundex(const char *instr, char *outstr)
736{
737 int count;
738
739 Assert(instr);
740 Assert(outstr);
741
742 /* Skip leading non-alphabetic characters */
743 while (*instr && !ascii_isalpha((unsigned char) *instr))
744 ++instr;
745
746 /* If no string left, return all-zeroes buffer */
747 if (!*instr)
748 {
749 memset(outstr, '\0', SOUNDEX_LEN + 1);
750 return;
751 }
752
753 /* Take the first letter as is */
754 *outstr++ = (char) pg_ascii_toupper((unsigned char) *instr++);
755
756 count = 1;
757 while (*instr && count < SOUNDEX_LEN)
758 {
759 if (ascii_isalpha((unsigned char) *instr) &&
760 soundex_code(*instr) != soundex_code(*(instr - 1)))
761 {
762 *outstr = soundex_code(*instr);
763 if (*outstr != '0')
764 {
765 ++outstr;
766 ++count;
767 }
768 }
769 ++instr;
770 }
771
772 /* Fill with 0's */
773 while (count < SOUNDEX_LEN)
774 {
775 *outstr = '0';
776 ++outstr;
777 ++count;
778 }
779
780 /* And null-terminate */
781 *outstr = '\0';
782}
783
785
786Datum
788{
789 char sndx1[SOUNDEX_LEN + 1],
790 sndx2[SOUNDEX_LEN + 1];
791 int i,
792 result;
793
796
797 result = 0;
798 for (i = 0; i < SOUNDEX_LEN; i++)
799 {
800 if (sndx1[i] == sndx2[i])
801 result++;
802 }
803
805}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:263
#define TextDatumGetCString(d)
Definition builtins.h:99
#define Assert(condition)
Definition c.h:943
uint32 result
Datum arg
Definition elog.c:1323
int errcode(int sqlerrcode)
Definition elog.c:875
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
#define PG_GETARG_TEXT_PP(n)
Definition fmgr.h:310
#define PG_MODULE_MAGIC_EXT(...)
Definition fmgr.h:540
#define PG_GETARG_DATUM(n)
Definition fmgr.h:268
#define PG_FUNCTION_INFO_V1(funcname)
Definition fmgr.h:417
#define PG_RETURN_TEXT_P(x)
Definition fmgr.h:374
#define PG_RETURN_INT32(x)
Definition fmgr.h:355
#define PG_GETARG_INT32(n)
Definition fmgr.h:269
#define PG_FUNCTION_ARGS
Definition fmgr.h:193
Datum metaphone(PG_FUNCTION_ARGS)
static void _metaphone(char *word, int max_phonemes, char **phoned_word)
#define SOUNDEX_LEN
#define After_Next_Letter
Datum levenshtein_less_equal_with_costs(PG_FUNCTION_ARGS)
#define Look_Back_Letter(n)
#define Curr_Letter
static const char *const soundex_table
#define SH
#define MAKESOFT(c)
Datum soundex(PG_FUNCTION_ARGS)
static char soundex_code(char letter)
static const char _codes[26]
Datum levenshtein_with_costs(PG_FUNCTION_ARGS)
#define Isbreak(c)
#define End_Phoned_Word
#define isvowel(c)
#define Prev_Letter
static bool ascii_isalpha(char c)
#define TH
#define NOGHTOF(c)
#define Next_Letter
static void _soundex(const char *instr, char *outstr)
#define Phonize(c)
static int getcode(char c)
Datum difference(PG_FUNCTION_ARGS)
#define MAX_METAPHONE_STRLEN
static char Lookahead(char *word, int how_far)
#define AFFECTH(c)
#define Phone_Len
Datum levenshtein_less_equal(PG_FUNCTION_ARGS)
#define Look_Ahead_Letter(n)
Datum levenshtein(PG_FUNCTION_ARGS)
int i
Definition isn.c:77
int varstr_levenshtein(const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, bool trusted)
Definition levenshtein.c:73
void * palloc(Size size)
Definition mcxt.c:1390
static char * errmsg
static unsigned char pg_ascii_toupper(unsigned char ch)
Definition port.h:178
uint64_t Datum
Definition postgres.h:70
char * c
static int fb(int x)
static void word(struct vars *v, int dir, struct state *lp, struct state *rp)
Definition regcomp.c:1477
Definition c.h:776
static Size VARSIZE_ANY_EXHDR(const void *PTR)
Definition varatt.h:472
static char * VARDATA_ANY(const void *PTR)
Definition varatt.h:486
text * cstring_to_text(const char *s)
Definition varlena.c:184
char * text_to_cstring(const text *t)
Definition varlena.c:217
int varstr_levenshtein_less_equal(const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, int max_d, bool trusted)
const char * name