~vcs-imports/mammoth-replicator/trunk

« back to all changes in this revision

Viewing changes to contrib/fuzzystrmatch/fuzzystrmatch.c

  • Committer: alvherre
  • Date: 2005-12-16 21:24:52 UTC
  • Revision ID: svn-v4:db760fc0-0f08-0410-9d63-cc6633f64896:trunk:1
Initial import of the REL8_0_3 sources from the Pgsql CVS repository.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * fuzzystrmatch.c
 
3
 *
 
4
 * Functions for "fuzzy" comparison of strings
 
5
 *
 
6
 * Joe Conway <mail@joeconway.com>
 
7
 *
 
8
 * Copyright (c) 2001-2005, PostgreSQL Global Development Group
 
9
 * ALL RIGHTS RESERVED;
 
10
 *
 
11
 * levenshtein()
 
12
 * -------------
 
13
 * Written based on a description of the algorithm by Michael Gilleland
 
14
 * found at http://www.merriampark.com/ld.htm
 
15
 * Also looked at levenshtein.c in the PHP 4.0.6 distribution for
 
16
 * inspiration.
 
17
 *
 
18
 * metaphone()
 
19
 * -----------
 
20
 * Modified for PostgreSQL by Joe Conway.
 
21
 * Based on CPAN's "Text-Metaphone-1.96" by Michael G Schwern <schwern@pobox.com>
 
22
 * Code slightly modified for use as PostgreSQL function (palloc, elog, etc).
 
23
 * Metaphone was originally created by Lawrence Philips and presented in article
 
24
 * in "Computer Language" December 1990 issue.
 
25
 *
 
26
 * Permission to use, copy, modify, and distribute this software and its
 
27
 * documentation for any purpose, without fee, and without a written agreement
 
28
 * is hereby granted, provided that the above copyright notice and this
 
29
 * paragraph and the following two paragraphs appear in all copies.
 
30
 *
 
31
 * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
 
32
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
 
33
 * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
 
34
 * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
 
35
 * POSSIBILITY OF SUCH DAMAGE.
 
36
 *
 
37
 * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
 
38
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 
39
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 
40
 * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
 
41
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 
42
 *
 
43
 */
 
44
 
 
45
#include "fuzzystrmatch.h"
 
46
 
 
47
/*
 
48
 * Calculates Levenshtein Distance between two strings.
 
49
 * Uses simplest and fastest cost model only, i.e. assumes a cost of 1 for
 
50
 * each deletion, substitution, or insertion.
 
51
 */
 
52
PG_FUNCTION_INFO_V1(levenshtein);
 
53
Datum
 
54
levenshtein(PG_FUNCTION_ARGS)
 
55
{
 
56
        char       *str_s;
 
57
        char       *str_s0;
 
58
        char       *str_t;
 
59
        int                     cols = 0;
 
60
        int                     rows = 0;
 
61
        int                *u_cells;
 
62
        int                *l_cells;
 
63
        int                *tmp;
 
64
        int                     i;
 
65
        int                     j;
 
66
 
 
67
        /*
 
68
         * Fetch the arguments. str_s is referred to as the "source" cols =
 
69
         * length of source + 1 to allow for the initialization column str_t
 
70
         * is referred to as the "target", rows = length of target + 1 rows =
 
71
         * length of target + 1 to allow for the initialization row
 
72
         */
 
73
        str_s = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(PG_GETARG_TEXT_P(0))));
 
74
        str_t = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(PG_GETARG_TEXT_P(1))));
 
75
 
 
76
        cols = strlen(str_s) + 1;
 
77
        rows = strlen(str_t) + 1;
 
78
 
 
79
        /*
 
80
         * Restrict the length of the strings being compared to something
 
81
         * reasonable because we will have to perform rows * cols
 
82
         * calculations. If longer strings need to be compared, increase
 
83
         * MAX_LEVENSHTEIN_STRLEN to suit (but within your tolerance for speed
 
84
         * and memory usage).
 
85
         */
 
86
        if ((cols > MAX_LEVENSHTEIN_STRLEN + 1) || (rows > MAX_LEVENSHTEIN_STRLEN + 1))
 
87
                ereport(ERROR,
 
88
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
89
                                 errmsg("argument exceeds max length: %d",
 
90
                                                MAX_LEVENSHTEIN_STRLEN)));
 
91
 
 
92
        /*
 
93
         * If either rows or cols is 0, the answer is the other value. This
 
94
         * makes sense since it would take that many insertions the build a
 
95
         * matching string
 
96
         */
 
97
 
 
98
        if (cols == 0)
 
99
                PG_RETURN_INT32(rows);
 
100
 
 
101
        if (rows == 0)
 
102
                PG_RETURN_INT32(cols);
 
103
 
 
104
        /*
 
105
         * Allocate two vectors of integers. One will be used for the "upper"
 
106
         * row, the other for the "lower" row. Initialize the "upper" row to
 
107
         * 0..cols
 
108
         */
 
109
        u_cells = palloc(sizeof(int) * cols);
 
110
        for (i = 0; i < cols; i++)
 
111
                u_cells[i] = i;
 
112
 
 
113
        l_cells = palloc(sizeof(int) * cols);
 
114
 
 
115
        /*
 
116
         * Use str_s0 to "rewind" the pointer to str_s in the nested for loop
 
117
         * below
 
118
         */
 
119
        str_s0 = str_s;
 
120
 
 
121
        /*
 
122
         * Loop throught the rows, starting at row 1. Row 0 is used for the
 
123
         * initial "upper" row.
 
124
         */
 
125
        for (j = 1; j < rows; j++)
 
126
        {
 
127
                /*
 
128
                 * We'll always start with col 1, and initialize lower row col 0
 
129
                 * to j
 
130
                 */
 
131
                l_cells[0] = j;
 
132
 
 
133
                for (i = 1; i < cols; i++)
 
134
                {
 
135
                        int                     c = 0;
 
136
                        int                     c1 = 0;
 
137
                        int                     c2 = 0;
 
138
                        int                     c3 = 0;
 
139
 
 
140
                        /*
 
141
                         * The "cost" value is 0 if the character at the current col
 
142
                         * position in the source string, matches the character at the
 
143
                         * current row position in the target string; cost is 1
 
144
                         * otherwise.
 
145
                         */
 
146
                        c = ((CHAREQ(str_s, str_t)) ? 0 : 1);
 
147
 
 
148
                        /*
 
149
                         * c1 is upper right cell plus 1
 
150
                         */
 
151
                        c1 = u_cells[i] + 1;
 
152
 
 
153
                        /*
 
154
                         * c2 is lower left cell plus 1
 
155
                         */
 
156
                        c2 = l_cells[i - 1] + 1;
 
157
 
 
158
                        /*
 
159
                         * c3 is cell diagonally above to the left plus "cost"
 
160
                         */
 
161
                        c3 = u_cells[i - 1] + c;
 
162
 
 
163
                        /*
 
164
                         * The lower right cell is set to the minimum of c1, c2, c3
 
165
                         */
 
166
                        l_cells[i] = (c1 < c2 ? c1 : c2) < c3 ? (c1 < c2 ? c1 : c2) : c3;
 
167
 
 
168
                        /*
 
169
                         * Increment the pointer to str_s
 
170
                         */
 
171
                        NextChar(str_s);
 
172
                }
 
173
 
 
174
                /*
 
175
                 * Lower row now becomes the upper row, and the upper row gets
 
176
                 * reused as the new lower row.
 
177
                 */
 
178
                tmp = u_cells;
 
179
                u_cells = l_cells;
 
180
                l_cells = tmp;
 
181
 
 
182
                /*
 
183
                 * Increment the pointer to str_t
 
184
                 */
 
185
                NextChar(str_t);
 
186
 
 
187
                /*
 
188
                 * Rewind the pointer to str_s
 
189
                 */
 
190
                str_s = str_s0;
 
191
        }
 
192
 
 
193
        /*
 
194
         * Because the final value (at position row, col) was swapped from the
 
195
         * lower row to the upper row, that's where we'll find it.
 
196
         */
 
197
        PG_RETURN_INT32(u_cells[cols - 1]);
 
198
}
 
199
 
 
200
/*
 
201
 * Calculates the metaphone of an input string.
 
202
 * Returns number of characters requested
 
203
 * (suggested value is 4)
 
204
 */
 
205
#define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))
 
206
 
 
207
PG_FUNCTION_INFO_V1(metaphone);
 
208
Datum
 
209
metaphone(PG_FUNCTION_ARGS)
 
210
{
 
211
        int                     reqlen;
 
212
        char       *str_i;
 
213
        size_t          str_i_len;
 
214
        char       *metaph;
 
215
        text       *result_text;
 
216
        int                     retval;
 
217
 
 
218
        str_i = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(PG_GETARG_TEXT_P(0))));
 
219
        str_i_len = strlen(str_i);
 
220
 
 
221
        /* return an empty string if we receive one */
 
222
        if (!(str_i_len > 0))
 
223
                PG_RETURN_TEXT_P(GET_TEXT(""));
 
224
 
 
225
        if (str_i_len > MAX_METAPHONE_STRLEN)
 
226
                ereport(ERROR,
 
227
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
228
                                 errmsg("argument exceeds max length: %d",
 
229
                                                MAX_METAPHONE_STRLEN)));
 
230
 
 
231
        if (!(str_i_len > 0))
 
232
                ereport(ERROR,
 
233
                                (errcode(ERRCODE_ZERO_LENGTH_CHARACTER_STRING),
 
234
                                 errmsg("argument is empty string")));
 
235
 
 
236
        reqlen = PG_GETARG_INT32(1);
 
237
        if (reqlen > MAX_METAPHONE_STRLEN)
 
238
                ereport(ERROR,
 
239
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
240
                                 errmsg("output length exceeds max length: %d",
 
241
                                                MAX_METAPHONE_STRLEN)));
 
242
 
 
243
        if (!(reqlen > 0))
 
244
                ereport(ERROR,
 
245
                                (errcode(ERRCODE_ZERO_LENGTH_CHARACTER_STRING),
 
246
                                 errmsg("output cannot be empty string")));
 
247
 
 
248
 
 
249
        retval = _metaphone(str_i, reqlen, &metaph);
 
250
        if (retval == META_SUCCESS)
 
251
        {
 
252
                result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(metaph)));
 
253
                PG_RETURN_TEXT_P(result_text);
 
254
        }
 
255
        else
 
256
        {
 
257
                /* internal error */
 
258
                elog(ERROR, "metaphone: failure");
 
259
 
 
260
                /*
 
261
                 * Keep the compiler quiet
 
262
                 */
 
263
                PG_RETURN_NULL();
 
264
        }
 
265
}
 
266
 
 
267
 
 
268
/*
 
269
 * Original code by Michael G Schwern starts here.
 
270
 * Code slightly modified for use as PostgreSQL
 
271
 * function (palloc, etc). Original includes
 
272
 * are rolled into fuzzystrmatch.h
 
273
 *------------------------------------------------------------------*/
 
274
 
 
275
/* I suppose I could have been using a character pointer instead of
 
276
 * accessing the array directly... */
 
277
 
 
278
/* Look at the next letter in the word */
 
279
#define Next_Letter (toupper((unsigned char) word[w_idx+1]))
 
280
/* Look at the current letter in the word */
 
281
#define Curr_Letter (toupper((unsigned char) word[w_idx]))
 
282
/* Go N letters back. */
 
283
#define Look_Back_Letter(n) \
 
284
        (w_idx >= (n) ? toupper((unsigned char) word[w_idx-(n)]) : '\0')
 
285
/* Previous letter.  I dunno, should this return null on failure? */
 
286
#define Prev_Letter (Look_Back_Letter(1))
 
287
/* Look two letters down.  It makes sure you don't walk off the string. */
 
288
#define After_Next_Letter \
 
289
        (Next_Letter != '\0' ? toupper((unsigned char) word[w_idx+2]) : '\0')
 
290
#define Look_Ahead_Letter(n) toupper((unsigned char) Lookahead(word+w_idx, n))
 
291
 
 
292
 
 
293
/* Allows us to safely look ahead an arbitrary # of letters */
 
294
/* I probably could have just used strlen... */
 
295
char
 
296
Lookahead(char *word, int how_far)
 
297
{
 
298
        char            letter_ahead = '\0';    /* null by default */
 
299
        int                     idx;
 
300
 
 
301
        for (idx = 0; word[idx] != '\0' && idx < how_far; idx++);
 
302
        /* Edge forward in the string... */
 
303
 
 
304
        letter_ahead = word[idx];       /* idx will be either == to how_far or at
 
305
                                                                 * the end of the string */
 
306
        return letter_ahead;
 
307
}
 
308
 
 
309
 
 
310
/* phonize one letter */
 
311
#define Phonize(c)      do {(*phoned_word)[p_idx++] = c;} while (0)
 
312
/* Slap a null character on the end of the phoned word */
 
313
#define End_Phoned_Word do {(*phoned_word)[p_idx] = '\0';} while (0)
 
314
/* How long is the phoned word? */
 
315
#define Phone_Len       (p_idx)
 
316
 
 
317
/* Note is a letter is a 'break' in the word */
 
318
#define Isbreak(c)      (!isalpha((unsigned char) (c)))
 
319
 
 
320
 
 
321
int
 
322
_metaphone(
 
323
 /* IN */
 
324
                   char *word,
 
325
                   int max_phonemes,
 
326
 /* OUT */
 
327
                   char **phoned_word
 
328
)
 
329
{
 
330
        int                     w_idx = 0;              /* point in the phonization we're at. */
 
331
        int                     p_idx = 0;              /* end of the phoned phrase */
 
332
 
 
333
        /*-- Parameter checks --*/
 
334
 
 
335
        /*
 
336
         * Shouldn't be necessary, but left these here anyway jec Aug 3, 2001
 
337
         */
 
338
 
 
339
        /* Negative phoneme length is meaningless */
 
340
        if (!(max_phonemes > 0))
 
341
                /* internal error */
 
342
                elog(ERROR, "metaphone: Requested output length must be > 0");
 
343
 
 
344
        /* Empty/null string is meaningless */
 
345
        if ((word == NULL) || !(strlen(word) > 0))
 
346
                /* internal error */
 
347
                elog(ERROR, "metaphone: Input string length must be > 0");
 
348
 
 
349
        /*-- Allocate memory for our phoned_phrase --*/
 
350
        if (max_phonemes == 0)
 
351
        {                                                       /* Assume largest possible */
 
352
                *phoned_word = palloc(sizeof(char) * strlen(word) +1);
 
353
                if (!*phoned_word)
 
354
                        return META_ERROR;
 
355
        }
 
356
        else
 
357
        {
 
358
                *phoned_word = palloc(sizeof(char) * max_phonemes + 1);
 
359
                if (!*phoned_word)
 
360
                        return META_ERROR;
 
361
        }
 
362
 
 
363
        /*-- The first phoneme has to be processed specially. --*/
 
364
        /* Find our first letter */
 
365
        for (; !isalpha((unsigned char) (Curr_Letter)); w_idx++)
 
366
        {
 
367
                /* On the off chance we were given nothing but crap... */
 
368
                if (Curr_Letter == '\0')
 
369
                {
 
370
                        End_Phoned_Word;
 
371
                        return META_SUCCESS;    /* For testing */
 
372
                }
 
373
        }
 
374
 
 
375
        switch (Curr_Letter)
 
376
        {
 
377
                        /* AE becomes E */
 
378
                case 'A':
 
379
                        if (Next_Letter == 'E')
 
380
                        {
 
381
                                Phonize('E');
 
382
                                w_idx += 2;
 
383
                        }
 
384
                        /* Remember, preserve vowels at the beginning */
 
385
                        else
 
386
                        {
 
387
                                Phonize('A');
 
388
                                w_idx++;
 
389
                        }
 
390
                        break;
 
391
                        /* [GKP]N becomes N */
 
392
                case 'G':
 
393
                case 'K':
 
394
                case 'P':
 
395
                        if (Next_Letter == 'N')
 
396
                        {
 
397
                                Phonize('N');
 
398
                                w_idx += 2;
 
399
                        }
 
400
                        break;
 
401
 
 
402
                        /*
 
403
                         * WH becomes H, WR becomes R W if followed by a vowel
 
404
                         */
 
405
                case 'W':
 
406
                        if (Next_Letter == 'H' ||
 
407
                                Next_Letter == 'R')
 
408
                        {
 
409
                                Phonize(Next_Letter);
 
410
                                w_idx += 2;
 
411
                        }
 
412
                        else if (isvowel(Next_Letter))
 
413
                        {
 
414
                                Phonize('W');
 
415
                                w_idx += 2;
 
416
                        }
 
417
                        /* else ignore */
 
418
                        break;
 
419
                        /* X becomes S */
 
420
                case 'X':
 
421
                        Phonize('S');
 
422
                        w_idx++;
 
423
                        break;
 
424
                        /* Vowels are kept */
 
425
 
 
426
                        /*
 
427
                         * We did A already case 'A': case 'a':
 
428
                         */
 
429
                case 'E':
 
430
                case 'I':
 
431
                case 'O':
 
432
                case 'U':
 
433
                        Phonize(Curr_Letter);
 
434
                        w_idx++;
 
435
                        break;
 
436
                default:
 
437
                        /* do nothing */
 
438
                        break;
 
439
        }
 
440
 
 
441
 
 
442
 
 
443
        /* On to the metaphoning */
 
444
        for (; Curr_Letter != '\0' &&
 
445
                 (max_phonemes == 0 || Phone_Len < max_phonemes);
 
446
                 w_idx++)
 
447
        {
 
448
                /*
 
449
                 * How many letters to skip because an earlier encoding handled
 
450
                 * multiple letters
 
451
                 */
 
452
                unsigned short int skip_letter = 0;
 
453
 
 
454
 
 
455
                /*
 
456
                 * THOUGHT:  It would be nice if, rather than having things
 
457
                 * like... well, SCI.  For SCI you encode the S, then have to
 
458
                 * remember to skip the C.      So the phonome SCI invades both S and
 
459
                 * C.  It would be better, IMHO, to skip the C from the S part of
 
460
                 * the encoding. Hell, I'm trying it.
 
461
                 */
 
462
 
 
463
                /* Ignore non-alphas */
 
464
                if (!isalpha((unsigned char) (Curr_Letter)))
 
465
                        continue;
 
466
 
 
467
                /* Drop duplicates, except CC */
 
468
                if (Curr_Letter == Prev_Letter &&
 
469
                        Curr_Letter != 'C')
 
470
                        continue;
 
471
 
 
472
                switch (Curr_Letter)
 
473
                {
 
474
                                /* B -> B unless in MB */
 
475
                        case 'B':
 
476
                                if (Prev_Letter != 'M')
 
477
                                        Phonize('B');
 
478
                                break;
 
479
 
 
480
                                /*
 
481
                                 * 'sh' if -CIA- or -CH, but not SCH, except SCHW. (SCHW
 
482
                                 * is handled in S) S if -CI-, -CE- or -CY- dropped if
 
483
                                 * -SCI-, SCE-, -SCY- (handed in S) else K
 
484
                                 */
 
485
                        case 'C':
 
486
                                if (MAKESOFT(Next_Letter))
 
487
                                {                               /* C[IEY] */
 
488
                                        if (After_Next_Letter == 'A' &&
 
489
                                                Next_Letter == 'I')
 
490
                                        {                       /* CIA */
 
491
                                                Phonize(SH);
 
492
                                        }
 
493
                                        /* SC[IEY] */
 
494
                                        else if (Prev_Letter == 'S')
 
495
                                        {
 
496
                                                /* Dropped */
 
497
                                        }
 
498
                                        else
 
499
                                                Phonize('S');
 
500
                                }
 
501
                                else if (Next_Letter == 'H')
 
502
                                {
 
503
#ifndef USE_TRADITIONAL_METAPHONE
 
504
                                        if (After_Next_Letter == 'R' ||
 
505
                                                Prev_Letter == 'S')
 
506
                                        {                       /* Christ, School */
 
507
                                                Phonize('K');
 
508
                                        }
 
509
                                        else
 
510
                                                Phonize(SH);
 
511
#else
 
512
                                        Phonize(SH);
 
513
#endif
 
514
                                        skip_letter++;
 
515
                                }
 
516
                                else
 
517
                                        Phonize('K');
 
518
                                break;
 
519
 
 
520
                                /*
 
521
                                 * J if in -DGE-, -DGI- or -DGY- else T
 
522
                                 */
 
523
                        case 'D':
 
524
                                if (Next_Letter == 'G' &&
 
525
                                        MAKESOFT(After_Next_Letter))
 
526
                                {
 
527
                                        Phonize('J');
 
528
                                        skip_letter++;
 
529
                                }
 
530
                                else
 
531
                                        Phonize('T');
 
532
                                break;
 
533
 
 
534
                                /*
 
535
                                 * F if in -GH and not B--GH, D--GH, -H--GH, -H---GH else
 
536
                                 * dropped if -GNED, -GN, else dropped if -DGE-, -DGI- or
 
537
                                 * -DGY- (handled in D) else J if in -GE-, -GI, -GY and
 
538
                                 * not GG else K
 
539
                                 */
 
540
                        case 'G':
 
541
                                if (Next_Letter == 'H')
 
542
                                {
 
543
                                        if (!(NOGHTOF(Look_Back_Letter(3)) ||
 
544
                                                  Look_Back_Letter(4) == 'H'))
 
545
                                        {
 
546
                                                Phonize('F');
 
547
                                                skip_letter++;
 
548
                                        }
 
549
                                        else
 
550
                                        {
 
551
                                                /* silent */
 
552
                                        }
 
553
                                }
 
554
                                else if (Next_Letter == 'N')
 
555
                                {
 
556
                                        if (Isbreak(After_Next_Letter) ||
 
557
                                                (After_Next_Letter == 'E' &&
 
558
                                                 Look_Ahead_Letter(3) == 'D'))
 
559
                                        {
 
560
                                                /* dropped */
 
561
                                        }
 
562
                                        else
 
563
                                                Phonize('K');
 
564
                                }
 
565
                                else if (MAKESOFT(Next_Letter) &&
 
566
                                                 Prev_Letter != 'G')
 
567
                                        Phonize('J');
 
568
                                else
 
569
                                        Phonize('K');
 
570
                                break;
 
571
                                /* H if before a vowel and not after C,G,P,S,T */
 
572
                        case 'H':
 
573
                                if (isvowel(Next_Letter) &&
 
574
                                        !AFFECTH(Prev_Letter))
 
575
                                        Phonize('H');
 
576
                                break;
 
577
 
 
578
                                /*
 
579
                                 * dropped if after C else K
 
580
                                 */
 
581
                        case 'K':
 
582
                                if (Prev_Letter != 'C')
 
583
                                        Phonize('K');
 
584
                                break;
 
585
 
 
586
                                /*
 
587
                                 * F if before H else P
 
588
                                 */
 
589
                        case 'P':
 
590
                                if (Next_Letter == 'H')
 
591
                                        Phonize('F');
 
592
                                else
 
593
                                        Phonize('P');
 
594
                                break;
 
595
 
 
596
                                /*
 
597
                                 * K
 
598
                                 */
 
599
                        case 'Q':
 
600
                                Phonize('K');
 
601
                                break;
 
602
 
 
603
                                /*
 
604
                                 * 'sh' in -SH-, -SIO- or -SIA- or -SCHW- else S
 
605
                                 */
 
606
                        case 'S':
 
607
                                if (Next_Letter == 'I' &&
 
608
                                        (After_Next_Letter == 'O' ||
 
609
                                         After_Next_Letter == 'A'))
 
610
                                        Phonize(SH);
 
611
                                else if (Next_Letter == 'H')
 
612
                                {
 
613
                                        Phonize(SH);
 
614
                                        skip_letter++;
 
615
                                }
 
616
#ifndef USE_TRADITIONAL_METAPHONE
 
617
                                else if (Next_Letter == 'C' &&
 
618
                                                 Look_Ahead_Letter(2) == 'H' &&
 
619
                                                 Look_Ahead_Letter(3) == 'W')
 
620
                                {
 
621
                                        Phonize(SH);
 
622
                                        skip_letter += 2;
 
623
                                }
 
624
#endif
 
625
                                else
 
626
                                        Phonize('S');
 
627
                                break;
 
628
 
 
629
                                /*
 
630
                                 * 'sh' in -TIA- or -TIO- else 'th' before H else T
 
631
                                 */
 
632
                        case 'T':
 
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(TH);
 
640
                                        skip_letter++;
 
641
                                }
 
642
                                else
 
643
                                        Phonize('T');
 
644
                                break;
 
645
                                /* F */
 
646
                        case 'V':
 
647
                                Phonize('F');
 
648
                                break;
 
649
                                /* W before a vowel, else dropped */
 
650
                        case 'W':
 
651
                                if (isvowel(Next_Letter))
 
652
                                        Phonize('W');
 
653
                                break;
 
654
                                /* KS */
 
655
                        case 'X':
 
656
                                Phonize('K');
 
657
                                if (max_phonemes == 0 || Phone_Len < max_phonemes)
 
658
                                        Phonize('S');
 
659
                                break;
 
660
                                /* Y if followed by a vowel */
 
661
                        case 'Y':
 
662
                                if (isvowel(Next_Letter))
 
663
                                        Phonize('Y');
 
664
                                break;
 
665
                                /* S */
 
666
                        case 'Z':
 
667
                                Phonize('S');
 
668
                                break;
 
669
                                /* No transformation */
 
670
                        case 'F':
 
671
                        case 'J':
 
672
                        case 'L':
 
673
                        case 'M':
 
674
                        case 'N':
 
675
                        case 'R':
 
676
                                Phonize(Curr_Letter);
 
677
                                break;
 
678
                        default:
 
679
                                /* nothing */
 
680
                                break;
 
681
                }                                               /* END SWITCH */
 
682
 
 
683
                w_idx += skip_letter;
 
684
        }                                                       /* END FOR */
 
685
 
 
686
        End_Phoned_Word;
 
687
 
 
688
        return (META_SUCCESS);
 
689
}       /* END metaphone */
 
690
 
 
691
 
 
692
/*
 
693
 * SQL function: soundex(text) returns text
 
694
 */
 
695
PG_FUNCTION_INFO_V1(soundex);
 
696
 
 
697
Datum
 
698
soundex(PG_FUNCTION_ARGS)
 
699
{
 
700
        char            outstr[SOUNDEX_LEN + 1];
 
701
        char       *arg;
 
702
 
 
703
        arg = _textout(PG_GETARG_TEXT_P(0));
 
704
 
 
705
        _soundex(arg, outstr);
 
706
 
 
707
        PG_RETURN_TEXT_P(_textin(outstr));
 
708
}
 
709
 
 
710
static void
 
711
_soundex(const char *instr, char *outstr)
 
712
{
 
713
        int                     count;
 
714
 
 
715
        AssertArg(instr);
 
716
        AssertArg(outstr);
 
717
 
 
718
        outstr[SOUNDEX_LEN] = '\0';
 
719
 
 
720
        /* Skip leading non-alphabetic characters */
 
721
        while (!isalpha((unsigned char) instr[0]) && instr[0])
 
722
                ++instr;
 
723
 
 
724
        /* No string left */
 
725
        if (!instr[0])
 
726
        {
 
727
                outstr[0] = (char) 0;
 
728
                return;
 
729
        }
 
730
 
 
731
        /* Take the first letter as is */
 
732
        *outstr++ = (char) toupper((unsigned char) *instr++);
 
733
 
 
734
        count = 1;
 
735
        while (*instr && count < SOUNDEX_LEN)
 
736
        {
 
737
                if (isalpha((unsigned char) *instr) &&
 
738
                        soundex_code(*instr) != soundex_code(*(instr - 1)))
 
739
                {
 
740
                        *outstr = soundex_code(instr[0]);
 
741
                        if (*outstr != '0')
 
742
                        {
 
743
                                ++outstr;
 
744
                                ++count;
 
745
                        }
 
746
                }
 
747
                ++instr;
 
748
        }
 
749
 
 
750
        /* Fill with 0's */
 
751
        while (count < SOUNDEX_LEN)
 
752
        {
 
753
                *outstr = '0';
 
754
                ++outstr;
 
755
                ++count;
 
756
        }
 
757
}