generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathcollation.c
More file actions
2353 lines (2024 loc) · 65.6 KB
/
collation.c
File metadata and controls
2353 lines (2024 loc) · 65.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "postgres.h"
#include "collation.h"
#include "fmgr.h"
#include "guc.h"
#include "utils/hsearch.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/memutils.h"
#include "utils/builtins.h"
#include "catalog/pg_type.h"
#include "catalog/pg_collation.h"
#include "catalog/namespace.h"
#include "tsearch/ts_locale.h"
#include "optimizer/clauses.h"
#include "optimizer/optimizer.h"
#include "parser/parser.h"
#include "parser/parse_coerce.h"
#include "parser/parse_type.h"
#include "parser/parse_oper.h"
#include "nodes/makefuncs.h"
#include "nodes/nodes.h"
#include "rewrite/rewriteManip.h"
#ifdef USE_ICU
#include <unicode/utrans.h>
#include "utils/removeaccent.map"
#include <unicode/ucol.h>
#include <unicode/usearch.h>
#endif
#include "miscadmin.h"
#include "pltsql.h"
#include "src/collation.h"
#include "catalog.h"
#define NOT_FOUND -1
#define SORT_KEY_STR "\357\277\277\0"
/*
* Rule applied to transliterate Latin and general category Nd character
* then convert the Latin (source) char to ASCII (destination) representation
*/
#define TRANSFORMATION_RULE "[[:Latin:][:Nd:]]; Latin-ASCII"
/*
* The maximum number of bytes per character is 4 according
* to RFC3629 which limited the character table to U+10FFFF
* Ref: https://www.rfc-editor.org/rfc/rfc3629#section-3
*/
#define MAX_BYTES_PER_CHAR 4
#define MAX_INPUT_LENGTH_TO_REMOVE_ACCENTS 250 * 1024 * 1024
/*
* Check if Uchar is lead surrogate pair, If Uchar is in
* the range D800 - DBFF then it is a lead surrogate pair
*/
#define UCHAR_IS_SURROGATE(c) ((c & 0xF800) == 0xD800)
/* Find length of given Uchar */
#define UCHAR_LENGTH(c) (UCHAR_IS_SURROGATE(c) ? 2 : 1)
Oid database_or_server_collation_oid = InvalidOid;
collation_callbacks *collation_callbacks_ptr = NULL;
extern bool babelfish_dump_restore;
static Oid remove_accents_internal_oid;
static UTransliterator *cached_transliterator = NULL;
static Node *pgtsql_expression_tree_mutator(Node *node, void *context);
static void init_and_check_collation_callbacks(void);
static int patindex_ai_match_text(pg_locale_t mylocale, char *input_str, char *pattern, Oid cid, bool is_cs_ai);
extern int pattern_fixed_prefix_wrapper(Const *patt,
int ptype,
Oid collation,
Const **prefix,
Selectivity *rest_selec);
static Node *transform_likenode_for_AI(OpExpr *op);
static Node *convert_node_to_funcexpr_for_like(Node *node, Oid inputcollid);
/* pattern prefix status for pattern_fixed_prefix_wrapper
* Pattern_Prefix_None: no prefix found, this means the first character is a wildcard character
* Pattern_Prefix_Exact: the pattern doesn't include any wildcard character
* Pattern_Prefix_Partial: the pattern has a constant prefix
*/
typedef enum
{
Pattern_Prefix_None, Pattern_Prefix_Partial, Pattern_Prefix_Exact
} Pattern_Prefix_Status;
PG_FUNCTION_INFO_V1(init_collid_trans_tab);
PG_FUNCTION_INFO_V1(init_like_ilike_table);
PG_FUNCTION_INFO_V1(get_server_collation_oid);
PG_FUNCTION_INFO_V1(is_collated_ci_as_internal);
PG_FUNCTION_INFO_V1(is_collated_ai_internal);
/* this function is no longer needed and is only a placeholder for upgrade script */
PG_FUNCTION_INFO_V1(init_server_collation);
Datum
init_server_collation(PG_FUNCTION_ARGS)
{
PG_RETURN_INT32(0);
}
/* this function is no longer needed and is only a placeholder for upgrade script */
PG_FUNCTION_INFO_V1(init_server_collation_oid);
Datum
init_server_collation_oid(PG_FUNCTION_ARGS)
{
PG_RETURN_INT32(0);
}
/* init_collid_trans_tab - this function is no longer needed and is only a placeholder for upgrade script */
Datum
init_collid_trans_tab(PG_FUNCTION_ARGS)
{
PG_RETURN_INT32(0);
}
PG_FUNCTION_INFO_V1(collation_list);
Datum
collation_list(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(tsql_collation_list_internal(fcinfo));
}
/*
* get_server_collation_oid - this is being used by sys.babelfish_update_collation_to_default
* to update the collation of system objects
*/
Datum
get_server_collation_oid(PG_FUNCTION_ARGS)
{
PG_RETURN_OID(tsql_get_database_or_server_collation_oid_internal(false));
}
Datum
is_collated_ci_as_internal(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(tsql_is_collated_ci_as_internal(fcinfo));
}
Datum
is_collated_ai_internal(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(tsql_is_collated_ai_internal(fcinfo));
}
/* init_like_ilike_table - this function is no longer needed and is only a placeholder for upgrade script */
Datum
init_like_ilike_table(PG_FUNCTION_ARGS)
{
PG_RETURN_INT32(0);
}
static Expr *
make_op_with_func(Oid opno, Oid opresulttype, bool opretset,
Expr *leftop, Expr *rightop,
Oid opcollid, Oid inputcollid, Oid oprfuncid)
{
OpExpr *expr = (OpExpr *) make_opclause(opno,
opresulttype,
opretset,
leftop,
rightop,
opcollid,
inputcollid);
expr->opfuncid = oprfuncid;
return (Expr *) expr;
}
/* helper fo make or qual, simialr to make_and_qual */
static Node *
make_or_qual(Node *qual1, Node *qual2)
{
if (qual1 == NULL)
return qual2;
if (qual2 == NULL)
return qual1;
return (Node *) make_orclause(list_make2(qual1, qual2));
}
static Node *
transform_funcexpr(Node *node)
{
if (node && IsA(node, FuncExpr))
{
FuncExpr *fe = (FuncExpr *) node;
int collidx_of_cs_as;
if (fe->funcid == 868 || //strpos - see pg_proc.dat
/* fe->funcid == 394 || // string_to_array, 3-arg form */
/* fe->funcid == 376 || // string_to_array, 2-arg form */
fe->funcid == 2073 || //substring - 2 - arg form, see pg_proc.dat
fe->funcid == 2074 || //substring - 3 - arg form, see pg_proc.dat
fe->funcid == 2285 || //regexp_replace, flags in 4 th arg
fe->funcid == 3397 || //regexp_match(find first match), flags in 3 rd arg
fe->funcid == 2764)
/* regexp_matches, flags in 3 rd arg */
{
coll_info_t coll_info_of_inputcollid = tsql_lookup_collation_table_internal(fe->inputcollid);
Node *leftop = (Node *) linitial(fe->args);
Node *rightop = (Node *) lsecond(fe->args);
if (OidIsValid(coll_info_of_inputcollid.oid) &&
coll_info_of_inputcollid.collateflags == 0x000d /* CI_AS */ )
{
Oid lower_funcid = 870;
/* lower */
Oid result_type = 25;
/* text */
tsql_get_database_or_server_collation_oid_internal(true);
if (!OidIsValid(database_or_server_collation_oid))
return node;
/*
* Find the CS_AS collation corresponding to the CI_AS
* collation Change the collation of the func op to the CS_AS
* collation
*/
collidx_of_cs_as =
tsql_find_cs_as_collation_internal(
tsql_find_collation_internal(coll_info_of_inputcollid.collname));
if (NOT_FOUND == collidx_of_cs_as)
return node;
if (fe->funcid == 2285 || fe->funcid == 3397 || fe->funcid == 2764)
{
Node *flags = (fe->funcid == 2285) ? lfourth(fe->args) : lthird(fe->args);
if (!IsA(flags, Const))
return node;
else
{
char *patt = TextDatumGetCString(((Const *) flags)->constvalue);
int f = 0;
while (patt[f] != '\0')
{
if (patt[f] == 'i')
break;
f++;
}
/*
* If the 'i' flag was specified then the operation is
* case-insensitive and so the ci_as collation may be
* replaced with the corresponding deterministic cs_as
* collation. If not, return.
*/
if (patt[f] != 'i')
return node;
}
}
fe->inputcollid = tsql_get_oid_from_collidx(collidx_of_cs_as);
if (fe->funcid >= 2285)
return node;
/*
* regexp operators have their own way to handle case
* -insensitivity
*/
if (!IsA(leftop, FuncExpr) || ((FuncExpr *) leftop)->funcid != lower_funcid)
leftop = (Node *) makeFuncExpr(lower_funcid,
result_type,
list_make1(leftop),
fe->inputcollid,
fe->inputcollid,
COERCE_EXPLICIT_CALL);
if (!IsA(rightop, FuncExpr) || ((FuncExpr *) rightop)->funcid != lower_funcid)
rightop = (Node *) makeFuncExpr(lower_funcid,
result_type,
list_make1(rightop),
fe->inputcollid,
fe->inputcollid,
COERCE_EXPLICIT_CALL);
if (list_length(fe->args) == 3)
{
Node *thirdop = (Node *) makeFuncExpr(lower_funcid,
result_type,
list_make1(lthird(fe->args)),
fe->inputcollid,
fe->inputcollid,
COERCE_EXPLICIT_CALL);
fe->args = list_make3(leftop, rightop, thirdop);
}
else if (list_length(fe->args) == 2)
{
fe->args = list_make2(leftop, rightop);
}
}
}
}
return node;
}
static CollateExpr*
create_collate_expr(Node *arg, Oid collid)
{
CollateExpr *expr = makeNode(CollateExpr);
expr->arg = (Expr *) arg;
expr->collOid = collid;
expr->location = -1;
return expr;
}
/*
* If the node is OpExpr and the colaltion is ci_as/ci_ai , then
* transform the LIKE OpExpr to ILIKE OpExpr. For ci_ai, use remove_accents_internal*
* function to remove the accents and optimize.
* If the node is OpExpr and the collation is cs_ai , then use remove_accents_internal*
* function to remove the accents and optimize.
* If the node is OpExpr and the collation is cs_as, then simply use optimization:
*
* Case 1: if the pattern is a constant string
* col LIKE PATTERN -> col = PATTERN AND col LIKE PATTERN
* col NOT LIKE PATTERN -> col <> PATTERN OR col NOT LIKE PATTERN
* Case 2: if the pattern have a constant prefix
* col LIKE PATTERN ->
* col LIKE PATTERN BETWEEN prefix AND prefix||E'\uFFFF'
* Case 3: if the pattern doesn't have a constant prefix
* col LIKE PATTERN -> col ILIKE PATTERN
*/
static Node *
optimise_likenode(Node *node, OpExpr *op, like_ilike_info_t like_entry, coll_info_t coll_info_of_inputcollid, bool is_constraint)
{
Node *leftop = copyObject(linitial(op->args));
Node *rightop = copyObject(lsecond(op->args));
Oid ltypeId = exprType(leftop);
Oid rtypeId = exprType(rightop);
char *op_str;
Node *ret;
Const *patt;
Const *prefix;
Operator optup;
Pattern_Prefix_Status pstatus;
int collidx_of_cs_as;
CollateExpr *prefix_collate;
Node *check_node;
tsql_get_database_or_server_collation_oid_internal(true);
if (!OidIsValid(database_or_server_collation_oid))
return node;
/*
* Find the CS_AS collation corresponding to the CI_AS collation
* Change the collation of the ILIKE op to the CS_AS collation
*/
collidx_of_cs_as =
tsql_find_cs_as_collation_internal(
tsql_find_collation_internal(coll_info_of_inputcollid.collname));
/*
* A CS_AS collation should always exist unless a Babelfish CS_AS
* collation was dropped or the lookup tables were not defined in
* lexicographic order. Program defensively here and just do no
* transformation in this case, which will generate a
* 'nondeterministic collation not supported' error.
*/
if (NOT_FOUND == collidx_of_cs_as)
{
elog(DEBUG2, "No corresponding CS_AS collation found for collation \"%s\"", coll_info_of_inputcollid.collname);
return node;
}
/* Change the opno and oprfuncid to ILIKE if CI collation */
if (coll_info_of_inputcollid.collateflags == 0x000f || coll_info_of_inputcollid.collateflags == 0x000d) /* CI */
{
op->opno = like_entry.ilike_oid;
op->opfuncid = like_entry.ilike_opfuncid;
}
op->inputcollid = tsql_get_oid_from_collidx(collidx_of_cs_as);
/* Remove CollateExpr as the op->inputcollid has already been set */
if (IsA(rightop, CollateExpr))
{
lsecond(op->args) = rightop = (Node*)((CollateExpr*) rightop)->arg;
}
if (IsA(leftop, CollateExpr))
{
linitial(op->args) = leftop = (Node*)((CollateExpr*) leftop)->arg;
}
/*
* Try to simplify rightop to a Const for prefix extraction.
* eval_const_expressions folds immutable subexpressions, evaluate_expr
* handles stable functions as a fallback.
*
* Peek through RelabelType wrappers to check for like_escape (ESCAPE
* clause) and remove_accents_internal (AI mode). Evaluating these at
* plan time loses escape and bracket pattern semantics.
* For AI mode, the RelabelType unwrap below handles simple patterns.
*/
check_node = rightop;
while (IsA(check_node, RelabelType))
check_node = (Node *) ((RelabelType *) check_node)->arg;
if (!(IsA(check_node, FuncExpr) &&
(strcmp(get_func_name(((FuncExpr *) check_node)->funcid),
"like_escape") == 0 ||
strcmp(get_func_name(((FuncExpr *) check_node)->funcid),
"remove_accents_internal") == 0)))
{
rightop = eval_const_expressions(NULL, rightop);
if (!IsA(rightop, Const) && !IsA(rightop, Param) &&
!checkExprHasSubLink(rightop) &&
!contain_var_clause(rightop) &&
!contain_volatile_functions(rightop) &&
bms_is_empty(pull_paramids((Expr *) rightop)))
{
rightop = (Node *) evaluate_expr((Expr *) rightop,
exprType(rightop),
exprTypmod(rightop),
exprCollation(rightop));
}
lsecond(op->args) = rightop;
}
/*
* This is needed to process CI_AI for Const nodes
* Because after we call coerce_to_target_type for type conversion in transform_likenode_for_AI,
* we obtain a Relabel node which won't help us to perform optimization
* for constant prefix. Hence, we process that here
*/
if (IsA(rightop, RelabelType))
{
RelabelType *relabel = (RelabelType *) rightop;
if (IsA(relabel->arg, Const))
{
lsecond(op->args) = relabel->arg;
rightop = (Node *) lsecond(op->args);
}
}
/*
* no constant prefix found in pattern, or pattern is not constant
* OR if it is for CHECK CONSTRAINT, we do NOT need any optimisation
* for it. Rather it will add extra overhead, moreover vanilla Postgres
* also handles check constraints this way
*/
if (IsA(leftop, Const) || !IsA(rightop, Const) ||
((Const *) rightop)->constisnull || is_constraint)
{
/* update the collation of left and right node*/
linitial(op->args) = (Node *) create_collate_expr(linitial(op->args), op->inputcollid);
lsecond(op->args) = (IsA(rightop, Const) && ((Const *) rightop)->constisnull) ? lsecond(op->args) :
(Node *) create_collate_expr(lsecond(op->args), op->inputcollid);
return node;
}
patt = (Const *) rightop;
/* extract pattern */
if (coll_info_of_inputcollid.collateflags == 0x000f || coll_info_of_inputcollid.collateflags == 0x000d) /* CI */
pstatus = pattern_fixed_prefix_wrapper(patt, 1, coll_info_of_inputcollid.oid,
&prefix, NULL);
else
pstatus = pattern_fixed_prefix_wrapper(patt, 0, coll_info_of_inputcollid.oid, /* CS */
&prefix, NULL);
/* If there is no constant prefix then there's nothing more to do */
if (pstatus == Pattern_Prefix_None)
{
/* update the collation of left and right node*/
linitial(op->args) = (Node *) create_collate_expr(linitial(op->args), op->inputcollid);
lsecond(op->args) = (Node *) create_collate_expr(lsecond(op->args), op->inputcollid);
return node;
}
/*
* Obtain the original typeId of leftop so that we can find the compatible =, >= and <
* operator for the original typeId. Else we will always obtain the operators compatible
* with TEXT datatype as the operands get type coerced into TEXT as LIKE is defined for it
* Make the typeId of rightop same as leftop so that we obtain expected operator
* Similarly, update the type of prefix to have appropriate datatypes of operands
*
* Optimiser will remove Relabel Node during Index scan, see match_index_to_operand
*/
if (IsA(leftop, RelabelType))
{
RelabelType *relabel = (RelabelType *) leftop;
leftop = copyObject((Node*) relabel->arg);
ltypeId = exprType(leftop);
}
/* Reconcile types — LIKE coerces to TEXT but we need original column type */
prefix->consttype = rtypeId = ltypeId;
/*
* We need to do this because the dump considers rightop as Const with COLLATE being added
* whereas during restore, that is considered as CollateExpr while building new expression tree
* which is adding extra parenthesis on rightop when we invoke pg_get_constraintdef() from PG
* We update the righop to equivalent CollateExpr to pick correct collation
* We are clearing collation or else we observe multiple redundant COLLATE
* clause in pg_get_constraintdef(), which will result in error during upgrade/restore
* We also set InvalidOid for highest_sort_key during creation for the same reason,
* later we enclose it withing CollateExpr
*/
prefix->constcollid = ((Const *) rightop)->constcollid = InvalidOid;
prefix_collate = create_collate_expr((Node* ) prefix, coll_info_of_inputcollid.oid);
Assert(ltypeId == rtypeId);
/* Always create a CollateExpr on top to match with op->inputcollid */
linitial(op->args) = (Node*) create_collate_expr(linitial(op->args), op->inputcollid);
lsecond(op->args) = (Node*) create_collate_expr(lsecond(op->args), op->inputcollid);
/*
* If we found an exact-match pattern, generate an "=" indexqual.
*/
if (pstatus == Pattern_Prefix_Exact)
{
op_str = like_entry.is_not_match ? "<>" : "=";
optup = compatible_oper(NULL, list_make1(makeString(op_str)), ltypeId, rtypeId,
true, -1);
if (optup == (Operator) NULL)
return node;
ret = (Node *) (make_op_with_func(oprid(optup), BOOLOID, false,
(Expr *) leftop,
(Expr *) prefix_collate,
InvalidOid,
coll_info_of_inputcollid.oid,
oprfuncid(optup)));
ret = like_entry.is_not_match ? make_or_qual(ret, node) : make_and_qual(ret, node);
ReleaseSysCache(optup);
}
else
{
Expr *greater_equal,
*less_equal,
*concat_expr;
Node *constant_suffix;
Const *highest_sort_key;
/* construct leftop >= pattern */
optup = compatible_oper(NULL, list_make1(makeString(">=")), ltypeId, rtypeId,
true, -1);
if (optup == (Operator) NULL)
return node;
/* Use the original node to create the operator */
greater_equal = make_op_with_func(oprid(optup), BOOLOID, false,
(Expr *) leftop,
(Expr *) prefix_collate,
InvalidOid,
coll_info_of_inputcollid.oid,
oprfuncid(optup));
ReleaseSysCache(optup);
/* construct pattern||E'\uFFFF' */
highest_sort_key = makeConst(rtypeId, -1, InvalidOid, -1,
PointerGetDatum(cstring_to_text(SORT_KEY_STR)), false, false);
optup = compatible_oper(NULL, list_make1(makeString("||")), rtypeId, rtypeId,
true, -1);
if (optup == (Operator) NULL)
return node;
concat_expr = make_op_with_func(oprid(optup), rtypeId, false,
(Expr *) prefix_collate,
(Expr *) create_collate_expr((Node* ) highest_sort_key, coll_info_of_inputcollid.oid),
coll_info_of_inputcollid.oid, coll_info_of_inputcollid.oid, oprfuncid(optup));
ReleaseSysCache(optup);
/* construct leftop < pattern */
optup = compatible_oper(NULL, list_make1(makeString("<")), ltypeId, rtypeId,
true, -1);
if (optup == (Operator) NULL)
return node;
/* Use the original node to create the operator */
less_equal = make_op_with_func(oprid(optup), BOOLOID, false,
(Expr *) leftop, (Expr *) concat_expr,
InvalidOid, coll_info_of_inputcollid.oid, oprfuncid(optup));
constant_suffix = make_and_qual((Node *) greater_equal, (Node *) less_equal);
if (like_entry.is_not_match)
{
constant_suffix = (Node *) make_notclause((Expr *) constant_suffix);
ret = make_or_qual(node, constant_suffix);
}
else
{
ret = make_and_qual(node, constant_suffix);
}
ReleaseSysCache(optup);
}
return ret;
}
/*
* Only use cached mappings for removing accents when the
* current ICU version matches to the one used to generate
* the cache. Otherwise we fallback on the ICU function
*/
static void
get_remove_accents_internal_oid()
{
const Oid funcargtypes[1] = {TEXTOID};
if (OidIsValid(remove_accents_internal_oid))
return;
#ifdef USE_ICU
if (U_ICU_VERSION_MAJOR_NUM == pltsql_remove_accent_map_icu_major_version && U_ICU_VERSION_MINOR_NUM == pltsql_remove_accent_map_icu_min_version)
{
elog(DEBUG1, "Using cached mappings to remove accents");
remove_accents_internal_oid = LookupFuncName(list_make2(makeString("sys"), makeString("remove_accents_internal_using_cache")), -1, funcargtypes, true);
return;
}
#endif
elog(DEBUG1, "Using ICU function to remove accents");
remove_accents_internal_oid = LookupFuncName(list_make2(makeString("sys"), makeString("remove_accents_internal")), -1, funcargtypes, true);
}
/*
* store 32bit character representation into multibyte stream
*/
static inline void
store_coded_char(unsigned char *dest, uint32 code)
{
if (code & 0xff000000)
{
*dest++ = code >> 24;
}
if (code & 0x00ff0000)
{
*dest++ = code >> 16;
}
if (code & 0x0000ff00)
{
*dest++ = code >> 8;
}
if (code & 0x000000ff)
{
*dest++ = code;
}
*dest = '\0';
return;
}
static int
compare_remove_accent_map_pair(const void *p1, const void *p2)
{
uint32 v1,
v2;
v1 = *(const uint32 *) p1;
v2 = ((const remove_accent_map_pair *) p2)->original_char;
return (v1 > v2) ? 1 : ((v1 == v2) ? 0 : -1);
}
PG_FUNCTION_INFO_V1(remove_accents_internal_using_cache);
Datum remove_accents_internal_using_cache(PG_FUNCTION_ARGS)
{
unsigned char *input_str,
*input_str_start,
*normalized_char;
int len,
char_len;
text *return_result;
StringInfoData result;
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
input_str = (unsigned char *) text_to_cstring(PG_GETARG_TEXT_PP(0));
input_str_start = input_str;
len = strlen((char *) input_str);
initStringInfo(&result);
normalized_char = (unsigned char *) palloc(sizeof(uint32) + 1);
for (; len > 0; len -= char_len)
{
unsigned char b1 = 0;
unsigned char b2 = 0;
unsigned char b3 = 0;
unsigned char b4 = 0;
uint32 utf8_char;
uint32 utf8_normalized_str;
remove_accent_map_pair *pr;
/* "break" cases all represent errors */
if (*input_str == '\0')
break;
char_len = pg_utf_mblen(input_str);
if (len < char_len)
break;
if (!pg_utf8_islegal(input_str, char_len))
break;
if (char_len == 1)
{
appendBinaryStringInfo(&result, input_str++, 1);
continue;
}
/* collect coded char of length l */
if (char_len == 2)
{
b3 = *input_str++;
b4 = *input_str++;
}
else if (char_len == 3)
{
b2 = *input_str++;
b3 = *input_str++;
b4 = *input_str++;
}
else if (char_len == 4)
{
b1 = *input_str++;
b2 = *input_str++;
b3 = *input_str++;
b4 = *input_str++;
}
else
{
elog(ERROR, "unsupported character length %d", char_len);
}
utf8_char = (b1 << 24 | b2 << 16 | b3 << 8 | b4);
pr = bsearch(&utf8_char, pltsql_remove_accent_map, lengthof(pltsql_remove_accent_map),
sizeof(remove_accent_map_pair), compare_remove_accent_map_pair);
/* Use the mapping if availaible or else the character */
if (pr && pr->normalized_char)
utf8_normalized_str = pr->normalized_char;
else
utf8_normalized_str = utf8_char;
store_coded_char(normalized_char, utf8_normalized_str);
appendBinaryStringInfo(&result, normalized_char, strlen((const char *) normalized_char));
}
if (len > 0)
ereport(ERROR,
(errcode(ERRCODE_CHARACTER_NOT_IN_REPERTOIRE),
errmsg("invalid byte sequence for encoding UTF-8 while removing accents")));
return_result = cstring_to_text_with_len(result.data, result.len);
pfree(result.data);
pfree(input_str_start);
pfree(normalized_char);
PG_RETURN_VARCHAR_P(return_result);
}
/*
* Function responsible for obtaining unaccented version of input
* string with the help of ICU provided APIs.
* We use a transformation rule to transliterate the string
*/
PG_FUNCTION_INFO_V1(remove_accents_internal);
Datum remove_accents_internal(PG_FUNCTION_ARGS)
{
char *input_str = text_to_cstring(PG_GETARG_TEXT_PP(0));
UChar *utf16_input, *utf16_res;
int32_t len_uinput, limit, capacity, len_result;
char *result;
UErrorCode status = U_ZERO_ERROR;
text *res_str;
size_t required_size;
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
#ifdef USE_ICU
// Check if transliterator is not yet cached
if (!cached_transliterator)
{
MemoryContext oldcontext;
UChar *rules;
int32_t len_uchar;
// Switch to TopMemoryContext for allocating cached transliterator
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
// Load transliterator rules
len_uchar = icu_to_uchar(&rules, TRANSFORMATION_RULE, strlen(TRANSFORMATION_RULE));
// Open transliterator
cached_transliterator = utrans_openU(rules, len_uchar, UTRANS_FORWARD, NULL, 0, NULL, &status);
if (U_FAILURE(status) || !cached_transliterator)
{
ereport(ERROR,
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
errmsg("Error opening transliterator: %s", u_errorName(status))));
}
// Switch back to original memory context
MemoryContextSwitchTo(oldcontext);
}
/*
* XXX: Currently, we are allowing length of input string upto 250MB bytes. For long term,
* we should try to chunk the input string into smaller parts, remove the accents of that
* part and concat back the final string.
*/
if (strlen(input_str) > MAX_INPUT_LENGTH_TO_REMOVE_ACCENTS)
{
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("Input string of the length greater than 250MB is not supported by the function remove_accents_internal." \
" This function might be used internally by LIKE operator.")));
}
len_uinput = icu_to_uchar(&utf16_input, input_str, strlen(input_str));
limit = len_uinput;
/*
* set the capacity (In UChar terms) to limit * MAX_BYTES_PER_CHAR if it is less than INT32_MAX
* else set it to INT32_MAX as capacity is of int32_t datatype so it can have maximum INT32_MAX
* value which would be equivalent to 2GB UChar points and 2GB * sizeof(UChar) in byte terms.
* XXX: It is assumed that this capacity should handle almost all the general input strings.
*/
capacity = (limit < (PG_INT32_MAX / MAX_BYTES_PER_CHAR)) ? (limit * MAX_BYTES_PER_CHAR) : PG_INT32_MAX;
/*
* utrans_transUChars will modify input string in place so ensure that it has enough capacity to store
* transformed string.
*/
utf16_res = (UChar *) palloc0(capacity * sizeof(UChar));
/*
* utf16_input would have one NULL terminator at the end. Copy that too. Limiting memory copy to min of
* (len_uinput + 1) * sizeof(UChar) and capacity * sizeof(UChar) in order to avoid buffer overwriting.
*/
memcpy(utf16_res, utf16_input, Min((len_uinput + 1) * sizeof(UChar), capacity * sizeof(UChar)));
pfree(utf16_input);
pfree(input_str);
utrans_transUChars(cached_transliterator,
utf16_res,
&len_uinput,
capacity,
0,
&limit,
&status);
/* Allocated capacity may not be enough to hold un-accented string. This shouldn't occur ideally but still defensive code. */
if (U_FAILURE(status))
{
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("Error normalising the input string: %s", u_errorName(status))));
}
/* Get required size of result */
required_size = icu_from_uchar(NULL, 0, utf16_res, len_uinput);
result = palloc(required_size + 1);
len_result = icu_from_uchar(result, required_size + 1, utf16_res, len_uinput);
pfree(utf16_res);
// Return result as NVARCHAR
res_str = cstring_to_text_with_len(result, len_result);
PG_RETURN_VARCHAR_P(res_str);
#else
ereport(ERROR,
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
errmsg("ICU library is required to be installed in order to use the function remove_accents_internal")));
PG_RETURN_NULL();
#endif
}
static Node *
convert_node_to_funcexpr_for_like(Node *node, Oid inputcollid)
{
FuncExpr *newFuncExpr = makeNode(FuncExpr);
Node *new_node;
newFuncExpr->funcid = remove_accents_internal_oid;
newFuncExpr->funcresulttype = get_sys_nvarcharoid();
newFuncExpr->funccollid = inputcollid;
newFuncExpr->inputcollid = inputcollid;
newFuncExpr->funcretset = false;
newFuncExpr->funcvariadic = false;
newFuncExpr->location = -1;
if (node == NULL)
return node;
switch (nodeTag(node))
{
case T_Const:
{
Const *con;
new_node = coerce_to_target_type(NULL, (Node *) node, exprType(node),
TEXTOID, -1,
COERCION_EXPLICIT,
COERCE_EXPLICIT_CAST,
exprLocation(node));
if (unlikely(new_node == NULL))
{
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Could not type cast the input argument of LIKE operator to desired data type")));
}
if (IsA(new_node, Const))
{
con = (Const *) new_node;
if (con->constisnull)
return new_node;
con->constvalue = OidFunctionCall1(remove_accents_internal_oid, con->constvalue);
con->constcollid = InvalidOid;
return (Node *) con;
}
else
{
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Could not convert Const node to desired node type")));
}
return new_node;
}
case T_FuncExpr:
case T_Var:
case T_Param:
case T_CaseExpr:
case T_RelabelType:
case T_CoerceViaIO:
{
new_node = coerce_to_target_type(NULL, (Node *) node, exprType(node),
TEXTOID, -1,
COERCION_EXPLICIT,
COERCE_EXPLICIT_CAST,
exprLocation(node));
if (unlikely(new_node == NULL))
{
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Could not type cast the input argument of LIKE operator to desired data type")));
}
newFuncExpr->args = list_make1(new_node);
break;
}
case T_CollateExpr:
{
CollateExpr *collateexpr = (CollateExpr*) node;
if (IsA(collateexpr->arg, Const))
{
Const *constnode = (Const*) (collateexpr->arg);
constnode->constcollid = collateexpr->collOid;
new_node = coerce_to_target_type(NULL, (Node *) constnode, exprType((Node *)constnode),
TEXTOID, -1,
COERCION_EXPLICIT,
COERCE_EXPLICIT_CAST,
exprLocation(node));
if (unlikely(new_node == NULL))
{
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Could not type cast the input argument of LIKE operator to desired data type")));
}
if (IsA(new_node, Const))
{
constnode = (Const *) new_node;
if (constnode->constisnull)
return new_node;
constnode->constvalue = OidFunctionCall1(remove_accents_internal_oid, constnode->constvalue);
constnode->constcollid = InvalidOid;
return (Node *) constnode;
}
else
{