]> granicus.if.org Git - postgresql/blob - contrib/fuzzystrmatch/fuzzystrmatch.c
b48edb05ba69b9f0c5709b6aec703fc00231b4ad
[postgresql] / contrib / fuzzystrmatch / fuzzystrmatch.c
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-2015, 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 "mb/pg_wchar.h"
44 #include "utils/builtins.h"
45
46 PG_MODULE_MAGIC;
47
48 /*
49  * Soundex
50  */
51 static void _soundex(const char *instr, char *outstr);
52
53 #define SOUNDEX_LEN 4
54
55 /*                                                                      ABCDEFGHIJKLMNOPQRSTUVWXYZ */
56 static const char *soundex_table = "01230120022455012623010202";
57
58 static char
59 soundex_code(char letter)
60 {
61         letter = toupper((unsigned char) letter);
62         /* Defend against non-ASCII letters */
63         if (letter >= 'A' && letter <= 'Z')
64                 return soundex_table[letter - 'A'];
65         return letter;
66 }
67
68 /*
69  * Metaphone
70  */
71 #define MAX_METAPHONE_STRLEN            255
72
73 /*
74  * Original code by Michael G Schwern starts here.
75  * Code slightly modified for use as PostgreSQL function.
76  */
77
78
79 /**************************************************************************
80         metaphone -- Breaks english phrases down into their phonemes.
81
82         Input
83                 word                    --      An english word to be phonized
84                 max_phonemes    --      How many phonemes to calculate.  If 0, then it
85                                                         will phonize the entire phrase.
86                 phoned_word             --      The final phonized word.  (We'll allocate the
87                                                         memory.)
88         Output
89                 error   --      A simple error flag, returns TRUE or FALSE
90
91         NOTES:  ALL non-alpha characters are ignored, this includes whitespace,
92         although non-alpha characters will break up phonemes.
93 ****************************************************************************/
94
95
96 /**************************************************************************
97         my constants -- constants I like
98
99         Probably redundant.
100
101 ***************************************************************************/
102
103 #define META_ERROR                      FALSE
104 #define META_SUCCESS            TRUE
105 #define META_FAILURE            FALSE
106
107
108 /*      I add modifications to the traditional metaphone algorithm that you
109         might find in books.  Define this if you want metaphone to behave
110         traditionally */
111 #undef USE_TRADITIONAL_METAPHONE
112
113 /* Special encodings */
114 #define  SH             'X'
115 #define  TH             '0'
116
117 static char Lookahead(char *word, int how_far);
118 static int      _metaphone(char *word, int max_phonemes, char **phoned_word);
119
120 /* Metachar.h ... little bits about characters for metaphone */
121
122
123 /*-- Character encoding array & accessing macros --*/
124 /* Stolen directly out of the book... */
125 static const char _codes[26] = {
126         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
127 /*      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 */
128 };
129
130 static int
131 getcode(char c)
132 {
133         if (isalpha((unsigned char) c))
134         {
135                 c = toupper((unsigned char) c);
136                 /* Defend against non-ASCII letters */
137                 if (c >= 'A' && c <= 'Z')
138                         return _codes[c - 'A'];
139         }
140         return 0;
141 }
142
143 #define isvowel(c)      (getcode(c) & 1)        /* AEIOU */
144
145 /* These letters are passed through unchanged */
146 #define NOCHANGE(c) (getcode(c) & 2)    /* FJMNR */
147
148 /* These form diphthongs when preceding H */
149 #define AFFECTH(c)      (getcode(c) & 4)        /* CGPST */
150
151 /* These make C and G soft */
152 #define MAKESOFT(c) (getcode(c) & 8)    /* EIY */
153
154 /* These prevent GH from becoming F */
155 #define NOGHTOF(c)      (getcode(c) & 16)       /* BDH */
156
157 PG_FUNCTION_INFO_V1(levenshtein_with_costs);
158 Datum
159 levenshtein_with_costs(PG_FUNCTION_ARGS)
160 {
161         text       *src = PG_GETARG_TEXT_PP(0);
162         text       *dst = PG_GETARG_TEXT_PP(1);
163         int                     ins_c = PG_GETARG_INT32(2);
164         int                     del_c = PG_GETARG_INT32(3);
165         int                     sub_c = PG_GETARG_INT32(4);
166         const char *s_data;
167         const char *t_data;
168         int                     s_bytes,
169                                 t_bytes;
170
171         /* Extract a pointer to the actual character data */
172         s_data = VARDATA_ANY(src);
173         t_data = VARDATA_ANY(dst);
174         /* Determine length of each string in bytes and characters */
175         s_bytes = VARSIZE_ANY_EXHDR(src);
176         t_bytes = VARSIZE_ANY_EXHDR(dst);
177
178         PG_RETURN_INT32(varstr_levenshtein(s_data, s_bytes, t_data, t_bytes, ins_c,
179                                                                            del_c, sub_c));
180 }
181
182
183 PG_FUNCTION_INFO_V1(levenshtein);
184 Datum
185 levenshtein(PG_FUNCTION_ARGS)
186 {
187         text       *src = PG_GETARG_TEXT_PP(0);
188         text       *dst = PG_GETARG_TEXT_PP(1);
189         const char *s_data;
190         const char *t_data;
191         int                     s_bytes,
192                                 t_bytes;
193
194         /* Extract a pointer to the actual character data */
195         s_data = VARDATA_ANY(src);
196         t_data = VARDATA_ANY(dst);
197         /* Determine length of each string in bytes and characters */
198         s_bytes = VARSIZE_ANY_EXHDR(src);
199         t_bytes = VARSIZE_ANY_EXHDR(dst);
200
201         PG_RETURN_INT32(varstr_levenshtein(s_data, s_bytes, t_data, t_bytes, 1, 1,
202                                                                            1));
203 }
204
205
206 PG_FUNCTION_INFO_V1(levenshtein_less_equal_with_costs);
207 Datum
208 levenshtein_less_equal_with_costs(PG_FUNCTION_ARGS)
209 {
210         text       *src = PG_GETARG_TEXT_PP(0);
211         text       *dst = PG_GETARG_TEXT_PP(1);
212         int                     ins_c = PG_GETARG_INT32(2);
213         int                     del_c = PG_GETARG_INT32(3);
214         int                     sub_c = PG_GETARG_INT32(4);
215         int                     max_d = PG_GETARG_INT32(5);
216         const char *s_data;
217         const char *t_data;
218         int                     s_bytes,
219                                 t_bytes;
220
221         /* Extract a pointer to the actual character data */
222         s_data = VARDATA_ANY(src);
223         t_data = VARDATA_ANY(dst);
224         /* Determine length of each string in bytes and characters */
225         s_bytes = VARSIZE_ANY_EXHDR(src);
226         t_bytes = VARSIZE_ANY_EXHDR(dst);
227
228         PG_RETURN_INT32(varstr_levenshtein_less_equal(s_data, s_bytes, t_data,
229                                                                                                   t_bytes, ins_c, del_c,
230                                                                                                   sub_c, max_d));
231 }
232
233
234 PG_FUNCTION_INFO_V1(levenshtein_less_equal);
235 Datum
236 levenshtein_less_equal(PG_FUNCTION_ARGS)
237 {
238         text       *src = PG_GETARG_TEXT_PP(0);
239         text       *dst = PG_GETARG_TEXT_PP(1);
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 and characters */
250         s_bytes = VARSIZE_ANY_EXHDR(src);
251         t_bytes = VARSIZE_ANY_EXHDR(dst);
252
253         PG_RETURN_INT32(varstr_levenshtein_less_equal(s_data, s_bytes, t_data,
254                                                                                                   t_bytes, 1, 1, 1, max_d));
255 }
256
257
258 /*
259  * Calculates the metaphone of an input string.
260  * Returns number of characters requested
261  * (suggested value is 4)
262  */
263 PG_FUNCTION_INFO_V1(metaphone);
264 Datum
265 metaphone(PG_FUNCTION_ARGS)
266 {
267         char       *str_i = TextDatumGetCString(PG_GETARG_DATUM(0));
268         size_t          str_i_len = strlen(str_i);
269         int                     reqlen;
270         char       *metaph;
271         int                     retval;
272
273         /* return an empty string if we receive one */
274         if (!(str_i_len > 0))
275                 PG_RETURN_TEXT_P(cstring_to_text(""));
276
277         if (str_i_len > MAX_METAPHONE_STRLEN)
278                 ereport(ERROR,
279                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
280                                  errmsg("argument exceeds the maximum length of %d bytes",
281                                                 MAX_METAPHONE_STRLEN)));
282
283         if (!(str_i_len > 0))
284                 ereport(ERROR,
285                                 (errcode(ERRCODE_ZERO_LENGTH_CHARACTER_STRING),
286                                  errmsg("argument is empty string")));
287
288         reqlen = PG_GETARG_INT32(1);
289         if (reqlen > MAX_METAPHONE_STRLEN)
290                 ereport(ERROR,
291                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
292                                  errmsg("output exceeds the maximum length of %d bytes",
293                                                 MAX_METAPHONE_STRLEN)));
294
295         if (!(reqlen > 0))
296                 ereport(ERROR,
297                                 (errcode(ERRCODE_ZERO_LENGTH_CHARACTER_STRING),
298                                  errmsg("output cannot be empty string")));
299
300
301         retval = _metaphone(str_i, reqlen, &metaph);
302         if (retval == META_SUCCESS)
303                 PG_RETURN_TEXT_P(cstring_to_text(metaph));
304         else
305         {
306                 /* internal error */
307                 elog(ERROR, "metaphone: failure");
308                 /* keep the compiler quiet */
309                 PG_RETURN_NULL();
310         }
311 }
312
313
314 /*
315  * Original code by Michael G Schwern starts here.
316  * Code slightly modified for use as PostgreSQL
317  * function (palloc, etc).
318  */
319
320 /* I suppose I could have been using a character pointer instead of
321  * accessing the array directly... */
322
323 /* Look at the next letter in the word */
324 #define Next_Letter (toupper((unsigned char) word[w_idx+1]))
325 /* Look at the current letter in the word */
326 #define Curr_Letter (toupper((unsigned char) word[w_idx]))
327 /* Go N letters back. */
328 #define Look_Back_Letter(n) \
329         (w_idx >= (n) ? toupper((unsigned char) word[w_idx-(n)]) : '\0')
330 /* Previous letter.  I dunno, should this return null on failure? */
331 #define Prev_Letter (Look_Back_Letter(1))
332 /* Look two letters down.  It makes sure you don't walk off the string. */
333 #define After_Next_Letter \
334         (Next_Letter != '\0' ? toupper((unsigned char) word[w_idx+2]) : '\0')
335 #define Look_Ahead_Letter(n) toupper((unsigned char) Lookahead(word+w_idx, n))
336
337
338 /* Allows us to safely look ahead an arbitrary # of letters */
339 /* I probably could have just used strlen... */
340 static char
341 Lookahead(char *word, int how_far)
342 {
343         char            letter_ahead = '\0';    /* null by default */
344         int                     idx;
345
346         for (idx = 0; word[idx] != '\0' && idx < how_far; idx++);
347         /* Edge forward in the string... */
348
349         letter_ahead = word[idx];       /* idx will be either == to how_far or at the
350                                                                  * end of the string */
351         return letter_ahead;
352 }
353
354
355 /* phonize one letter */
356 #define Phonize(c)      do {(*phoned_word)[p_idx++] = c;} while (0)
357 /* Slap a null character on the end of the phoned word */
358 #define End_Phoned_Word do {(*phoned_word)[p_idx] = '\0';} while (0)
359 /* How long is the phoned word? */
360 #define Phone_Len       (p_idx)
361
362 /* Note is a letter is a 'break' in the word */
363 #define Isbreak(c)      (!isalpha((unsigned char) (c)))
364
365
366 static int
367 _metaphone(char *word,                  /* IN */
368                    int max_phonemes,
369                    char **phoned_word)  /* OUT */
370 {
371         int                     w_idx = 0;              /* point in the phonization we're at. */
372         int                     p_idx = 0;              /* end of the phoned phrase */
373
374         /*-- Parameter checks --*/
375
376         /*
377          * Shouldn't be necessary, but left these here anyway jec Aug 3, 2001
378          */
379
380         /* Negative phoneme length is meaningless */
381         if (!(max_phonemes > 0))
382                 /* internal error */
383                 elog(ERROR, "metaphone: Requested output length must be > 0");
384
385         /* Empty/null string is meaningless */
386         if ((word == NULL) || !(strlen(word) > 0))
387                 /* internal error */
388                 elog(ERROR, "metaphone: Input string length must be > 0");
389
390         /*-- Allocate memory for our phoned_phrase --*/
391         if (max_phonemes == 0)
392         {                                                       /* Assume largest possible */
393                 *phoned_word = palloc(sizeof(char) * strlen(word) +1);
394         }
395         else
396         {
397                 *phoned_word = palloc(sizeof(char) * max_phonemes + 1);
398         }
399
400         /*-- The first phoneme has to be processed specially. --*/
401         /* Find our first letter */
402         for (; !isalpha((unsigned char) (Curr_Letter)); w_idx++)
403         {
404                 /* On the off chance we were given nothing but crap... */
405                 if (Curr_Letter == '\0')
406                 {
407                         End_Phoned_Word;
408                         return META_SUCCESS;    /* For testing */
409                 }
410         }
411
412         switch (Curr_Letter)
413         {
414                         /* AE becomes E */
415                 case 'A':
416                         if (Next_Letter == 'E')
417                         {
418                                 Phonize('E');
419                                 w_idx += 2;
420                         }
421                         /* Remember, preserve vowels at the beginning */
422                         else
423                         {
424                                 Phonize('A');
425                                 w_idx++;
426                         }
427                         break;
428                         /* [GKP]N becomes N */
429                 case 'G':
430                 case 'K':
431                 case 'P':
432                         if (Next_Letter == 'N')
433                         {
434                                 Phonize('N');
435                                 w_idx += 2;
436                         }
437                         break;
438
439                         /*
440                          * WH becomes H, WR becomes R W if followed by a vowel
441                          */
442                 case 'W':
443                         if (Next_Letter == 'H' ||
444                                 Next_Letter == 'R')
445                         {
446                                 Phonize(Next_Letter);
447                                 w_idx += 2;
448                         }
449                         else if (isvowel(Next_Letter))
450                         {
451                                 Phonize('W');
452                                 w_idx += 2;
453                         }
454                         /* else ignore */
455                         break;
456                         /* X becomes S */
457                 case 'X':
458                         Phonize('S');
459                         w_idx++;
460                         break;
461                         /* Vowels are kept */
462
463                         /*
464                          * We did A already case 'A': case 'a':
465                          */
466                 case 'E':
467                 case 'I':
468                 case 'O':
469                 case 'U':
470                         Phonize(Curr_Letter);
471                         w_idx++;
472                         break;
473                 default:
474                         /* do nothing */
475                         break;
476         }
477
478
479
480         /* On to the metaphoning */
481         for (; Curr_Letter != '\0' &&
482                  (max_phonemes == 0 || Phone_Len < max_phonemes);
483                  w_idx++)
484         {
485                 /*
486                  * How many letters to skip because an earlier encoding handled
487                  * multiple letters
488                  */
489                 unsigned short int skip_letter = 0;
490
491
492                 /*
493                  * THOUGHT:  It would be nice if, rather than having things like...
494                  * well, SCI.  For SCI you encode the S, then have to remember to skip
495                  * the C.  So the phonome SCI invades both S and C.  It would be
496                  * better, IMHO, to skip the C from the S part of the encoding. Hell,
497                  * I'm trying it.
498                  */
499
500                 /* Ignore non-alphas */
501                 if (!isalpha((unsigned char) (Curr_Letter)))
502                         continue;
503
504                 /* Drop duplicates, except CC */
505                 if (Curr_Letter == Prev_Letter &&
506                         Curr_Letter != 'C')
507                         continue;
508
509                 switch (Curr_Letter)
510                 {
511                                 /* B -> B unless in MB */
512                         case 'B':
513                                 if (Prev_Letter != 'M')
514                                         Phonize('B');
515                                 break;
516
517                                 /*
518                                  * 'sh' if -CIA- or -CH, but not SCH, except SCHW. (SCHW is
519                                  * handled in S) S if -CI-, -CE- or -CY- dropped if -SCI-,
520                                  * SCE-, -SCY- (handed in S) else K
521                                  */
522                         case 'C':
523                                 if (MAKESOFT(Next_Letter))
524                                 {                               /* C[IEY] */
525                                         if (After_Next_Letter == 'A' &&
526                                                 Next_Letter == 'I')
527                                         {                       /* CIA */
528                                                 Phonize(SH);
529                                         }
530                                         /* SC[IEY] */
531                                         else if (Prev_Letter == 'S')
532                                         {
533                                                 /* Dropped */
534                                         }
535                                         else
536                                                 Phonize('S');
537                                 }
538                                 else if (Next_Letter == 'H')
539                                 {
540 #ifndef USE_TRADITIONAL_METAPHONE
541                                         if (After_Next_Letter == 'R' ||
542                                                 Prev_Letter == 'S')
543                                         {                       /* Christ, School */
544                                                 Phonize('K');
545                                         }
546                                         else
547                                                 Phonize(SH);
548 #else
549                                         Phonize(SH);
550 #endif
551                                         skip_letter++;
552                                 }
553                                 else
554                                         Phonize('K');
555                                 break;
556
557                                 /*
558                                  * J if in -DGE-, -DGI- or -DGY- else T
559                                  */
560                         case 'D':
561                                 if (Next_Letter == 'G' &&
562                                         MAKESOFT(After_Next_Letter))
563                                 {
564                                         Phonize('J');
565                                         skip_letter++;
566                                 }
567                                 else
568                                         Phonize('T');
569                                 break;
570
571                                 /*
572                                  * F if in -GH and not B--GH, D--GH, -H--GH, -H---GH else
573                                  * dropped if -GNED, -GN, else dropped if -DGE-, -DGI- or
574                                  * -DGY- (handled in D) else J if in -GE-, -GI, -GY and not GG
575                                  * else K
576                                  */
577                         case 'G':
578                                 if (Next_Letter == 'H')
579                                 {
580                                         if (!(NOGHTOF(Look_Back_Letter(3)) ||
581                                                   Look_Back_Letter(4) == 'H'))
582                                         {
583                                                 Phonize('F');
584                                                 skip_letter++;
585                                         }
586                                         else
587                                         {
588                                                 /* silent */
589                                         }
590                                 }
591                                 else if (Next_Letter == 'N')
592                                 {
593                                         if (Isbreak(After_Next_Letter) ||
594                                                 (After_Next_Letter == 'E' &&
595                                                  Look_Ahead_Letter(3) == 'D'))
596                                         {
597                                                 /* dropped */
598                                         }
599                                         else
600                                                 Phonize('K');
601                                 }
602                                 else if (MAKESOFT(Next_Letter) &&
603                                                  Prev_Letter != 'G')
604                                         Phonize('J');
605                                 else
606                                         Phonize('K');
607                                 break;
608                                 /* H if before a vowel and not after C,G,P,S,T */
609                         case 'H':
610                                 if (isvowel(Next_Letter) &&
611                                         !AFFECTH(Prev_Letter))
612                                         Phonize('H');
613                                 break;
614
615                                 /*
616                                  * dropped if after C else K
617                                  */
618                         case 'K':
619                                 if (Prev_Letter != 'C')
620                                         Phonize('K');
621                                 break;
622
623                                 /*
624                                  * F if before H else P
625                                  */
626                         case 'P':
627                                 if (Next_Letter == 'H')
628                                         Phonize('F');
629                                 else
630                                         Phonize('P');
631                                 break;
632
633                                 /*
634                                  * K
635                                  */
636                         case 'Q':
637                                 Phonize('K');
638                                 break;
639
640                                 /*
641                                  * 'sh' in -SH-, -SIO- or -SIA- or -SCHW- else S
642                                  */
643                         case 'S':
644                                 if (Next_Letter == 'I' &&
645                                         (After_Next_Letter == 'O' ||
646                                          After_Next_Letter == 'A'))
647                                         Phonize(SH);
648                                 else if (Next_Letter == 'H')
649                                 {
650                                         Phonize(SH);
651                                         skip_letter++;
652                                 }
653 #ifndef USE_TRADITIONAL_METAPHONE
654                                 else if (Next_Letter == 'C' &&
655                                                  Look_Ahead_Letter(2) == 'H' &&
656                                                  Look_Ahead_Letter(3) == 'W')
657                                 {
658                                         Phonize(SH);
659                                         skip_letter += 2;
660                                 }
661 #endif
662                                 else
663                                         Phonize('S');
664                                 break;
665
666                                 /*
667                                  * 'sh' in -TIA- or -TIO- else 'th' before H else T
668                                  */
669                         case 'T':
670                                 if (Next_Letter == 'I' &&
671                                         (After_Next_Letter == 'O' ||
672                                          After_Next_Letter == 'A'))
673                                         Phonize(SH);
674                                 else if (Next_Letter == 'H')
675                                 {
676                                         Phonize(TH);
677                                         skip_letter++;
678                                 }
679                                 else
680                                         Phonize('T');
681                                 break;
682                                 /* F */
683                         case 'V':
684                                 Phonize('F');
685                                 break;
686                                 /* W before a vowel, else dropped */
687                         case 'W':
688                                 if (isvowel(Next_Letter))
689                                         Phonize('W');
690                                 break;
691                                 /* KS */
692                         case 'X':
693                                 Phonize('K');
694                                 if (max_phonemes == 0 || Phone_Len < max_phonemes)
695                                         Phonize('S');
696                                 break;
697                                 /* Y if followed by a vowel */
698                         case 'Y':
699                                 if (isvowel(Next_Letter))
700                                         Phonize('Y');
701                                 break;
702                                 /* S */
703                         case 'Z':
704                                 Phonize('S');
705                                 break;
706                                 /* No transformation */
707                         case 'F':
708                         case 'J':
709                         case 'L':
710                         case 'M':
711                         case 'N':
712                         case 'R':
713                                 Phonize(Curr_Letter);
714                                 break;
715                         default:
716                                 /* nothing */
717                                 break;
718                 }                                               /* END SWITCH */
719
720                 w_idx += skip_letter;
721         }                                                       /* END FOR */
722
723         End_Phoned_Word;
724
725         return (META_SUCCESS);
726 }       /* END metaphone */
727
728
729 /*
730  * SQL function: soundex(text) returns text
731  */
732 PG_FUNCTION_INFO_V1(soundex);
733
734 Datum
735 soundex(PG_FUNCTION_ARGS)
736 {
737         char            outstr[SOUNDEX_LEN + 1];
738         char       *arg;
739
740         arg = text_to_cstring(PG_GETARG_TEXT_P(0));
741
742         _soundex(arg, outstr);
743
744         PG_RETURN_TEXT_P(cstring_to_text(outstr));
745 }
746
747 static void
748 _soundex(const char *instr, char *outstr)
749 {
750         int                     count;
751
752         AssertArg(instr);
753         AssertArg(outstr);
754
755         outstr[SOUNDEX_LEN] = '\0';
756
757         /* Skip leading non-alphabetic characters */
758         while (!isalpha((unsigned char) instr[0]) && instr[0])
759                 ++instr;
760
761         /* No string left */
762         if (!instr[0])
763         {
764                 outstr[0] = (char) 0;
765                 return;
766         }
767
768         /* Take the first letter as is */
769         *outstr++ = (char) toupper((unsigned char) *instr++);
770
771         count = 1;
772         while (*instr && count < SOUNDEX_LEN)
773         {
774                 if (isalpha((unsigned char) *instr) &&
775                         soundex_code(*instr) != soundex_code(*(instr - 1)))
776                 {
777                         *outstr = soundex_code(instr[0]);
778                         if (*outstr != '0')
779                         {
780                                 ++outstr;
781                                 ++count;
782                         }
783                 }
784                 ++instr;
785         }
786
787         /* Fill with 0's */
788         while (count < SOUNDEX_LEN)
789         {
790                 *outstr = '0';
791                 ++outstr;
792                 ++count;
793         }
794 }
795
796 PG_FUNCTION_INFO_V1(difference);
797
798 Datum
799 difference(PG_FUNCTION_ARGS)
800 {
801         char            sndx1[SOUNDEX_LEN + 1],
802                                 sndx2[SOUNDEX_LEN + 1];
803         int                     i,
804                                 result;
805
806         _soundex(text_to_cstring(PG_GETARG_TEXT_P(0)), sndx1);
807         _soundex(text_to_cstring(PG_GETARG_TEXT_P(1)), sndx2);
808
809         result = 0;
810         for (i = 0; i < SOUNDEX_LEN; i++)
811         {
812                 if (sndx1[i] == sndx2[i])
813                         result++;
814         }
815
816         PG_RETURN_INT32(result);
817 }