File: Beautify.pm

package info (click to toggle)
pgformatter 5.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 7,936 kB
  • sloc: sql: 186,285; perl: 5,662; makefile: 2; sh: 1
file content (5598 lines) | stat: -rwxr-xr-x 180,772 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
package pgFormatter::Beautify;

use strict;
use warnings;
use warnings qw( FATAL );
use Encode   qw( decode );
use utf8;

binmode STDIN,  ':utf8';
binmode STDOUT, ':utf8';
binmode STDERR, ':utf8';

use Text::Wrap;

our $DEBUG    = 0;
our $DEBUG_SP = 0;

# PostgreSQL functions that use a FROM clause
our @have_from_clause = qw( extract overlay substring trim );
our @extract_keywords =
  qw(century day decade dow doy epoch hour isodow isoyear microseconds millennium minute month quarter second timezone timezone_minute week year);

our $math_operators =
  qr{^(?:\+|\-|\*|\/|\%|\^|\|\/|\|\|\/|\!|\!\!|\@|\&|\||\#|\~|<<|>>|=|>=|<=)$};

=head1 NAME

pgFormatter::Beautify - Library for pretty-printing SQL queries

=head1 VERSION

Version 5.8

=cut

# Version of pgFormatter
our $VERSION = '5.8';

# Inclusion of code from Perl package SQL::Beautify
# Copyright (C) 2009 by Jonas Kramer
# Published under the terms of the Artistic License 2.0.

=head1 SYNOPSIS

This module can be used to reformat given SQL query, optionally anonymizing parameters.

Output can be either plain text, or it can be HTML with appropriate styles so that it can be displayed on a web page.

Example usage:

    my $beautifier = pgFormatter::Beautify->new();
    $beautifier->query( 'select a,b,c from d where e = f' );

    $beautifier->beautify();
    my $nice_txt = $beautifier->content();

    $beautifier->format('html');
    $beautifier->beautify();
    my $nice_html = $beautifier->content();

    $beautifier->format('html');
    $beautifier->anonymize();
    $beautifier->beautify();
    my $nice_anonymized_html = $beautifier->content();

    $beautifier->format();
    $beautifier->beautify();
    $beautifier->wrap_lines()
    my $wrapped_txt = $beautifier->content();

=head1 FUNCTIONS

=head2 new

Generic constructor - creates object, sets defaults, and reads config from given hash with options.

Takes options as hash. Following options are recognized:

=over

=item * break - String that is used for linebreaks. Default is "\n".

=item * colorize - if set to false CSS style will not be applied to html output. Used internally to display errors in CGI mode withour style.

=item * comma - set comma at beginning or end of a line in a parameter list

=over

=item end - put comma at end of the list (default)

=item start - put comma at beginning of the list

=back

=item * comma_break - add new-line after each comma in INSERT statements

=item * format - set beautify format to apply to the content (default: text)

=over

=item text - output content as plain/text (command line mode default)

=item html - output text/html with CSS style applied to content (CGI mode default)

=back

=item * functions - list (arrayref) of strings that are function names

=item * keywords - list (arrayref) of strings that are keywords

=item * multiline - use multi-line search for placeholder regex, see placeholder.

=item * no_comments - if set to true comments will be removed from query

=item * no_grouping - if set to true statements will not be grouped in a transaction, an extra newline character will be added between statements like outside a transaction.

=item * placeholder - use the specified regex to find code that must not be changed in the query.

=item * query - query to beautify

=item * rules - hash of rules - uses rule semantics from SQL::Beautify

=item * space - character(s) to be used as space for indentation

=item * spaces - how many spaces to use for indentation

=item * uc_functions - what to do with function names:

=over

=item 0 - do not change

=item 1 - change to lower case

=item 2 - change to upper case

=item 3 - change to Capitalized

=back

=item * separator - string used as dynamic code separator, default is single quote

=item * uc_keywords - what to do with keywords - meaning of value like with uc_functions

=item * uc_types - what to do with data types - meaning of value like with uc_functions

=item * wrap - wraps given keywords in pre- and post- markup. Specific docs in SQL::Beautify

=item * format_type - try an other formatting

=item * wrap_limit - wrap queries at a certain length

=item * wrap_after - number of column after which lists must be wrapped

=item * wrap_comment - apply wrapping to comments starting with --

=item * numbering - statement numbering as a comment before each query

=item * redshift - add Redshift keywords (obsolete, use --extra-keyword)

=item * no_extra_line - do not add an extra empty line at end of the output

=item * keep_newline - preserve empty line in plpgsql code 

=item * no_space_function - remove space before function call and open parenthesis

=item * redundant_parenthesis - do not eliminate redundant parenthesis in DML queries

=back

For defaults, please check function L<set_defaults>.

=cut

sub new {
	my $class   = shift;
	my %options = @_;

	my $self = bless {}, $class;
	$self->set_defaults();

	for my $key (
		qw( query spaces space break wrap keywords functions rules uc_keywords uc_functions uc_types no_comments no_grouping placeholder multiline separator comma comma_break format colorize format_type wrap_limit wrap_after wrap_comment numbering redshift no_extra_line keep_newline no_space_function redundant_parenthesis)
	  )
	{
		$self->{$key} = $options{$key} if defined $options{$key};
	}

	$self->_refresh_functions_re();

	# Make sure "break" is sensible
	$self->{'break'} = ' ' if $self->{'spaces'} == 0;

	# Initialize internal stuff.
	$self->{'_level'} = 0;

	# Array to store placeholders values
	@{ $self->{'placeholder_values'} } = ();

	# Hash to store dynamic code
	%{ $self->{'dynamic_code'} } = ();

	# Hash to store and preserve constants
	%{ $self->{'keyword_constant'} } = ();

	# Hash to store and preserve aliases between double quote
	%{ $self->{'alias_constant'} } = ();

	# Check comma value, when invalid set to default: end
	if ( lc( $self->{'comma'} ) ne 'start' ) {
		$self->{'comma'} = 'end';
	}
	else {
		$self->{'comma'} = lc( $self->{'comma'} );
	}

	$self->{'format'}        //= 'text';
	$self->{'colorize'}      //= 1;
	$self->{'format_type'}   //= 0;
	$self->{'wrap_limit'}    //= 0;
	$self->{'wrap_after'}    //= 0;
	$self->{'wrap_comment'}  //= 0;
	$self->{'no_extra_line'} //= 0;

	return $self;
}

=head2 query

Accessor to query string. Both reads:

    $object->query()

, and writes

    $object->query( $something )

=cut

sub query {
	my $self      = shift;
	my $new_value = shift;

	$self->{'query'} = $new_value if defined $new_value;

	$self->{idx_code} = 0;

	# Replace any COMMENT constant between single quote
	while ( $self->{'query'} =~
		s/IS\s+([EU]*'(?:[^;]*)')\s*;/IS TEXTVALUE$self->{idx_code};/is )
	{
		$self->{dynamic_code}{ $self->{idx_code} } = $1;
		$self->{dynamic_code}{ $self->{idx_code} } =~
s/([\n\r])\s+([EU]*'(?:[^']*)')/$1 . ($self->{ 'space' } x $self->{ 'spaces' }) . $2/gsei;
		$self->{idx_code}++;
	}

	# Replace any \\ by BSLHPGF
	$self->{'query'} =~ s/\\\\/BSLHPGF/sg;

	# Replace any \' by PGFBSLHQ
	$self->{'query'} =~ s/\\'/PGFBSLHQ/sg;

	# Replace any '' by PGFESCQ1
	while ( $self->{'query'} =~ s/([^'])''([^'])/$1PGFESCQ1$2/s ) { }

	# Replace any '''' by PGFESCQ1PGFESCQ1
	while ( $self->{'query'} =~ s/([^'])''''([^'])/$1PGFESCQ1PGFESCQ1$2/s ) { }

	# Replace any '...''' by '.*PGFESCQ1'
	while ( $self->{'query'} =~ s/([^']'[^']+)''('[^'])/$1PGFESCQ1$2/s ) { }

	# Replace any '''...' by 'PGFESCQ1.*'
	while ( $self->{'query'} =~ s/([^']')''([^']+'[^'])/$1PGFESCQ1$2/s ) { }

	# Replace any multiline '''...''' by 'PGFESCQ1...PGFESCQ1'
	$self->{'query'} =~ s/([^']')''([^']*)''('[^']|$)/$1PGFESCQ1$2PGFESCQ1$3/sg;

	# Replace any "" by PGFESCQ2
	while ( $self->{'query'} =~ s/([^"])""([^"])/$1PGFESCQ2$2/s ) { }

	# Replace aliases using double quote
	my $j = 0;
	while ( $self->{'query'} =~ s/(\s+AS\s*)("+[^"]+"+)/$1PGFALIAS$j/is ) {
		$self->{'alias_constant'}{$j} = $2;
		$j++;
	}

	# Escape quote in comments
	while ( $self->{'query'} =~ s/(\/\*(?:.*)?)'((?:.*)?\*\/)/$1SNGLQUOTE$2/s )
	{
	}

	# replace all constant between quote
	$j = 0;
	while ( $self->{'query'} =~ s/('[^'\n\r]+')/AAKEYWCONST${j}AA/s ) {
		$self->{'keyword_constant'}{$j} = $1;
		$j++;
	}

	# Restore quote in comments
	$self->{'query'} =~ s/SNGLQUOTE/'/gs;
	foreach my $k ( keys %{ $self->{'keyword_constant'} } ) {
		$self->{'keyword_constant'}{$k} =~ s/SNGLQUOTE/'/gs;
	}

	# Fix false positive generated by code above.
	while ( $self->{'query'} =~
		s/(\s+AS\s+)AAKEYWCONST(\d+)AA/$1$self->{ 'keyword_constant' }{$2}/is )
	{
		delete $self->{'keyword_constant'}{$2};
	}

# Hide content of format() function when the code separator is not a single quote */
	my $i = 0;
	while ( $self->{'query'} =~
		s/\bformat\((\$(?:.*)?\$\s*)([,\)])/format\(CODEPARTB${i}CODEPARTB$2/i )
	{
		push( @{ $self->{'placeholder_values'} }, $1 );
		$i++;
	}
	my %temp_placeholder = ();
	my @temp_content =
	  split( /(CREATE(?:\s+OR\s+REPLACE)?\s+(?:FUNCTION|PROCEDURE)\s+)/i,
		$self->{'query'} );
	if ( $#temp_content > 0 ) {
		for ( my $j = 0 ; $j <= $#temp_content ; $j++ ) {
			next
			  if ( $temp_content[$j] =~ /^CREATE/i or $temp_content[$j] eq '' );

			# Replace single quote code delimiter into $PGFDLM$
			if ( $temp_content[$j] !~
				s/(\s+AS\s+)'(\s+.*?;\s*)'/$1\$PGFDLM\$$2\$PGFDLM\$/is )
			{
				$temp_content[$j] =~
				  s/(\s+AS\s+)'(\s+.*?END[;]*\s*)'/$1\$PGFDLM\$$2\$PGFDLM\$/is;
			}

# Remove any call too CREATE/DROP LANGUAGE to not break search of function code separator
			$temp_content[$j] =~ s/(CREATE|DROP)\s+LANGUAGE\s+[^;]+;.*//is;

	  # Fix case where code separator with $ is associated to begin/end keywords
			$temp_content[$j] =~ s/([^\s]+\$)(BEGIN\s)/$1 $2/igs;
			$temp_content[$j] =~ s/(\sEND)(\$[^\s]+)/$1 $2/igs;
			$temp_content[$j] =~ s/(CREATE|DROP)\s+LANGUAGE\s+[^;]+;.*//is;
			my $fctname = '';
			if ( $temp_content[$j] =~ /^([^\s\(]+)/ ) {
				$fctname = lc($1);
			}
			next if ( !$fctname );
			my $language = 'sql';
			if ( $temp_content[$j] =~ /\s+LANGUAGE\s+[']*([^'\s;]+)[']*/is ) {
				$language = lc($1);
				if ( $language =~ /AAKEYWCONST(\d+)AA/i ) {
					$language = lc( $self->{'keyword_constant'}{$1} );
					$language =~ s/'//g;
				}
			}

			if ( $language =~ /^internal$/i ) {
				if ( $temp_content[$j] =~
					s/AS ('[^\']+')/AS CODEPARTB${i}CODEPARTB/is )
				{
					push( @{ $self->{'placeholder_values'} }, $1 );
					$i++;
				}
			}

			# C function language with AS obj_file, link_symbol
			elsif ( $language =~ /^c$/i ) {
				if ( $temp_content[$j] =~
s/AS ('[^\']+')\s*,\s*('[^\']+')/AS CODEPARTB${i}CODEPARTB/is
				  )
				{
					push( @{ $self->{'placeholder_values'} }, "$1, $2" );
					$i++;
				}
			}

			# if the function language is not SQL or PLPGSQL
			elsif ( $language !~ /^(?:plpg)?sql$/ ) {

				# Try to find the code separator
				my $tmp_str = $temp_content[$j];
				while ( $tmp_str =~ s/\s+AS\s+([^\s]+)\s+//is ) {
					my $code_sep = quotemeta($1);
					foreach my $k ( @{ $self->{'keywords'} } ) {
						last if ( $code_sep =~ s/\b$k$//i );
					}
					next if ( !$code_sep );
					if ( $tmp_str =~ /\s+$code_sep[\s;]+/ ) {
						while ( $temp_content[$j] =~
							s/($code_sep(?:.+?)$code_sep)/CODEPART${i}CODEPART/s
						  )
						{
							push( @{ $self->{'placeholder_values'} }, $1 );
							$i++;
						}
						last;
					}
				}
			}
		}
	}
	$self->{'query'} = join( '', @temp_content );

 # Store values of code that must not be changed following the given placeholder
	if ( $self->{'placeholder'} ) {
		if ( !$self->{'multiline'} ) {
			while ( $self->{'query'} =~
				s/($self->{ 'placeholder' })/PLACEHOLDER${i}PLACEHOLDER/ )
			{
				push( @{ $self->{'placeholder_values'} }, $1 );
				$i++;
			}
		}
		else {
			while ( $self->{'query'} =~
				s/($self->{ 'placeholder' })/PLACEHOLDER${i}PLACEHOLDER/s )
			{
				push( @{ $self->{'placeholder_values'} }, $1 );
				$i++;
			}
		}
	}

	# Replace dynamic code with placeholder
	$self->_remove_dynamic_code( \$self->{'query'}, $self->{'separator'} );

	# Replace operator with placeholder
	$self->_quote_operator( \$self->{'query'} );

	# Replace comment with not quote delimiter with placeholder
	$self->_quote_comment_stmt( \$self->{'query'} );

	return $self->{'query'};
}

=head2 content

Accessor to content of results. Must be called after $object->beautify().

This can be either plain text or html following the format asked by the
client with the $object->format() method.

=cut

sub content {
	my $self      = shift;
	my $new_value = shift;

	$self->{'content'} = $new_value if defined $new_value;
	$self->{'content'} =~ s/\(\s+\(/\(\(/gs;

	# Replace placeholders with their original dynamic code
	$self->_restore_dynamic_code( \$self->{'content'} );

	# Replace placeholders with their original operator
	$self->_restore_operator( \$self->{'content'} );

	# Replace placeholders with their original string
	$self->_restore_comment_stmt( \$self->{'content'} );

	# Replace placeholders by their original values
	if ( $#{ $self->{'placeholder_values'} } >= 0 ) {
		$self->{'content'} =~
		  s/PLACEHOLDER(\d+)PLACEHOLDER/$self->{ 'placeholder_values' }[$1]/igs;
		$self->{'content'} =~
s/CODEPART[B]*(\d+)CODEPART[B]*/$self->{ 'placeholder_values' }[$1]/igs;
	}

	$self->{'content'} =~ s/PGFALIAS(\d+)/$self->{ 'alias_constant' }{$1}/gs;

	while ( $self->{'content'} =~
		s/AAKEYWCONST(\d+)AA/$self->{ 'keyword_constant' }{$1}/s )
	{
		delete $self->{'keyword_constant'}{$1};
	}

	# Replace any BSLHPGF by \\
	$self->{'content'} =~ s/BSLHPGF/\\\\/g;

	# Replace any PGFBSLHQ by \'
	$self->{'content'} =~ s/PGFBSLHQ/\\'/g;

	# Replace any $PGFDLM$ by code delimiter '
	$self->{'content'} =~ s/\$PGFDLM\$/'/g;

	# Replace any PGFESCQ1 by ''
	$self->{'content'} =~ s/PGFESCQ1/''/g;

	# Replace any PGFESCQ2 by ""
	$self->{'content'} =~ s/PGFESCQ2/""/g;

	return $self->{'content'};
}

=head2 highlight_code

Makes result html with styles set for highlighting.

=cut

sub highlight_code {
	my ( $self, $token, $last_token, $next_token ) = @_;

	# Do not use uninitialized variable
	$last_token //= '';
	$next_token //= '';

	# Colorize operators
	while ( my ( $k, $v ) = each %{ $self->{'dict'}->{'symbols'} } ) {
		if ( $token eq $k ) {
			$token = '<span class="sy0">' . $v . '</span>';
			return $token;
		}
	}

	# lowercase/uppercase keywords taking care of function with same name
	if (
		$self->_is_keyword( $token, $next_token, $last_token )
		&& (  !$self->_is_function( $token, $last_token, $next_token )
			|| $next_token ne '(' )
	  )
	{
		if ( $self->{'uc_keywords'} == 1 ) {
			$token = '<span class="kw1_l">' . $token . '</span>';
		}
		elsif ( $self->{'uc_keywords'} == 2 ) {
			$token = '<span class="kw1_u">' . $token . '</span>';
		}
		elsif ( $self->{'uc_keywords'} == 3 ) {
			$token = '<span class="kw1_c">' . $token . '</span>';
		}
		else {
			$token = '<span class="kw1">' . $token . '</span>';
		}
		return $token;
	}

  # lowercase/uppercase known functions or words followed by an open parenthesis
  # if the token is not a keyword, an open parenthesis or a comment
	if (
		(
			   $self->_is_function( $token, $last_token, $next_token )
			&& $next_token eq '('
		)
		|| (   !$self->_is_keyword( $token, $next_token, $last_token )
			&& $next_token ne '('
			&& $token ne '('
			&& !$self->_is_comment($token) )
	  )
	{
		if ( $self->{'uc_functions'} == 1 ) {
			$token = '<span class="kw2_l">' . $token . '</span>';
		}
		elsif ( $self->{'uc_functions'} == 2 ) {
			$token = '<span class="kw2_u">' . $token . '</span>';
		}
		elsif ( $self->{'uc_functions'} == 3 ) {
			$token = '<span class="kw2_c">' . $token . '</span>';
		}
		else {
			$token = '<span class="kw2">' . $token . '</span>';
		}
		return $token;
	}

	# Colorize STDIN/STDOUT in COPY statement
	if ( grep( /^\Q$token\E$/i, @{ $self->{'dict'}->{'copy_keywords'} } ) ) {
		if ( $self->{'uc_keywords'} == 1 ) {
			$token = '<span class="kw3_!">' . $token . '</span>';
		}
		elsif ( $self->{'uc_keywords'} == 2 ) {
			$token = '<span class="kw3_u">' . $token . '</span>';
		}
		elsif ( $self->{'uc_keywords'} == 3 ) {
			$token = '<span class="kw3_c">' . $token . '</span>';
		}
		else {
			$token = '<span class="kw3">' . $token . '</span>';
		}
		return $token;
	}

	# Colorize parenthesis
	if ( grep( /^\Q$token\E$/i, @{ $self->{'dict'}->{'brackets'} } ) ) {
		$token = '<span class="br0">' . $token . '</span>';
		return $token;
	}

	# Colorize comment
	if ( $self->_is_comment($token) ) {
		$token = '<span class="br1">' . $token . '</span>';
		return $token;
	}

	# Colorize numbers
	$token =~ s/\b(\d+)\b/<span class="nu0">$1<\/span>/igs;

	# Colorize string
	$token =~ s/('.*?(?<!\\)')/<span class="st0">$1<\/span>/gs;
	$token =~ s/(`[^`]*`)/<span class="st0">$1<\/span>/gs;

	return $token;
}

=head2 tokenize_sql

Splits input SQL into tokens

Code lifted from SQL::Beautify

=cut

sub tokenize_sql {
	my $self  = shift;
	my $query = shift;

	$query ||= $self->{'query'};

	# just in case it has not been called in the main script
	$query = $self->query() if ( !$query );

	my $re = qr{
        (
		(?:\\(?:copyright|errverbose|gx|gexec|gset|gdesc|q|crosstabview|watch|\?|copy|qecho|echo|if|elif|else|endif|edit|ir|include_relative|include|warn|write|html|print|out|ef|ev|h|H|i|p|r|s|w|o|e|g|q|d(?:[aAbcCdDeEfFgilLmnoOpPrRstTuvwxy+]{0,3})?|l\+?|sf\+?|sv\+?|z|a|C|f|H|t|T|x|c|pset|connect|encoding|password|conninfo|cd|setenv|timing|prompt|reset|set|unset|lo_export|lo_import|lo_list|lo_unlink|\!))(?:$|[\n]|[\ \t](?:(?!\\(?:\\|pset|reset|connect|encoding|password|conninfo|cd|setenv|timing|prompt|set|unset|lo_export|lo_import|lo_list|lo_unlink|\!|copy|qecho|echo|edit|html|include_relative|include|print|out|warn|watch|write|q))[\ \t\S])*)        # psql meta-command
		|
		AAKEYWCONST\d+AA(?:\s+AAKEYWCONST\d+AA)+             # preserved multiple constants with newline
		|
		AAKEYWCONST\d+AA             # preserved constants
		|
		\/\/			# mysql delimiter ( $$ is handled later with PG code delimiters )
		|
		(?:COPY\s+[^\s]+\s+\((?:.*?)\\\.)		# COPY and its content
		|
		[^\s\(,]+\%(?:ROWTYPE|TYPE)      # single line comments
		|
		(?:\s*--)[\ \t\S]*      # single line comments
		|
		(?:\-\|\-) # range operator "is adjacent to"
		|
		(?:\%[\d\-\*\$]*[sIL]) # format() placeholder
		|
		(?:<\%|\%>|<<\->|<\->>|<\->)  # pg_trgm and some geometry operators
		|
		(?:\->>|\->|<\#>|\#>>|\#>|\?\&|\?\||\?|\@\?)  # Vector and Json Operators
		|
		(?:\#<=|\#>=|\#<>|\#<|\#=) # compares tinterval and reltime
		|
		(?:>>=|<<=) # inet operators
		|
		(?:!!|\@\@\@) # deprecated factorial and full text search  operators
		|
		(?:\|\|\/|\|\/) # square root and cube root
		|
		(?:\@\-\@|\@\@|\#\#|<<\||\|>>|\&<\||\&<|\|\&>|\&>|<\^|>\^|\?\#|\#|\?<\||\?\-\||\?\-|\?\|\||\?\||\@>|<\@|\~=)
                                 # Geometric Operators
		|
		(?:~<=~|~>=~|~>~|~<~) # string comparison for pattern matching operator families
		|
		(?:!~~|!~~\*|~~\*|~~) # LIKE operators
		|
		(?:!~\*|!~|~\*) # regular expression operators
		|
		(?:\*=|\*<>|\*<=|\*>=|\*<|\*>) # composite type comparison operators
		|
		(?:\d+e[\+\-]\d+) # signed exponents
		|
		(?:<>|<=>|>=|<=|=>|==|!=|:=|=|!|<<|>>|<|>|\|\||\||&&|&|\-|\+|\*(?!/)|/(?!\*)|\%|~|\^|\?) # operators and tests
		|
		[\[\]\(\),;.]            # punctuation (parenthesis, comma)
		|
		\"\"(?!\"")             # empty double quoted string
		|
		"[^\"\s]+"\.[^\"\s\(\)=<>!~\*&:\|\-\+\%\^\?\@\#\[\]\{\}\.,;']+ # fqdn identifier form "schema".table or "table".column
		|
		[^\"\s=<>!~\*&\(\):\|\-\+\%\^\?\@\#\[\]\{\}\.,;']+\."[^\"\s]+" # fqdn identifier form schema."table" or table."column"
		|
		"[^\"\s]+"\."[^\"\s]+" # fqdn identifier form "schema"."table" or "table"."column"
		|
		"(?>(?:(?>[^"\\]+)|""|\\.)*)+" # anything inside double quotes, ungreedy
		|
		`(?>(?:(?>[^`\\]+)|``|\\.)*)+` # anything inside backticks quotes, ungreedy
		|
		[EB]*'[^']+' # anything inside single quotes, ungreedy.
		|
		/\*[\ \t\r\n\S]*?\*/      # C style comments
		|
		(?:[\w:\@]+[\$]*[\w:\@]*(?:\.(?:\w+|\*)?)*) # words, standard named placeholders, db.table.*, db.*
		|
		(?:\$\w+\$)
                |
                (?: \$_\$ | \$\d+ | \${1,2} | \$\w+\$) # dollar expressions - eg $_$ $3 $$ $BODY$
                |
                (?:\r\n){2,}                      # empty line Windows
                |
                \n{2,}                      # empty line Unix
                |
                \r{2,}                      # empty line Mac
                |
                [\t\ ]+                 # any kind of white spaces
		|
		[^\s\*\/\-\\;:,]+                 # anything else
        )
    }ismx;

	my @query = grep { /\S/ } $query =~ m{$re}simxg;
	if ( $self->{'keep_newline'} ) {
		@query = grep { /(?:\S|^[\r\n]+$)/ } $query =~ m{$re}simxg;
	}

	# fix := operator that can not be found when attached to the variable name
	for ( my $i = 0 ; $i < $#query ; $i++ ) {
		if ( $query[$i] =~ /:$/ && $query[ $i + 1 ] =~ /^=/ ) {
			$query[$i] =~ s/:$//;
			$query[ $i + 1 ] =~ s/^/:/;
		}
	}

	# Revert position when a comment is before a comma
	if ( $self->{'comma'} eq 'end' ) {
		for ( my $i = 0 ; $i < ( $#query - 1 ) ; $i++ ) {
			if ( $query[ $i + 1 ] eq ',' and $self->_is_comment( $query[$i] ) )
			{
				$query[ $i + 1 ] = $query[$i];
				$query[$i] = ',';
			}
		}
	}

	# Fix token split of negative numbers
	if ( $#query > 2 ) {
		for ( my $i = 2 ; $i <= $#query ; $i++ ) {
			if (
				$query[$i] =~ /^[\d\.]+$/ && $query[ $i - 1 ] =~ /^[\+\-]$/
				and (  $query[ $i - 2 ] =~ /$math_operators/
					or $query[ $i - 2 ] =~ /^(?:,|\(|\[)$/
					or $self->_is_keyword( $query[ $i - 2 ] ) )
			  )
			{
				$query[$i] = $query[ $i - 1 ] . $query[$i];
				$query[ $i - 1 ] = '';
			}
			elsif (
					$query[$i] =~ /^[\d\.]+[^\d\.]+$/
				and $query[ $i - 1 ] =~ /^\%$/
				and (  $query[ $i - 2 ] =~ /$math_operators/
					or $query[ $i - 2 ] =~ /^(?:,|\(|\[)$/
					or $self->_is_keyword( $query[ $i - 2 ] )
					or $self->_is_type( $query[ $i - 2 ] ) )
			  )
			{
				$query[$i] = $query[ $i - 1 ] . $query[$i];
				$query[ $i - 1 ] = '';
			}
		}
	}
	@query = grep( !/^$/, @query );

	#print STDERR "DEBUG KWDLIST: ", join(' | ', @query), "\n";

	return @query if (wantarray);

	$self->{'_tokens'} = \@query;
}

sub _pop_level {
	my ( $self, $token, $last_token ) = @_;

	if ($DEBUG) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_POP: line: $line => last=", ( $last_token || '' ),
		  ", token=$token\n";
	}

	return 0 if ( $#{ $self->{'_level_stack'} } == -1 );

	return pop( @{ $self->{'_level_stack'} } ) || 0;

}

sub _reset_level {
	my ( $self, $token, $last_token ) = @_;

	if ($DEBUG) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_RESET: line: $line => last=",
		  ( $last_token || '' ), ", token=$token\n";
	}

	@{ $self->{'_level_stack'} } = ();
	$self->{'_level'} = 0;
	$self->{'break'}  = ' ' unless ( $self->{'spaces'} != 0 );
}

sub _set_level {
	my ( $self, $position, $token, $last_token ) = @_;

	my ( $package, $filename, $line ) = caller;

	return 0 if ( not defined $position );

	if ($DEBUG) {
		print STDERR "DEBUG_SET: line: $line => position=$position, last=",
		  ( $last_token || '' ), ", token=$token\n";
	}

	$self->{'_level'} = ( $position >= 0 ) ? $position : 0;
}

sub _push_level {
	my ( $self, $position, $token, $last_token ) = @_;

	if ($DEBUG) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_PUSH: line: $line => position=$position, last=",
		  ( $last_token || '' ), ", token=$token\n";
	}

	push( @{ $self->{'_level_stack'} },
		( ( $position >= 0 ) ? $position : 0 ) );
}

sub _set_last {
	my ( $self, $token, $last_token ) = @_;

	if ($DEBUG) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_LAST: line: $line => last=", ( $last_token || '' ),
		  ", token=$token\n";
	}

	return $token;
}

=head2 beautify

Beautify SQL.

After calling this function, $object->content() will contain nicely indented result.

Code lifted from SQL::Beautify

=cut

sub beautify {
	my $self = shift;

	# Use to store the token position in the array
	my $pos = 0;

	# Main variables used to store differents state
	$self->content('');
	$self->{'_level'}                      = 0;
	$self->{'_level_stack'}                = [];
	$self->{'_level_parenthesis'}          = [];
	$self->{'_new_line'}                   = 1;
	$self->{'_current_sql_stmt'}           = '';
	$self->{'_current_full_sql_stmt'}      = '';
	$self->{'_is_meta_command'}            = 0;
	$self->{'_fct_code_delimiter'}         = '';
	$self->{'_language_sql'}               = 0;
	$self->{'_first_when_in_case'}         = 0;
	$self->{'_is_in_if'}                   = 0;
	$self->{'_is_in_set'}                  = 0;
	$self->{'_is_in_conversion'}           = 0;
	$self->{'_is_in_case'}                 = ();
	$self->{'_is_in_where'}                = 0;
	$self->{'_is_in_from'}                 = 0;
	$self->{'_is_in_join'}                 = 0;
	$self->{'_is_in_create'}               = 0;
	$self->{'_is_in_create_schema'}        = 0;
	$self->{'_is_in_rule'}                 = 0;
	$self->{'_is_in_create_function'}      = 0;
	$self->{'_is_in_drop_function'}        = 0;
	$self->{'_is_in_alter'}                = 0;
	$self->{'_is_in_trigger'}              = 0;
	$self->{'_is_in_publication'}          = 0;
	$self->{'_is_in_call'}                 = 0;
	$self->{'_is_in_type'}                 = 0;
	$self->{'_is_in_domain'}               = 0;
	$self->{'_is_in_declare'}              = 0;
	$self->{'_is_in_block'}                = -1;
	$self->{'_is_in_work'}                 = 0;
	$self->{'_is_in_function'}             = 0;
	$self->{'_current_function'}           = '';
	$self->{'_is_in_statistics'}           = 0;
	$self->{'_is_in_cast'}                 = 0;
	$self->{'_is_in_procedure'}            = 0;
	$self->{'_is_in_index'}                = 0;
	$self->{'_is_in_with'}                 = 0;
	$self->{'_is_in_explain'}              = 0;
	$self->{'_is_in_overlaps'}             = 0;
	$self->{'_parenthesis_level'}          = 0;
	$self->{'_parenthesis_function_level'} = 0;
	$self->{'_has_order_by'}               = 0;
	$self->{'_is_in_order_by'}             = 0;
	$self->{'_has_over_in_join'}           = 0;
	$self->{'_insert_values'}              = 0;
	$self->{'_is_in_constraint'}           = 0;
	$self->{'_is_in_distinct'}             = 0;
	$self->{'_is_in_array'}                = 0;
	$self->{'_is_in_filter'}               = 0;
	$self->{'_parenthesis_filter_level'}   = 0;
	$self->{'_is_in_within'}               = 0;
	$self->{'_is_in_grouping'}             = 0;
	$self->{'_is_in_partition'}            = 0;
	$self->{'_is_in_over'}                 = 0;
	$self->{'_is_in_policy'}               = 0;
	$self->{'_is_in_truncate'}             = 0;
	$self->{'_is_in_using'}                = 0;
	$self->{'_and_level'}                  = 0;
	$self->{'_col_count'}                  = 0;
	$self->{'_is_in_drop'}                 = 0;
	$self->{'_is_in_operator'}             = 0;
	$self->{'_is_in_exception'}            = 0;
	$self->{'_is_in_sub_query'}            = 0;
	$self->{'_is_in_fetch'}                = 0;
	$self->{'_is_in_aggregate'}            = 0;
	$self->{'_is_in_value'}                = 0;
	$self->{'_parenthesis_level_value'}    = 0;
	$self->{'_parenthesis_with_level'}     = 0;
	$self->{'_is_in_returns_table'}        = 0;
	$self->{'_has_limit'}                  = 0;
	$self->{'_not_a_type'}                 = 0;
	$self->{'stmt_number'}                 = 1;
	$self->{'_is_subquery'}                = 0;
	$self->{'_mysql_delimiter'}            = '';
	$self->{'_is_in_generated'}            = 0;
	$self->{'_is_in_between'}              = 0;
	$self->{'_is_in_materialized'}         = 0;
	$self->{'_is_closing_function'}        = 0;

	@{ $self->{'_begin_level'} } = ();

	my $last = '';
	$self->tokenize_sql();

	$self->{'content'} .= "-- Statement # $self->{ 'stmt_number' }\n"
	  if ( $self->{'numbering'} and $#{ $self->{'_tokens'} } > 0 );
	while ( defined( my $token = $self->_token ) ) {
		my $rule = $self->_get_rule($token);
		$self->{'_is_closing_function'} = 0;

		if (    $self->{'keep_newline'}
			and $self->{'_is_in_block'} >= 0
			and $token =~ /^[\r\n]+$/s
			and defined $last
			and $last eq ';' )
		{
			$self->_add_token( $token, $last );
			next;
		}

		# Replace concat operator found in some SGBD into || for normalization
		if (   lc($token) eq 'concat'
			&& defined $self->_next_token()
			&& $self->_next_token ne '(' )
		{
			$token = '||';
		}

		# Case where a keyword is used as a column name.
		if (    $self->{'_is_in_create'} > 1
			and $self->_is_keyword( $token, $self->_next_token(), $last )
			and defined $self->_next_token
			and $self->_is_type( $self->_next_token ) )
		{
			$self->_add_token( $token, $last );
			$last = $self->_set_last( $token, $last );
			next;

		}

		# COPY block
		if ( $token =~ /^COPY\s+[^\s]+\s+\(/i ) {
			$self->_new_line( $token, $last );
			$self->_add_token( $token, $last );
			$self->_new_line( $token, $last );
			$self->{'content'} .= "\n";
			$last = $self->_set_last( $token, $last );
			next;
		}

		if ( uc($token) eq 'BETWEEN' ) {
			$self->{'_is_in_between'} = 1;
			$self->_add_token( $token, $last );
			$last = $self->_set_last( $token, $last );
			next;
		}

# mark when we are processing a materialized view to avoid formating issue with parameters
		if (    uc($token) eq 'MATERIALIZED'
			and uc( $self->_next_token ) eq 'VIEW' )
		{
			$self->{'_is_in_materialized'} = 1;
		}

		####
		# Find if the current keyword is a known function name
		####
		if ( defined $last && $last && defined $self->_next_token
			and $self->_next_token eq '(' )
		{
			my $word = lc($token);
			$word =~ s/^[^\.]+\.//;
			$word =~ s/^:://;
			if ( uc($last) eq 'FUNCTION' and $token =~ /^\d+$/ ) {
				$self->{'_is_in_function'}++;
			}
			elsif ( $word && exists $self->{'dict'}->{'pg_functions'}{$word} ) {
				$self->{'_current_function'} = $word;
				$self->{'_is_in_function'}++
				  if ( $self->{'_is_in_create'} != 1 or $token =~ /^CAST$/i );

				# Try to detect user defined functions
			}
			elsif (
					$last ne '*'
				and !$self->_is_keyword( $token, $self->_next_token(), $last )
				and ( exists $self->{'dict'}->{'symbols'}{$last}
					or $last =~ /^\d+$/ )
			  )
			{
				$self->{'_is_in_function'}++;
			}
			elsif ( uc($token) eq 'IN'
				and $self->{'_tokens'}[1] !~ /^(SELECT|WITH|VALUES)$/i )
			{
				$self->{'_is_in_function'}++;

				# try to detect if this is a user function
			}
			elsif (
					!$self->{'_is_in_function'}
				and !$self->{'_is_in_create'}
				and !$self->_is_comment($token)
				and length($token) > 2    # lazy exclusion of operators/comma
				and $last !~ /^(?:AS|RECURSIVE|WITH|OPERATOR|INTO|TYPE|VIEW)/i
				and !$self->_is_keyword( $token, $self->_next_token(), $last )
			  )
			{
				$self->{'_is_in_function'}++;
			}
		}

		####
		# Set open parenthesis position to know if we
		# are in subqueries or function parameters
		####
		if ( $token eq ')' ) {
			$self->{'_parenthesis_filter_level'}--
			  if ( $self->{'_parenthesis_filter_level'} );
			$self->{'_parenthesis_with_level'}--
			  if ( $self->{'_parenthesis_with_level'} );
			$self->{'_is_in_filter'} = 0
			  if ( !$self->{'_parenthesis_filter_level'} );

			if ( !$self->{'_is_in_function'} ) {
				$self->{'_parenthesis_level'}--
				  if ( $self->{'_parenthesis_level'} > 0 );
			}
			else {
				if ( $self->{'_parenthesis_function_level'} > 0 ) {
					$self->{'_is_closing_function'} = 1;
					$self->{'_parenthesis_function_level'}--;
				}
				if ( !$self->{'_parenthesis_function_level'} ) {
					$self->_set_level(
						pop( @{ $self->{'_level_parenthesis_function'} } ) || 0,
						$token, $last
					);
					$self->_over( $token, $last )
					  if ( !$self->{'_is_in_create'}
						&& !$self->{'_is_in_operator'}
						&& !$self->{'_is_in_alter'}
						and uc( $self->_next_token( $token, $last ) || '' ) ne
						'LOOP' );
				}
			}
			$self->{'_is_in_function'} = 0
			  if ( !$self->{'_parenthesis_function_level'} );
			$self->{'_is_in_cast'} = 0
			  if (
				(
					not defined $self->_next_token
					or $self->_next_token !~ /^(WITH|WITHOUT)$/i
				)
				and (  !$self->{'_parenthesis_level'}
					or !$self->{'_parenthesis_function_level'} )
			  );

			if (
				   !$self->{'_parenthesis_level'}
				and $self->{'_is_in_sub_query'}
				and defined $self->_next_token
				and ( !$self->{'_is_in_order_by'}
					or $self->_next_token =~ /^(FROM|GROUP)$/i )
			  )
			{
				$self->{'_is_in_sub_query'}--;
				$self->_back( $token, $last );
			}
			if ( $self->{'_is_in_value'} ) {
				$self->{'_parenthesis_level_value'}--
				  if ( $self->{'_parenthesis_level_value'} );
			}
		}
		elsif ( $token eq '(' ) {
			$self->{'_parenthesis_filter_level'}++
			  if ( $self->{'_is_in_filter'} );
			$self->{'_parenthesis_with_level'}++ if ( $self->{'_is_in_with'} );
			if ( $self->{'_is_in_function'} ) {
				$self->{'_parenthesis_function_level'}++;
				push(
					@{ $self->{'_level_parenthesis_function'} },
					$self->{'_level'}
				) if ( $self->{'_parenthesis_function_level'} == 1 );
			}
			else {
				if ( !$self->{'_parenthesis_level'} && $self->{'_is_in_from'} )
				{
					push(
						@{ $self->{'_level_parenthesis'} },
						$self->{'_level'}
					);
				}
				$self->{'_parenthesis_level'}++;
				if ( $self->{'_is_in_value'} ) {
					$self->{'_parenthesis_level_value'}++;
				}
			}

			if ( defined $self->_next_token
				and $self->_next_token =~ /^(SELECT|WITH)$/i )
			{
				$self->{'_is_in_sub_query'}++
				  if ( defined $last and uc($last) ne 'AS' );
			}
		}

		####
		# Control case where we have to add a newline, go back and
		# reset indentation after the last ) in the WITH statement
		####
		if (
			$token =~ /^WITH$/i
			and (
				!defined $last
				or
				( $last ne ')' and $self->_next_token !~ /^(TIME|FUNCTION)/i )
			)
		  )
		{
			if (    !$self->{'_is_in_partition'}
				and !$self->{'_is_in_publication'}
				and !$self->{'_is_in_policy'} )
			{
				$self->{'_is_in_with'} = 1
				  if (  !$self->{'_is_in_using'}
					and !$self->{'_is_in_materialized'}
					and uc( $self->_next_token ) ne 'ORDINALITY'
					and uc($last) ne 'START' );
				$self->{'no_break'} = 1
				  if ( uc( $self->_next_token ) eq 'ORDINALITY' );
			}
			$self->{'_is_in_materialized'} = 0;
		}
		elsif ( $token =~ /^WITH$/i
			&& uc( $self->_next_token ) eq 'ORDINALITY' )
		{
			$self->{'no_break'} = 1;
		}
		elsif ($token =~ /^(AS|IS)$/i
			&& defined $self->_next_token
			&& $self->_next_token =~ /^(NOT|\()$/ )
		{
			$self->{'_is_in_materialized'} = 0;
			$self->{'_is_in_with'}++ if ( $self->{'_is_in_with'} == 1 );
		}
		elsif ($self->{'_is_in_create'}
			&& $token =~ /^AS$/i
			&& defined $self->_next_token
			&& uc( $self->_next_token ) eq 'SELECT' )
		{
			$self->{'_is_in_materialized'} = 0;
			$self->{'_is_in_create'}       = 0;
		}
		elsif ( $token eq '[' ) {
			$self->{'_is_in_array'}++;
		}
		elsif ( $token eq ']' ) {
			$self->{'_is_in_array'}-- if ( $self->{'_is_in_array'} );
		}
		elsif ( $token eq ')' ) {
			$self->{'_has_order_by'} = 0;
			if ( $self->{'_is_in_distinct'} ) {
				$self->_add_token($token);
				$self->_new_line( $token, $last );
				$self->{'_is_in_distinct'} = 0;
				$last = $self->_set_last( $token, $last );
				next;
			}
			$self->{'_is_in_generated'} = 0
			  if (  $self->{'_is_in_create'}
				and $self->{'_parenthesis_level'} == 1 );
			$self->{'_is_in_using'} = 0
			  if (  $self->{'_is_in_using'}
				and !$self->{'_parenthesis_level'}
				and !$self->{'_is_in_policy'} );
			if (
					defined $self->_next_token
				and $self->_next_token !~ /^(AS|WITH|,)$/i
				and (
					!$self->_is_comment( $self->_next_token )
					or (    $#{ $self->{'_tokens'} } >= 1
						and $self->{'_tokens'}[1] ne ',' )
				)
				and !$self->{'_parenthesis_with_level'}
				and $self->{'_is_in_with'}
			  )
			{
				$self->{'_is_in_with'} = 0;
				$self->{'_is_in_from'} = 0;
			}

			if (    $self->{'_is_in_create'} > 1
				and defined $self->_next_token
				and uc( $self->_next_token ) eq 'AS'
				and !$self->{'_is_in_with'} )
			{
				$self->{'_is_in_materialized'} = 0;
				$self->_new_line( $token, $last )
				  if ( $last ne '(' and !$self->{'_is_in_create'} );
				if ( $self->{'_is_in_returns_table'}
					and !$self->{'_parenthesis_level'} )
				{
					$self->{'_is_in_returns_table'} = 0;
					$self->_new_line( $token, $last );
					$self->_back( $token, $last );
					$self->_add_token( $token, $last );
					$last = $self->_set_last( $token, $last );
					next;
				}
				else {
					$self->_over( $token, $last )
					  if ( $self->{'_is_in_procedure'} );
				}
			}
			if (   ( $self->{'_is_in_with'} > 1 || $self->{'_is_in_operator'} )
				&& !$self->{'_parenthesis_level'}
				&& !$self->{'_parenthesis_with_level'}
				&& !$self->{'_is_in_alter'}
				&& !$self->{'_is_in_policy'} )
			{
				$self->_new_line( $token, $last )
				  if (
					!$self->{'_is_in_operator'}
					|| ( !$self->{'_is_in_drop'} and $self->_next_token eq ';' )
				  );

				if ( !$self->{'_is_in_operator'} ) {
					$self->_set_level( $self->_pop_level( $token, $last ),
						$token, $last );
					$self->_back( $token, $last );
				}
				$self->_add_token($token);
				if ( !$self->{'_is_in_operator'} ) {
					$self->_reset_level( $token, $last );
				}
				if ( $self->{'_is_in_with'} ) {
					if ( defined $self->_next_token
						&& $self->_next_token eq ',' )
					{
						$self->{'_is_in_with'} = 1;
					}
					else {
						$self->{'_is_in_with'} = 0;
					}
				}
				$last = $self->_set_last( $token, $last );
				next;
			}
		}
		elsif ( defined $self->_next_token && $self->_next_token eq '(' ) {
			$self->{'_is_in_filter'}   = 1 if ( uc($token) eq 'FILTER' );
			$self->{'_is_in_grouping'} = 1
			  if ( $token =~ /^(GROUPING|ROLLUP)$/i );
		}
		elsif ( uc($token) eq 'PASSING'
			and defined $self->_next_token && uc( $self->_next_token ) eq 'BY' )
		{
			$self->{'_has_order_by'} = 1;
		}

		# Explain need indentation in option list
		if ( uc($token) eq 'EXPLAIN' ) {
			$self->{'_is_in_explain'} = 1;
		}
		elsif ( uc($token) eq 'OVERLAPS' ) {
			$self->{'_is_in_overlaps'} = 1;
		}

		if ($self->{'_current_sql_stmt'} eq 'DO UPDATE' && $token =~ /^(WHERE|SELECT)$/i) {
			$self->{'_current_sql_stmt'} = 'INSERT';
			$self->{'_is_in_set'} = 0;
		}

		####
		# Set the current kind of statement parsed
		####
		if ( $token =~
/^(FUNCTION|PROCEDURE|SEQUENCE|INSERT|DELETE|UPDATE|SELECT|RAISE|ALTER|GRANT|REVOKE|COMMENT|DROP|RULE|COMMENT|LOCK)$/i
		  )
		{
			my $k_stmt = uc($1);
			$self->{'_is_in_explain'} = 0;
			$self->{'_is_in_where'}   = 0;
			$self->{'_current_full_sql_stmt'} = '';

	# Set current statement with taking care to exclude of SELECT ... FOR UPDATE
	# statement and ON CONFLICT DO UPDATE.
			if (
				$k_stmt ne 'UPDATE'
				or (    defined $self->_next_token
					and $self->_next_token ne ';'
					and $self->_next_token ne ')'
					and ( not defined $last or $last !~ /^(DO|SHARE)$/i ) )
			  )
			{
				if ( $k_stmt !~ /^(UPDATE|DELETE)$/i
					|| !$self->{'_is_in_create'} )
				{
					if (    $self->{'_current_sql_stmt'} !~ /^(GRANT|REVOKE)$/i
						and !$self->{'_is_in_trigger'}
						and !$self->{'_is_in_operator'}
						and !$self->{'_is_in_alter'} )
					{
						if (   $k_stmt ne 'COMMENT'
							or $self->_next_token =~ /^(ON|IS)$/i )
						{
							$self->{'_current_sql_stmt'} = $k_stmt
							  if ( not defined $last or uc($last) ne 'WITH' );
						}
					}
				}
				if ( $self->{'_current_sql_stmt'} =~ /^(INSERT|DELETE|UPDATE|SELECT)$/i ) {
					$self->{'_current_full_sql_stmt'} = "$self->{'_current_sql_stmt'} ";
					for (my $i = 0; $i <= $#{ $self->{'_tokens'} }; $i++) {
						last if ($self->{'_tokens'}[$i] eq ';');
						$self->{'_current_full_sql_stmt'} .= " " . $self->{'_tokens'}[$i];
					}
					$self->{'_current_full_sql_stmt'} .= ";";
				}
			}
		}

		####
		# Mark that we are in CREATE statement that need newline
		# after a comma in the parameter, declare or column lists.
		####
		if (    $token =~ /^(FUNCTION|PROCEDURE)$/i
			and $self->{'_is_in_create'}
			and !$self->{'_is_in_trigger'} )
		{
			$self->{'_is_in_create_function'} = 1;
		}
		elsif ( $token =~ /^(FUNCTION|PROCEDURE)$/i
			and defined $last
			and uc($last) eq 'DROP' )
		{
			$self->{'_is_in_drop_function'} = 1;
		}
		elsif ( $token =~ /^(FUNCTION|PROCEDURE)$/i
			and $self->{'_is_in_trigger'} )
		{
			$self->{'_is_in_index'} = 1;
		}
		if ( $token =~ /^CREATE$/i
			and defined $self->_next_token
			&& $self->_next_token !~
/^(EVENT|UNIQUE|INDEX|EXTENSION|TYPE|PUBLICATION|OPERATOR|RULE|CONVERSION|DOMAIN)$/i
		  )
		{
			if ( $self->_next_token =~ /^SCHEMA$/i ) {
				$self->{'_is_in_create_schema'} = 1;
			}
			elsif ( $self->{'_is_in_create_schema'} ) {

				# we are certainly in a create schema statement
				$self->_new_line( $token, $last );
				$self->{'_level'} = 1;
				$self->{'_is_in_create_schema'}++;
			}
			$self->{'_is_in_create'} = 1;
		}
		elsif ( $token =~ /^CREATE$/i
			and defined $self->_next_token && $self->_next_token =~ /^RULE$/i )
		{
			$self->{'_is_in_rule'} = 1;
		}
		elsif ( $token =~ /^CREATE$/i
			and defined $self->_next_token && $self->_next_token =~ /^EVENT$/i )
		{
			$self->{'_is_in_trigger'} = 1;
		}
		elsif ( $token =~ /^CREATE$/i
			and defined $self->_next_token && $self->_next_token =~ /^TYPE$/i )
		{
			$self->{'_is_in_type'} = 1;
		}
		elsif ( $token =~ /^CREATE$/i
			and defined $self->_next_token
			&& $self->_next_token =~ /^DOMAIN$/i )
		{
			$self->{'_is_in_domain'} = 1;
		}
		elsif ( $token =~ /^CREATE$/i
			and defined $self->_next_token
			&& $self->_next_token =~ /^PUBLICATION$/i )
		{
			$self->{'_is_in_publication'} = 1;
		}
		elsif ( $token =~ /^CREATE$/i
			and defined $self->_next_token
			&& $self->_next_token =~ /^CONVERSION$/i )
		{
			$self->{'_is_in_conversion'} = 1;
		}
		elsif ( $token =~ /^(CREATE|DROP)$/i
			and defined $self->_next_token
			&& $self->_next_token =~ /^OPERATOR$/i )
		{
			$self->{'_is_in_operator'} = 1;
			$self->{'_is_in_drop'}     = 1 if ( $token =~ /^DROP$/i );
		}
		elsif ( $token =~ /^ALTER$/i ) {
			$self->{'_is_in_alter'}++;
		}
		elsif ( $token =~ /^DROP$/i ) {
			$self->{'_is_in_drop'} = 1;
		}
		elsif ( $token =~ /^VIEW$/i and $self->{'_is_in_create'} ) {
			$self->{'_is_in_index'}  = 1;
			$self->{'_is_in_create'} = 0;
		}
		elsif ( $token =~ /^STATISTICS$/i and $self->{'_is_in_create'} ) {
			$self->{'_is_in_statistics'} = 1;
			$self->{'_is_in_create'}     = 0;
		}
		elsif ( $token =~ /^CAST$/i
			and defined $self->_next_token
			and $self->_next_token eq '(' )
		{
			$self->{'_is_in_cast'} = 1;
		}
		elsif ( $token =~ /^AGGREGATE$/i and $self->{'_is_in_create'} ) {
			$self->{'_is_in_aggregate'} = 1;
			$self->{'_has_order_by'}    = 1;
		}
		elsif ( $token =~ /^EVENT$/i
			and defined $self->_next_token
			&& $self->_next_token =~ /^TRIGGER$/i )
		{
			$self->_over( $token, $last );
			$self->{'_is_in_index'} = 1;
		}
		elsif ( $token =~ /^CREATE$/i
			and defined $self->_next_token
			&& $self->_next_token =~ /^INDEX|UNIQUE/i )
		{
			if ( $self->{'_is_in_create_schema'} ) {
				$self->_new_line( $token, $last );
				$self->{'_level'} = 1;
				$self->{'_is_in_create_schema'}++;
			}
		}

		if (    $self->{'_is_in_using'}
			and defined $self->_next_token
			and $self->_next_token =~ /^(OPERATOR|AS)$/i )
		{
			$self->{'_is_in_using'} = 0;
		}

		if ( $token =~ /^ALTER$/i and $self->{'_is_in_alter'} > 1 ) {
			$self->_new_line( $token, $last );
			$self->_over( $token, $last ) if ( $last ne ',' );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			next;
		}

		# Special case for MySQL delimiter
		if (   uc($token) eq 'DELIMITER'
			&& defined $self->_next_token
			&& ( $self->_next_token eq '//' or $self->_next_token eq '$$' ) )
		{
			$self->{'_mysql_delimiter'} = $self->_next_token;
		}
		elsif (uc($token) eq 'DELIMITER'
			&& defined $self->_next_token
			&& $self->_next_token eq ';' )
		{
			$self->{'_mysql_delimiter'} = '';
		}

		# case of the delimiter alone
		if (   $self->{'_mysql_delimiter'}
			&& $token eq $self->{'_mysql_delimiter'} )
		{
			$self->{'content'} =~ s/\n\n$/\n/s;
			$self->_add_token($token);
			$self->_new_line( $token, $last );
			$last = $self->_set_last( ';', $last );
			next;
		}

		####
		# Mark that we are in a CALL statement to remove any new line
		####
		if ( $token =~ /^CALL$/i ) {
			$self->{'_is_in_call'} = 1;
		}

		# Increment operator tag to add newline in alter operator statement
		if ( ( $self->{'_is_in_alter'} or uc($last) eq 'AS' )
			and uc($token) eq 'OPERATOR' )
		{
			$self->_new_line( $token, $last )
			  if ( uc($last) eq 'AS' and uc($token) eq 'OPERATOR' );
			$self->{'_is_in_operator'}++;
		}

		####
		# Mark that we are in index/constraint creation statement to
		# avoid inserting a newline after comma and AND/OR keywords.
		# This also used in SET statement taking care that we are not
		# in update statement. CREATE statement are not subject to this rule
		####
		if (   !$self->{'_is_in_create'}
			and $token =~ /^(INDEX|PRIMARY|CONSTRAINT)$/i )
		{
			$self->{'_is_in_index'} = 1
			  if ( $last =~ /^(ALTER|CREATE|UNIQUE|USING|ADD)$/i );
		}
		elsif ( !$self->{'_is_in_create'} and uc($token) eq 'SET' ) {
			$self->{'_is_in_index'} = 1
			  if ( $self->{'_current_sql_stmt'} ne 'UPDATE' );
		}
		elsif (
			$self->{'_is_in_create'}
			and (
				uc($token) eq 'UNIQUE'
				or ( $token =~ /^(PRIMARY|FOREIGN)$/i
					and uc( $self->_next_token ) eq 'KEY' )
			)
		  )
		{
			$self->{'_is_in_constraint'} = 1;
		}

		# Same as above but for ALTER FUNCTION/PROCEDURE/SEQUENCE or when
		# we are in a CREATE FUNCTION/PROCEDURE statement
		elsif ( $token =~ /^(FUNCTION|PROCEDURE|SEQUENCE)$/i
			and !$self->{'_is_in_trigger'} )
		{
			$self->{'_is_in_index'} = 1
			  if (  uc($last) eq 'ALTER'
				and !$self->{'_is_in_operator'}
				and !$self->{'_is_in_alter'} );
			if (
				$token =~ /^FUNCTION$/i
				&& (   $self->{'_is_in_create'}
					|| $self->{'_current_sql_stmt'} eq 'COMMENT' )
			  )
			{
				$self->{'_is_in_index'} = 1 if ( !$self->{'_is_in_operator'} );
			}
			elsif ( $token =~ /^PROCEDURE$/i && $self->{'_is_in_create'} ) {
				$self->{'_is_in_index'}     = 1;
				$self->{'_is_in_procedure'} = 1;
			}
		}

		# Desactivate index like formatting when RETURN(S) keyword is found
		elsif ( $token =~ /^(RETURN|RETURNS)$/i ) {
			$self->{'_is_in_index'} = 0;
			if (    uc($token) eq 'RETURNS'
				and uc( $self->_next_token() ) eq 'TABLE' )
			{
				$self->{'_is_in_returns_table'} = 1;
			}
		}
		elsif ( $token =~ /^AS$/i ) {
			$self->{'_is_in_materialized'} = 0;
			if (   !$self->{'_is_in_index'}
				and $self->{'_is_in_from'}
				and $last eq ')'
				and uc($token) eq 'AS'
				and $self->_next_token() eq '(' )
			{
				$self->{'_is_in_index'} = 1;
			}
			else {
				$self->{'_is_in_index'} = 0;
			}
			$self->{'_is_in_block'} = 1 if ( $self->{'_is_in_procedure'} );
			$self->{'_is_in_over'}  = 0;
		}

		if ( $token =~ /^(BEGIN|DECLARE)$/i ) {
			$self->{'_is_in_create'}-- if ( $self->{'_is_in_create'} );
			if ( uc($token) eq 'BEGIN' ) {
				push(
					@{ $self->{'_begin_level'} },
					( $#{ $self->{'_begin_level'} } < 0 )
					? 0
					: $self->{'_level'}
				);
			}
		}

		####
		# Mark statements that use string_agg() or group_concat() function
		# as statement that can have an ORDER BY clause inside the call to
		# prevent applying order by formatting.
		####
		if (
			$token =~ /^(string_agg|group_concat|array_agg|percentile_cont)$/i )
		{
			$self->{'_has_order_by'} = 1;
		}
		elsif ( $token =~ /^(?:GENERATED)$/i
			and $self->_next_token =~ /^(ALWAYS|BY)$/i )
		{
			$self->{'_is_in_generated'} = 1;
		}
		elsif ( $token =~ /^(?:TRUNCATE)$/i ) {
			$self->{'no_break'} = 1;
		}
		elsif ( uc($token) eq 'IDENTITY' ) {
			$self->{'_has_order_by'}    = 0;
			$self->{'no_break'}         = 0;
			$self->{'_is_in_generated'} = 0;
		}
		elsif ( $self->{'_has_order_by'}
			and uc($token) eq 'ORDER'
			and $self->_next_token =~ /^BY$/i )
		{
			$self->_add_token( $token, $last );
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif ( $self->{'_has_order_by'} and uc($token) eq 'BY' ) {
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif ( $token =~ /^OVER$/i ) {
			$self->_add_token($token);
			$self->{'_is_in_over'}   = 1;
			$self->{'_has_order_by'} = 1;
			$last                    = $self->_set_last( $token, $last );
			next;
		}

		# Fix case where we don't knwon if we are outside a SQL function
		if (    defined $last
			and uc($last) eq 'AS'
			and defined $self->_next_token
			and $self->_next_token eq ';'
			and $self->{'_is_in_create_function'} )
		{
			$self->{'_is_in_create_function'} = 0;
		}

		####
		# Set function code delimiter, it can be any string found after
		# the AS keyword in function or procedure creation code
		####
# Toogle _fct_code_delimiter to force next token to be stored as the function code delimiter
		if (
			uc($token) eq 'AS'
			and ( !$self->{'_fct_code_delimiter'}
				|| $self->_next_token =~ /CODEPART/ )
			and $self->{'_current_sql_stmt'} =~ /^(FUNCTION|PROCEDURE)$/i
		  )
		{
			if (    $self->{'_is_in_create'}
				and !$self->{'_is_in_with'}
				and !$self->{'_is_in_cast'}
				and $self->_next_token !~ /^(IMPLICIT|ASSIGNMENT)$/i )
			{
				$self->_new_line( $token, $last );
				$self->_add_token($token);
				$self->{'_is_in_set'} = 0;
				$self->_reset_level( $token, $last )
				  if ( $self->_next_token !~ /CODEPARTB/ );
			}
			else {
				$self->_add_token($token);
			}
			if (   $self->_next_token !~ /(CODEPART|IMPLICIT|ASSIGNMENT)/
				|| $self->_next_token =~ /^'/ )
			{
				if ( !$self->{'_is_in_cast'} and $self->{'_is_in_create'} ) {

					# extract potential code joined with the code separator
					if ( $self->{'_tokens'}->[0] =~ s/^'(.)/$1/ ) {
						$self->{'_tokens'}->[0] =~ s/[;\s]*'$//;
						my @tmp_arr =
						  $self->tokenize_sql( $self->{'_tokens'}->[0] );
						push( @tmp_arr, ";", "'" );
						shift( @{ $self->{'_tokens'} } );
						unshift( @{ $self->{'_tokens'} }, "'", @tmp_arr );
					}
					$self->{'_fct_code_delimiter'} = '1';
				}
			}
			$self->{'_is_in_create'} = 0;
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif ( $token =~ /^(INSTEAD|ALSO)$/i
			and defined $last
			and uc($last) eq 'DO' )
		{
			$self->_add_token($token);
			$self->_new_line( $token, $last );
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif ( $token =~ /^DO$/i
			and defined $self->_next_token
			and $self->_next_token =~ /^(INSTEAD|ALSO|UPDATE|NOTHING)$/i )
		{
			$self->_new_line( $token, $last );
			$self->_over( $token, $last );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif ( $token =~ /^DO$/i
			and !$self->{'_fct_code_delimiter'}
			and $self->_next_token =~ /^\$[^\s]*/ )
		{
			@{ $self->{'_begin_level'} } = ();
			$self->{'_fct_code_delimiter'}    = '1';
			$self->{'_is_in_create_function'} = 1;
			$self->_new_line( $token, $last )
			  if ( $self->{'content'} !~ /\n$/s );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			$self->{_is_in_procedure} = 1;
			next;
		}

		# Store function code delimiter
		if ( $self->{'_fct_code_delimiter'} eq '1' ) {
			if ( $self->_next_token =~ /CODEPART/ ) {
				$self->{'_fct_code_delimiter'} = '0';
			}
			elsif ( $token =~ /^'.*'$/ ) {
				$self->{'_fct_code_delimiter'} = "'";
			}
			else {
				$self->{'_fct_code_delimiter'} = $token;
			}
			$self->_add_token($token);
			if (  !$self->{'_is_in_create_function'}
				or $self->_next_token ne ','
				or $self->{'_tokens'}[1] !~ /KEYWCONST/ )
			{
				$self->_new_line( $token, $last );
			}
			if ( defined $self->_next_token
				and $self->_next_token_skip_comment !~ /^(DECLARE|BEGIN)$/i )
			{
				$self->_over( $token, $last );
				$self->{'_language_sql'} = 1;
			}

			if ( $self->{'_fct_code_delimiter'} eq "'" ) {
				$self->{'_is_in_block'}     = -1;
				$self->{'_is_in_exception'} = 0;
				$self->_reset_level( $token, $last )
				  if ( $self->_next_token eq ';' );
				$self->{'_fct_code_delimiter'}    = '';
				$self->{'_current_sql_stmt'}      = '';
				$self->{'_is_in_procedure'}       = 0;
				$self->{'_is_in_function'}        = 0;
				$self->{'_is_in_create_function'} = 0;
				$self->{'_language_sql'}          = 0;
			}
			$last = $self->_set_last( $token, $last );
			next;
		}

# With SQL language the code delimiter can be include with the keyword, try to detect and fix it
		if (    $self->{'_fct_code_delimiter'}
			and $token =~ s/(.)\Q$self->{ '_fct_code_delimiter' }\E$/$1/ )
		{
			unshift( @{ $self->{'_tokens'} }, $self->{'_fct_code_delimiter'} );
		}

   # Desactivate the block mode when code delimiter is found for the second time
		if (   $self->{'_fct_code_delimiter'}
			&& $token eq $self->{'_fct_code_delimiter'} )
		{
			$self->{'_is_in_block'}           = -1;
			$self->{'_is_in_exception'}       = 0;
			$self->{'_is_in_create_function'} = 0;
			$self->_reset_level( $token, $last );
			$self->{'_fct_code_delimiter'} = '';
			$self->{'_current_sql_stmt'}   = '';
			$self->{'_language_sql'}       = 0;
			$self->_new_line( $token, $last );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			next;
		}

		####
		# Mark when we are parsing a DECLARE or a BLOCK section. When
		# entering a BLOCK section store the current indentation level
		####
		if ( uc($token) eq 'DECLARE' and $self->{'_is_in_create_function'} ) {
			$self->{'_is_in_block'}     = -1;
			$self->{'_is_in_exception'} = 0;
			$self->{'_is_in_declare'}   = 1;
			$self->_reset_level( $token, $last );
			$self->_new_line( $token, $last );
			$self->_add_token($token);
			$self->_new_line( $token, $last );
			$self->_over( $token, $last );
			$last = $self->_set_last( $token, $last );
			$self->{'_is_in_create_function'} = 0;
			next;
		}
		elsif ( uc($token) eq 'ATOMIC' ) {
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			$self->_new_line( $token, $last );
			$self->_over( $token, $last );
			$self->{'_is_in_block'}++;

			# Store current indent position to print END at the right level
			$self->_push_level( $self->{'_level'}, $token, $last );
			next;
		}
		elsif ( uc($token) eq 'BEGIN' ) {
			$self->{'_is_in_declare'} = 0;
			if ( $self->{'_is_in_block'} == -1 ) {
				$self->_reset_level( $token, $last );
			}
			$self->_new_line( $token, $last );
			$self->_add_token($token);
			if ( defined $self->_next_token
				&& $self->_next_token !~
				/^(WORK|TRANSACTION|ISOLATION|ATOMIC|;)$/i )
			{
				$self->_new_line( $token, $last );
				$self->_over( $token, $last );
				$self->{'_is_in_block'}++;

				# Store current indent position to print END at the right level
				$self->_push_level( $self->{'_level'}, $token, $last );
			}
			$self->{'_is_in_work'}++
			  if ( !$self->{'no_grouping'}
				and defined $self->_next_token
				&& $self->_next_token =~
				/^(WORK|TRANSACTION|ISOLATION|ATOMIC|;)$/i );
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif ( $token =~ /^(COMMIT|ROLLBACK)$/i
			and ( not defined $last or uc($last) ne 'ON' )
			and !$self->{'_is_in_procedure'} )
		{
			$self->{'_is_in_work'}            = 0;
			$self->{'_is_in_declare'}         = 0;
			$self->{'_is_in_create_function'} = 0;
			$self->_new_line( $token, $last );
			$self->_set_level( $self->_pop_level( $token, $last ),
				$token, $last );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			@{ $self->{'_begin_level'} } = ();
			next;
		}
		elsif ( $token =~ /^(COMMIT|ROLLBACK)$/i
			and defined $self->_next_token
			and $self->_next_token eq ';'
			and $self->{'_is_in_procedure'} )
		{
			$self->_new_line( $token, $last );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			@{ $self->{'_begin_level'} } = ();
			next;
		}
		elsif ( $token =~ /^FETCH$/i and defined $last and $last eq ';' ) {
			$self->_new_line( $token, $last );
			$self->_back( $token, $last ) if ( $self->{'_is_in_block'} == -1 );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			$self->{'_is_in_fetch'} = 1;
			next;
		}

		####
		# Special case where we want to add a newline into ) AS (
		####
		if ( uc($token) eq 'AS' and $last eq ')' and $self->_next_token eq '(' )
		{
			$self->_new_line( $token, $last );
		}

		# and before RETURNS with increasing indent level
		elsif ( uc($token) eq 'RETURNS' ) {
			$self->_new_line( $token, $last );
			$self->_over( $token, $last )
			  if ( uc( $self->_next_token ) ne 'NULL' );
		}

		# and before WINDOW
		elsif ( uc($token) eq 'WINDOW' ) {
			$self->_new_line( $token, $last );
			$self->_set_level( $self->_pop_level( $token, $last ),
				$token, $last );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			$self->{'_has_order_by'} = 1;
			next;
		}

# Treated DISTINCT as a modifier of the whole select clause, not only the first column only
		if ( uc($token) eq 'ON' && defined $last && uc($last) eq 'DISTINCT' ) {
			$self->{'_is_in_distinct'} = 1;
			$self->_over( $token, $last );
		}
		elsif (uc($token) eq 'DISTINCT'
			&& defined $last
			&& uc($last) eq 'SELECT'
			&& defined $self->_next_token
			&& $self->_next_token !~ /^ON$/i )
		{
			$self->_add_token($token);
			$self->_new_line( $token, $last ) if ( !$self->{'wrap_after'} );
			$self->_over( $token, $last );
			$last = $self->_set_last( $token, $last );
			next;
		}

		if ($rule) {
			$self->_process_rule( $rule, $token );
		}

		elsif ($token =~ /^(LANGUAGE|SECURITY|COST)$/i
			&& !$self->{'_is_in_alter'}
			&& !$self->{'_is_in_drop'}
			&& $last ne ',' )
		{
			@{ $self->{'_begin_level'} } = ();
			$self->_new_line( $token, $last )
			  if ( uc($token) ne 'SECURITY'
				or ( defined $last and uc($last) ne 'LEVEL' ) );
			$self->_add_token($token);
		}
		elsif ($token =~ /^PARTITION$/i
			&& !$self->{'_is_in_over'}
			&& defined $last
			&& $last ne '(' )
		{
			$self->{'_is_in_partition'} = 1;
			if ( $self->{'_is_in_create'} && defined $last and $last eq ')' ) {
				$self->_new_line( $token, $last );
				$self->_set_level( $self->_pop_level( $token, $last ),
					$token, $last )
				  if ( $self->{'_level'} );
				$self->_add_token($token);
			}
			else {
				$self->_add_token($token);
			}
		}
		elsif ( $token =~ /^POLICY$/i ) {
			$self->{'_is_in_policy'} = 1;
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif ($token =~ /^TRUNCATE$/i
			&& $self->_next_token !~ /^(TABLE|ONLY|,)$/i )
		{
			$self->{'_is_in_truncate'} = 1;
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			my $str_tmp = join( ' ', @{ $self->{'_tokens'} } );
			$str_tmp =~ s/;.*//s;
			if ( $str_tmp =~ / , /s ) {
				$self->_new_line( $token, $last );
				$self->_over( $token, $last );
				$self->{'_is_in_truncate'} = 2;
			}
			next;
		}
		elsif ( $token =~ /^(TABLE|ONLY)$/i && uc($last) eq 'TRUNCATE' ) {
			$self->{'_is_in_truncate'} = 1;
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			my $str_tmp = join( ' ', @{ $self->{'_tokens'} } );
			$str_tmp =~ s/;.*//s;
			if ( $str_tmp =~ / , /s ) {
				$self->_new_line( $token, $last );
				$self->_over( $token, $last );
				$self->{'_is_in_truncate'} = 2;
			}
			next;
		}
		elsif ($token =~ /^(RESTART|CASCADE)$/i
			&& $self->{'_is_in_truncate'} == 2 )
		{
			$self->_new_line( $token, $last );
			$self->_back( $token, $last );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif ( $token =~ /^TRIGGER$/i
			and defined $last
			and $last =~ /^(CREATE|CONSTRAINT|REPLACE)$/i )
		{
			$self->{'_is_in_trigger'} = 1;
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif ( $token =~ /^(BEFORE|AFTER|INSTEAD)$/i
			and $self->{'_is_in_trigger'} )
		{
			$self->_new_line( $token, $last );
			$self->_over( $token, $last );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif (
			$token =~ /^EXECUTE$/i
			and ( $self->{'_is_in_trigger'}
				or ( defined $last and uc($last) eq 'AS' ) )
		  )
		{
			$self->_new_line( $token, $last );
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			next;
		}
		elsif ( $token eq '(' ) {
			if (
				$self->{'_is_in_aggregate'} && defined $self->_next_token
				and (  $self->_is_keyword( $self->_next_token )
					or $self->_is_sql_keyword( $self->_next_token ) )
				and uc( $self->_next_token ) ne 'VARIADIC'
			  )
			{
				$self->{'_is_in_aggregate'} = 0;
				$self->{'_has_order_by'}    = 0;
			}
			$self->{'_is_in_create'}++     if ( $self->{'_is_in_create'} );
			$self->{'_is_in_constraint'}++ if ( $self->{'_is_in_constraint'} );
			# case of insert with multiple values, don't stay single line
			if (uc($last) eq 'VALUES' && $self->{'_current_sql_stmt'} eq 'INSERT' && $self->{'_current_full_sql_stmt'} =~ /\) , \(/) {
				$self->_new_line( $token, $last );
				$self->_over( $token, $last );
			}
			$self->_add_token( $token, $last );
			if ( defined $self->_next_token
				and uc( $self->_next_token ) eq 'SELECT' )
			{
				$self->{'_is_in_cast'} = 0;
				$self->{'_is_subquery'}++;
			}
			if (    defined $self->_next_token
				and $self->_next_token eq ')'
				and !$self->{'_is_in_create'} )
			{
				$last = $self->_set_last( $token, $last );
				next;
			}
			if (   !$self->{'_is_in_index'}
				&& !$self->{'_is_in_publication'}
				&& !$self->{'_is_in_distinct'}
				&& !$self->{'_is_in_filter'}
				&& !$self->{'_is_in_grouping'}
				&& !$self->{'_is_in_partition'}
				&& !$self->{'_is_in_over'}
				&& !$self->{'_is_in_trigger'}
				&& !$self->{'_is_in_policy'}
				&& !$self->{'_is_in_aggregate'}
				&& !$self->{'no_break'}
				&& !$self->{'_is_in_generated'} )
			{
				if (   uc($last) eq 'AS'
					|| $self->{'_is_in_create'} == 2
					|| uc( $self->_next_token ) eq 'CASE' )
				{
					$self->_new_line( $token, $last )
					  if (
						(
							  !$self->{'_is_in_function'}
							or $self->_next_token =~ /^CASE$/i
						)
						and $self->_next_token ne ')'
						and $self->_next_token !~ /^(PARTITION|ORDER)$/i
					  );
				}
				if ( $self->{'_is_in_with'} == 1 or $self->{'_is_in_explain'} )
				{
					$self->_over( $token, $last );
					$self->_new_line( $token, $last )
					  if ( !$self->{'wrap_after'} );
					$last = $self->_set_last( $token, $last )
					  if (!$self->{'_is_in_explain'}
						|| $self->{'wrap_after'} );
					next;
				}
				if (    !$self->{'_is_in_if'}
					and !$self->{'_is_in_alter'}
					and ( !$self->{'_is_in_function'} or $last ne '(' )
					and uc($last) ne 'CHECK' )
				{
					$self->_over( $token, $last )
					  if ( $self->{'_is_in_operator'} <= 2
						&& $self->{'_is_in_create'} <= 2 );
					if (    !$self->{'_is_in_function'}
						and !$self->_is_type( $self->_next_token ) )
					{
						if ( $self->{'_is_in_operator'} == 1 ) {
							$self->_new_line( $token, $last );
							$self->{'_is_in_operator'}++;
						}
						elsif ( $self->{'_is_in_type'} ) {
							$self->_new_line( $token, $last );
						}
					}
					$last = $self->_set_last( $token, $last );
				}
				if ( $self->{'_is_in_type'} == 1 ) {
					$last = $self->_set_last( $token, $last );
					next;
				}
			}

			if (
				   $self->{'format_type'}
				&& $self->{'_current_sql_stmt'} =~ /(FUNCTION|PROCEDURE)/i
				&& $self->{'_is_in_create'} == 2
				&& ( not defined $self->_next_token
					or $self->_next_token ne ')' )
			  )
			{
				$self->_over( $token, $last )
				  if ( $self->{'_is_in_block'} < 0 );
				$self->_new_line( $token, $last );
				next;
			}
		}

		elsif ( $token eq ')' ) {
			if ( defined $self->_next_token ) {
				my $next = quotemeta( $self->_next_token ) || 'SELECT';
				if (
						!$self->{'_parenthesis_level'}
					and defined $self->_next_token
					and $self->_is_keyword( $self->_next_token )
					or ( !grep( /^$next$/, %{ $self->{'dict'}->{'symbols'} } ) )
				  )
				{
					$self->{'_is_in_where'} = 0;
				}
			}
			if (    $self->{'_is_in_constraint'}
				and defined $self->_next_token
				and ( $self->_next_token eq ',' or $self->_next_token eq ')' ) )
			{
				$self->{'_is_in_constraint'} = 0;
			}
			elsif ( $self->{'_is_in_constraint'} ) {
				$self->{'_is_in_constraint'}--;
			}

			# Case of CTE and explain
			if ( $self->{'_is_in_with'} == 1 || $self->{'_is_in_explain'} ) {
				$self->_back( $token, $last );
				$self->_new_line( $token, $last )
				  if ( !$self->{'wrap_after'} && !$self->{'_is_in_overlaps'} );
				$self->_add_token($token);
				$last = $self->_set_last( $token, $last )
				  if ( $token ne ')' or uc( $self->_next_token ) ne 'AS' );
				$self->{'_is_in_explain'} = 0;
				next;
			}
			if (
				(
					   $self->{'format_type'}
					&& $self->{'_current_sql_stmt'} =~ /(FUNCTION|PROCEDURE)/i
					&& $self->{'_is_in_create'} == 2
				)
				|| ( defined $self->_next_token
					and uc( $self->_next_token ) eq 'INHERITS' )
			  )
			{
				$self->_back( $token, $last )
				  if ( $self->{'_is_in_block'} < 0 );
				$self->_new_line( $token, $last )
				  if ( defined $last && $last ne '(' );
			}
			if (
				   $self->{'_is_in_index'}
				|| $self->{'_is_in_alter'}
				|| $self->{'_is_in_partition'}
				|| $self->{'_is_in_policy'}
				|| ( defined $self->_next_token
					and $self->_next_token =~ /^OVER$/i )
			  )
			{
				$self->_add_token('');
				$self->_add_token($token);
				$self->{'_is_in_over'} = 0
				  if ( !$self->{'_parenthesis_level'} );
				$last = $self->_set_last( $token, $last );
				$self->{'_is_in_create'}-- if ( $self->{'_is_in_create'} );
				next;
			}
			if ( defined $self->_next_token && $self->_next_token !~ /FILTER/i )
			{
				my $add_nl = 0;
				$add_nl = 1
				  if (
						$self->{'_is_in_create'} > 1
					and defined $last
					and $last ne '('
					and !$self->{'_is_in_cast'}
					and (
						not defined $self->_next_token
						or $self->_next_token =~
						/^(TABLESPACE|PARTITION|AS|;)$/i
						or ( $self->_next_token =~ /^ON$/i
							and !$self->{'_parenthesis_level'} )
					)
				  );
				$add_nl = 1
				  if (
						$self->{'_is_in_type'} == 1
					and $self->_next_token !~ /^AS$/i
					and ( not defined $self->_next_token
						or $self->_next_token eq ';' )
				  );
				$add_nl = 1
				  if (
						$self->{'_current_sql_stmt'} ne 'INSERT'
					and !$self->{'_is_in_function'}
					and ( defined $self->_next_token
						and $self->_next_token =~ /^(SELECT|WITH)$/i )
					and $self->{'_tokens'}[1] !~ /^(ORDINALITY|FUNCTION)$/i
					and (  $self->{'_is_in_create'}
						or $last ne ')' and $last ne ']' )
					and (  uc( $self->_next_token ) ne 'WITH'
						or uc( $self->{'_tokens'}->[1] ) !~ /TIME|INOUT/i )
				  );

				$self->_new_line( $token, $last ) if ($add_nl);

				if (    !$self->{'_is_in_grouping'}
					and !$self->{'_is_in_trigger'}
					and !$self->{'no_break'}
					and !$self->{'_is_in_generated'}
					and $self->{'_is_in_create'} <= 2
					and $self->_next_token !~ /^LOOP$/i )
				{
					$self->_back( $token, $last );
				}
				$self->{'_is_in_create'}-- if ( $self->{'_is_in_create'} );
			}
			if ( !$self->{'_parenthesis_level'} ) {
				$self->{'_is_in_filter'}    = 0;
				$self->{'_is_in_within'}    = 0;
				$self->{'_is_in_grouping'}  = 0;
				$self->{'_is_in_over'}      = 0;
				$self->{'_has_order_by'}    = 0;
				$self->{'_is_in_policy'}    = 0;
				$self->{'_is_in_aggregate'} = 0;
			}
			$self->_add_token($token);

			# Do not go further if this is the last token
			if ( not defined $self->_next_token ) {
				$last = $self->_set_last( $token, $last );
				next;
			}

			# When closing CTE statement go back again
			if (
				(
					$self->_next_token =~ /^(?:SELECT|INSERT|UPDATE|DELETE)$/i
					and !$self->{'_is_in_policy'}
				)
				or (    $self->{'_is_in_with'}
					and $self->{'_is_subquery'}
					and $self->{'_is_subquery'} % 2 == 0 )
			  )
			{
				$self->_back( $token, $last )
				  if (
						$self->{'_current_sql_stmt'} ne 'INSERT'
					and !$self->{'_is_closing_function'}
					and (
						   !$self->{'_parenthesis_level'}
						or !defined $self->_next_token
						or uc( $self->_next_token ) eq 'AS'
						or (    $#{ $self->{'_tokens'} } >= 1
							and $self->{'_tokens'}->[1] eq ',' )
					)
				  );
			}
			$self->{'_is_subquery'}--
			  if (
					$self->{'_is_subquery'}
				and defined $self->_next_token
				and $#{ $self->{'_tokens'} } >= 1
				and ( uc( $self->_next_token ) eq 'AS'
					or $self->{'_tokens'}->[1] eq ',' )
			  );
			if ( $self->{'_is_in_create'} <= 1 ) {
				my $next_tok = quotemeta( $self->_next_token );
				$self->_new_line( $token, $last )
				  if (
					defined $self->_next_token
					and $self->_next_token !~
/^(?:AS|IS|THEN|INTO|BETWEEN|ON|IN|FILTER|WITHIN|DESC|ASC|WITHOUT|CASCADE)$/i
					and ( $self->_next_token !~ /^(AND|OR)$/i
						or !$self->{'_is_in_if'} )
					and $self->_next_token ne ')'
					and $self->_next_token !~ /^:/
					and $self->_next_token ne ';'
					and $self->_next_token ne ','
					and $self->_next_token ne '||'
					and uc( $self->_next_token ) ne 'CONCAT'
					and (  $self->_is_keyword( $self->_next_token )
						or $self->_is_function( $self->_next_token ) )
					and $self->{'_current_sql_stmt'} !~ /^(GRANT|REVOKE)$/
					and !exists $self->{'dict'}->{'symbols'}{$next_tok}
					and !$self->{'_is_in_over'}
					and !$self->{'_is_in_cast'}
					and !$self->{'_is_in_domain'}
				  );
			}
		}

		elsif ( $token eq ',' ) {
			my $add_newline = 0;

			# Format INSERT with multiple values
			if (    $self->{'_current_sql_stmt'} eq 'INSERT'
				and $last eq ')'
				and $self->_next_token eq '(' )
			{
				$self->_new_line( $token, $last )
				  if ( $self->{'comma'} eq 'start' );
				$self->_add_token($token);
				$self->_new_line( $token, $last )
				  if ( $self->{'comma'} eq 'end' );
				next;
			}
			$self->{'_is_in_constraint'} = 0
			  if ( $self->{'_is_in_constraint'} == 1 );
			$self->{'_col_count'}++ if ( !$self->{'_is_in_function'} );
			if (    ( $self->{'_is_in_over'} or $self->{'_has_order_by'} )
				and !$self->{'_parenthesis_level'}
				and !$self->{'_parenthesis_function_level'} )
			{
				$self->{'_is_in_over'}   = 0;
				$self->{'_has_order_by'} = 0;
				$self->_back( $token, $last );
			}
			$add_newline = 1
			  if (
				   !$self->{'no_break'}
				&& !$self->{'_is_in_generated'}
				&& !$self->{'_is_in_function'}
				&& !$self->{'_is_in_distinct'}
				&& !$self->{'_is_in_array'}
				&& (   $self->{'comma_break'}
					|| $self->{'_current_sql_stmt'} ne 'INSERT' )
				&& ( $self->{'_current_sql_stmt'} ne 'RAISE' )
				&& (   $self->{'_current_sql_stmt'} !~ /^(FUNCTION|PROCEDURE)$/
					|| $self->{'_fct_code_delimiter'} ne '' )
				&& !$self->{'_is_in_where'}
				&& !$self->{'_is_in_drop'}
				&& !$self->{'_is_in_index'}
				&& !$self->{'_is_in_aggregate'}
				&& !$self->{'_is_in_alter'}
				&& !$self->{'_is_in_publication'}
				&& !$self->{'_is_in_call'}
				&& !$self->{'_is_in_policy'}
				&& !$self->{'_is_in_grouping'}
				&& !$self->{'_is_in_partition'}
				&& ( $self->{'_is_in_constraint'} <= 1 )
				&& ( $self->{'_is_in_create'} <= 2 )
				&& $self->{'_is_in_operator'} != 1
				&& !$self->{'_has_order_by'}
				&& $self->{'_current_sql_stmt'} !~ /^(GRANT|REVOKE)$/
				&& (
					$self->_next_token !~ /^('$|\s*\-\-)/is
					or
					( $self->_next_token !~ /^'$/is and $self->{'no_comments'} )
				)
				&& !$self->{'_parenthesis_function_level'}
				&& (  !$self->{'_col_count'}
					or $self->{'_col_count'} > ( $self->{'wrap_after'} - 1 ) )
				|| ( $self->{'_is_in_with'} and !$self->{'wrap_after'} )
			  );
			$self->{'_col_count'} = 0
			  if ( $self->{'_col_count'} > ( $self->{'wrap_after'} - 1 ) );
			$add_newline = 0
			  if ( $self->{'_is_in_using'} and $self->{'_parenthesis_level'} );
			$add_newline = 0 if ( $self->{'no_break'} );

			if ( $self->{'_is_in_with'} >= 1 && !$self->{'_parenthesis_level'} )
			{
				$add_newline = 1 if ( !$self->{'wrap_after'} );
			}
			if (   $self->{'format_type'}
				&& $self->{'_current_sql_stmt'} =~ /(FUNCTION|PROCEDURE)/i
				&& $self->{'_is_in_create'} == 2 )
			{
				$add_newline = 1;
			}
			if ( $self->{'_is_in_alter'} && $self->{'_is_in_operator'} >= 2 ) {
				$add_newline = 1
				  if ( defined $self->_next_token
					and $self->_next_token =~ /^(OPERATOR|FUNCTION)$/i );
			}
			$add_newline = 1 if ( $self->{'_is_in_returns_table'} );
			$self->_new_line( $token, $last )
			  if ( $add_newline and $self->{'comma'} eq 'start' );
			$self->_add_token($token);
			$add_newline = 0
			  if (  $self->{'_is_in_value'}
				and $self->{'_parenthesis_level_value'} );
			$add_newline = 0
			  if ( $self->{'_is_in_function'} or $self->{'_is_in_statistics'} );
			$add_newline = 0
			  if (  defined $self->_next_token
				and !$self->{'no_comments'}
				and $self->_is_comment( $self->_next_token ) );
			$add_newline = 0
			  if (  defined $self->_next_token
				and $self->_next_token =~ /KEYWCONST/
				and $self->{'_tokens'}[1] =~ /^(LANGUAGE|STRICT)$/i );
			$add_newline = 1 if ( $self->{'_is_in_truncate'} );
			  if (
					$add_newline
				and $self->{'comma'} eq 'end'
				and (  $self->{'comma_break'}
					|| ($self->{'_current_sql_stmt'} ne 'INSERT' 
				     		&& ($self->{'_current_sql_stmt'} ne 'DO UPDATE'
							|| !$self->{'_parenthesis_level'})) )
			  )
			  {
				$self->_new_line( $token, $last );
			  }
			}

		elsif ( $token eq ';' or $token =~ /^\\(?:g|crosstabview|watch)/ ) {

# statement separator or executing psql meta command (prefix 'g' includes all its variants)

			$self->_add_token($token);

			next
			  if (  $token eq ';'
				and $#{ $self->{'_is_in_case'} } >= 0
				and uc($last) ne 'CASE' );

			if ( $self->{'_is_in_type'} and $last eq ')' ) {
				$self->_reset_level( $token, $last )
				  if ( $self->{'_is_in_block'} == -1
					&& !$self->{'_parenthesis_level'} );
				$self->{'_is_in_type'}--;
			}
			if ( $self->{'_is_in_rule'} ) {
				$self->_back( $token, $last );
			}
			elsif ( $self->{'_is_in_create'} && $self->{'_is_in_block'} > -1 ) {
				$self->_pop_level( $token, $last );
			}

			# Initialize most of statement related variables
			$self->{'no_break'}                    = 0;
			$self->{'_is_in_generated'}            = 0;
			$self->{'_is_in_where'}                = 0;
			$self->{'_is_in_between'}              = 0;
			$self->{'_is_in_from'}                 = 0;
			$self->{'_is_in_join'}                 = 0;
			$self->{'_is_in_create'}               = 0;
			$self->{'_is_in_create_schema'}        = 0;
			$self->{'_is_in_alter'}                = 0;
			$self->{'_is_in_rule'}                 = 0;
			$self->{'_is_in_publication'}          = 0;
			$self->{'_is_in_call'}                 = 0;
			$self->{'_is_in_type'}                 = 0;
			$self->{'_is_in_domain'}               = 0;
			$self->{'_is_in_function'}             = 0;
			$self->{'_current_function'}           = '';
			$self->{'_is_in_prodedure'}            = 0;
			$self->{'_is_in_index'}                = 0;
			$self->{'_is_in_statistics'}           = 0;
			$self->{'_is_in_cast'}                 = 0;
			$self->{'_is_in_if'}                   = 0;
			$self->{'_is_in_set'}                  = 0;
			$self->{'_is_in_with'}                 = 0;
			$self->{'_is_in_overlaps'}             = 0;
			$self->{'_has_order_by'}               = 0;
			$self->{'_has_over_in_join'}           = 0;
			$self->{'_parenthesis_level'}          = 0;
			$self->{'_parenthesis_function_level'} = 0;
			$self->{'_is_in_constraint'}           = 0;
			$self->{'_is_in_distinct'}             = 0;
			$self->{'_is_in_array'}                = 0;
			$self->{'_is_in_filter'}               = 0;
			$self->{'_parenthesis_filter_level'}   = 0;
			$self->{'_is_in_partition'}            = 0;
			$self->{'_is_in_over'}                 = 0;
			$self->{'_is_in_policy'}               = 0;
			$self->{'_is_in_truncate'}             = 0;
			$self->{'_is_in_trigger'}              = 0;
			$self->{'_is_in_using'}                = 0;
			$self->{'_and_level'}                  = 0;
			$self->{'_col_count'}                  = 0;
			$self->{'_is_in_drop'}                 = 0;
			$self->{'_is_in_conversion'}           = 0;
			$self->{'_is_in_operator'}             = 0;
			$self->{'_is_in_explain'}              = 0;
			$self->{'_is_in_sub_query'}            = 0;
			$self->{'_is_in_fetch'}                = 0;
			$self->{'_is_in_aggregate'}            = 0;
			$self->{'_is_in_value'}                = 0;
			$self->{'_parenthesis_level_value'}    = 0;
			$self->{'_parenthesis_with_level'}     = 0;
			$self->{'_is_in_returns_table'}        = 0;
			$self->{'_has_limit'}                  = 0;
			$self->{'_not_a_type'}                 = 0;
			$self->{'_is_subquery'}                = 0;
			$self->{'_is_in_order_by'}             = 0;
			$self->{'_is_in_materialized'}         = 0;
			$self->{'_is_in_drop_function'}        = 0;
			$self->{'_current_full_sql_stmt'}      = '';

			if ( $self->{'_insert_values'} ) {
				if (    $self->{'_is_in_block'} == -1
					and !$self->{'_is_in_declare'}
					and !$self->{'_fct_code_delimiter'} )
				{
					$self->_reset_level( $token, $last );
				}
				elsif ( $self->{'_is_in_block'} == -1
					and $self->{'_current_sql_stmt'} eq 'INSERT'
					and !$self->{'_is_in_create'}
					and !$self->{'_is_in_create_function'} )
				{
					$self->_back( $token, $last );
					$self->_pop_level( $token, $last );
				}
				else {
					$self->_set_level( $self->_pop_level( $token, $last ),
						$token, $last );
				}
				$self->{'_insert_values'} = 0;
			}
			$self->{'_current_sql_stmt'} = '';
			$self->{'break'} = "\n" unless ( $self->{'spaces'} != 0 );

#$self->_new_line($token,$last) if ($last !~ /^(VALUES|IMPLICIT|ASSIGNMENT)$/i);
			$self->_new_line( $token, $last ) if ( $last !~ /^VALUES$/i );

			# Add an additional newline after ; when we are not in a function
			if (    $self->{'_is_in_block'} == -1
				and !$self->{'_is_in_work'}
				and !$self->{'_language_sql'}
				and !$self->{'_is_in_declare'}
				and uc($last) ne 'VALUES' )
			{
				$self->{'_new_line'} = 0;
				$self->_new_line( $token, $last );
				$self->{'stmt_number'}++;
				$self->{'content'} .=
				  "-- Statement # $self->{ 'stmt_number' }\n"
				  if ( $self->{'numbering'} and $#{ $self->{'_tokens'} } > 0 );
			}

 # End of statement; remove all indentation when we are not in a BEGIN/END block
			if (   !$self->{'_is_in_declare'}
				and $self->{'_is_in_block'} == -1
				and !$self->{'_fct_code_delimiter'}
				and !$self->{'_is_in_exception'} )
			{
				$self->_reset_level( $token, $last );
			}
			elsif (
				!$self->{'_language_sql'}
				and ( not defined $self->_next_token
					or $self->_next_token !~ /^INSERT$/ )
				and !$self->{'_is_in_exception'}
			  )
			{
				if ( $#{ $self->{'_level_stack'} } == -1 ) {
					$self->_set_level(
						( $self->{'_is_in_declare'} )
						? 1
						: ( $self->{'_is_in_block'} + 1 ),
						$token, $last
					);
				}
				else {
					$self->_set_level( $self->{'_level_stack'}[-1],
						$token, $last );
				}
			}
			$last = $self->_set_last( $token, $last );
		}

		elsif ( $token =~ /^FOR$/i ) {
			if ( $self->{'_is_in_policy'} ) {
				$self->_over( $token, $last );
				$self->_new_line( $token, $last );
				$self->_add_token($token);
				$last = $self->_set_last( $token, $last );
				next;
			}

			if ( $self->_next_token =~ /^(UPDATE|KEY|NO|VALUES)$/i ) {
				$self->_back( $token, $last )
				  if (
					!$self->{'_has_limit'}
					and (  $#{ $self->{'_level_stack'} } == -1
						or $self->{'_level'} > $self->{'_level_stack'}[-1] )
				  );
				$self->_new_line( $token, $last );
				$self->{'_has_limit'} = 0;
			}
			elsif ( $self->_next_token =~ /^EACH$/
				and $self->{'_is_in_trigger'} )
			{
				$self->_new_line( $token, $last );
			}
			$self->_add_token($token);

			# cover FOR in cursor
			$self->_over( $token, $last )
			  if ( uc( $self->_next_token ) eq 'SELECT' );
			$last = $self->_set_last( $token, $last );
		}

		elsif ( $token =~ /^(?:FROM|WHERE|SET|RETURNING|HAVING|VALUES)$/i )
		{
			if (    uc($token) eq 'FROM'
				and $self->{'_has_order_by'}
				and !$self->{'_parenthesis_level'} )
			{
				$self->_back( $token, $last ) if ( $self->{'_has_order_by'} );
			}

			$self->{'no_break'}   = 0;
			$self->{'_col_count'} = 0;
			$self->{'_is_in_set'} = 1
			if ( uc($token) eq 'SET'
				&& $self->{'_current_sql_stmt'} !~ /^(UPDATE|INSERT)$/i );

			# special cases for create partition statement
			if (    $token =~ /^VALUES$/i && defined $last
				and $last =~ /^(FOR|IN)$/i )
			{
				$self->_add_token($token);
				$self->{'no_break'} = 1;
				$last = $self->_set_last( $token, $last );
				next;
			}
			elsif ( $token =~ /^FROM$/i && defined $last
				and uc($last) eq 'VALUES' )
			{
				$self->_add_token($token);
				$last = $self->_set_last( $token, $last );
				next;
			}

			# Case of DISTINCT FROM clause
			if ( $token =~ /^FROM$/i ) {
				if (   uc($last) eq 'DISTINCT'
					|| $self->{'_is_in_fetch'}
					|| $self->{'_is_in_alter'}
					|| $self->{'_is_in_conversion'}
					|| $self->{'_is_in_set'} )
				{
					$self->_add_token($token);
					$last = $self->_set_last( $token, $last );
					$self->{'_is_in_set'} = 0;
					next;
				}
				$self->{'_is_in_from'}++
				  if ( !$self->{'_is_in_function'}
					&& !$self->{'_is_in_partition'} );
			}

			if ( $token =~ /^WHERE$/i && !$self->{'_is_in_filter'} ) {
				$self->_back( $token, $last )
				  if ( $self->{'_has_over_in_join'} );
				$self->{'_is_in_where'}++;
				$self->{'_is_in_from'}-- if ( $self->{'_is_in_from'} );
				$self->{'_is_in_join'}       = 0;
				$self->{'_has_over_in_join'} = 0;
			}
			elsif ( !$self->{'_is_in_function'} ) {
				$self->{'_is_in_where'}-- if ( $self->{'_is_in_where'} );
			}

			if ( $token =~ /^SET$/i and $self->{'_is_in_create'} ) {

				# Add newline before SET statement in function header
				$self->_new_line( $token, $last )
				  if ( not defined $last or $last !~ /^(DELETE|UPDATE)$/i );
			}
			elsif ( $token =~ /^WHERE$/i
				and $self->{'_current_sql_stmt'} eq 'DELETE' )
			{
				$self->_new_line( $token, $last );
				$self->_add_token($token);
				$self->_over( $token, $last );
				$last                  = $self->_set_last( $token, $last );
				$self->{'_is_in_join'} = 0;
				$last                  = $self->_set_last( $token, $last );
				next;
			}
			elsif ( $token =~ /^SET$/i
				and defined $last
				and uc($last) eq 'UPDATE'
				and !$self->_is_keyword( $self->_next_token() ) )
			{
				$self->{'_is_in_index'} = 0;
				$self->{'_is_in_from'}  = 0;
				$self->_add_token($token);
				$self->_new_line( $token, $last );
				$self->_over( $token, $last );
				$last = $self->_set_last( $token, $last );
				next;
			}
			elsif (
				$token !~ /^FROM$/i
				or (    !$self->{'_is_in_function'}
					and !$self->{'_is_in_statistics'}
					and $self->{'_current_sql_stmt'} !~ /(DELETE|REVOKE)/ )
			  )
			{
				if ( !$self->{'_is_in_filter'}
					and ( $token !~ /^SET$/i or !$self->{'_is_in_index'} ) )
				{
					$self->_back( $token, $last )
					  if (
						(
							uc($token) ne 'VALUES'
							or $self->{'_current_sql_stmt'} ne 'INSERT'
							and $last ne "'"
						)
						and (  uc($token) !~ /^WHERE$/i
							or $self->{'_is_in_with'} < 2
							or $self->{'_level'} > 1 )
					  );
					if (    uc($token) eq 'WHERE'
						and $self->{'_is_in_function'}
						and $self->{'_is_subquery'} <= 2 )
					{
						$self->_over( $token, $last );
					}
					$self->_new_line( $token, $last )
					  if (
						!$self->{'_is_in_rule'}
						and
						( $last !~ /^DEFAULT$/i or $self->_next_token() ne ';' )
					  );
				}
			}
			else {
				if (
						uc($token) eq 'FROM'
					and $self->{'_is_in_sub_query'}
					and !grep( /^\Q$last\E$/i, @extract_keywords )
					and
					( $self->{'_insert_values'} or $self->{'_is_in_function'} )
					and (
						!$self->{'_is_in_function'}
						or !grep( /^$self->{ '_current_function' }$/,
							@have_from_clause )
					)
				  )
				{
					$self->_new_line( $token, $last );
					$self->_back( $token, $last );
				}
				if ( uc($token) eq 'FROM' ) {
					$self->{'_current_function'} = '';
				}
				$self->_add_token($token);
				$last = $self->_set_last( $token, $last );
				next;
			}

			if (
					$token =~ /^VALUES$/i
				and !$self->{'_is_in_rule'}
				and !$self->{'comma_break'}
				and ( $self->{'_current_sql_stmt'} eq 'INSERT' or $last eq '(' )
			  )
			{
				$self->_over( $token, $last )
				if (uc($token) ne 'VALUES' || $self->{'_current_sql_stmt'} ne 'INSERT' || $self->{'_current_full_sql_stmt'} !~ /\) , \(/);

				if ( $self->{'_current_sql_stmt'} eq 'INSERT' or $last eq '(' )
				{
					$self->{'_insert_values'} = 1;
					$self->_push_level( $self->{'_level'}, $token, $last );
				}
			}

			if ( $token =~ /^VALUES$/i and $last eq '(' ) {
				$self->{'_is_in_value'} = 1;
			}

			if ( uc($token) eq 'WHERE' ) {
				$self->_add_token( $token, $last );
				$self->{'_is_in_value'}             = 0;
				$self->{'_parenthesis_level_value'} = 0;
			}
			else {
				$self->_add_token($token);
			}

			if ( $token =~ /^VALUES$/i and $last eq '(' ) {
				$self->_over( $token, $last );
			}
			elsif ($token =~ /^SET$/i
				&& $self->{'_current_sql_stmt'} eq 'UPDATE' )
			{
				$self->_new_line( $token, $last ) if ( !$self->{'wrap_after'} );
				$self->_over( $token, $last );
			}
			elsif (
					!$self->{'_is_in_over'}
				and !$self->{'_is_in_filter'}
				and (  $token !~ /^SET$/i
					or $self->{'_current_sql_stmt'} eq 'UPDATE' )
			  )
			{
				if (
						defined $self->_next_token
					and $self->_next_token !~ /\(|;/
					and ( $self->_next_token !~ /^(UPDATE|KEY|NO)$/i
						|| uc($token) eq 'WHERE' )
				  )
				{
					$self->_new_line( $token, $last )
					  if ( !$self->{'wrap_after'} );
					$self->_over( $token, $last );
				}
			}
		}

# Add newline before INSERT and DELETE if last token was AS (prepared statement)
		elsif ( defined $last
			and $token =~ /^(?:INSERT|DELETE|UPDATE)$/i
			and uc($last) eq 'AS' )
		{
			$self->_new_line( $token, $last );
			$self->_add_token($token);
		}

		elsif ( $self->{'_current_sql_stmt'} !~ /^(GRANT|REVOKE)$/
			and $token =~ /^(?:SELECT|PERFORM|UPDATE|DELETE)$/i
			and ( !$self->{'_is_in_policy'} || $self->{'format_type'} ) )
		{
			$self->{'no_break'} = 0;

			if (   $token =~ /^(SELECT|UPDATE|DELETE|INSERT)$/i
				&& $self->{'_is_in_policy'} )
			{
				$self->_over( $token, $last );
			}

			# case of ON DELETE/UPDATE clause in create table statements
			if ( $token =~ /^(UPDATE|DELETE)$/i && $self->{'_is_in_create'} ) {
				$self->_add_token($token);
				$last = $self->_set_last( $token, $last );
				next;
			}
			if ( $token =~ /^UPDATE$/i and $last =~ /^(FOR|KEY|DO)$/i ) {
				$self->_add_token($token);
				if ( uc($last) eq 'DO' && uc( $self->_next_token ) eq 'SET' ) {
					$self->{'_current_sql_stmt'} = 'DO UPDATE';
				}
			}
			elsif (
				  !$self->{'_is_in_policy'}
				&& $token !~ /^(DELETE|UPDATE)$/i
				&& ( !defined $self->_next_token
					|| $self->_next_token !~ /^DISTINCT$/i )
			  )
			{
				$self->_new_line( $token, $last )
				  if ( !defined $last or $last ne "\\\\" );
				$self->_add_token($token);
				$self->_new_line( $token, $last )
				  if ( !$self->{'wrap_after'}
					and ( !defined $last or $last ne "\\\\" ) );
				$self->_over( $token, $last );
			}
			else {
				if ( $self->{'_is_in_policy'} > 1 ) {
					$self->_new_line( $token, $last );
				}
				$self->_add_token($token);
				if ( $self->{'_is_in_policy'} > 1 ) {
					$self->_new_line( $token, $last );
					$self->_over( $token, $last );
				}
				$self->{'_is_in_policy'}++ if ( $self->{'_is_in_policy'} );
			}
		}

		elsif ( $self->{'_current_sql_stmt'} !~ /^(GRANT|REVOKE)$/
			and uc($token) eq 'INSERT'
			and $self->{'_is_in_policy'} && $self->{'format_type'} )
		{
			$self->_add_token($token);
			$self->_new_line( $token, $last );
			$self->_over( $token, $last );
		}
		elsif ( $token =~ /^(?:WITHIN)$/i ) {
			$self->{'_is_in_within'} = 1;
			$self->{'_has_order_by'} = 1;
			$self->_add_token($token);
			$last = $self->_set_last( $token, $last );
			next;
		}

		elsif (
			$token =~ /^(?:GROUP|ORDER|LIMIT|EXCEPTION)$/i
			or
			( uc($token) eq 'ON' and uc( $self->_next_token() ) eq 'CONFLICT' )
		  )
		{
			#if (uc($last) ne 'RAISE' and $token =~ /^EXCEPTION$/i)
			#{
			#$self->{ '_is_in_exception' } = 1;
			#}
			if (    $self->{'format_type'}
				and uc($token) eq 'GROUP'
				and uc( $self->_next_token() ) eq 'BY' )
			{
				$self->{'no_break'} = 1;
			}
			if ( uc($token) eq 'ORDER' and uc( $self->_next_token() ) eq 'BY' )
			{
				$self->{'_is_in_order_by'} = 1;
			}
			else {
				$self->{'_is_in_order_by'} = 0;
			}
			$self->{'_is_in_value'}             = 0;
			$self->{'_parenthesis_level_value'} = 0;
			if (   uc($token) eq 'GROUP' and !defined $last
				or uc($last) eq 'EXCLUDE' )
			{
				$self->_add_token($token);
				$last = $self->_set_last( $token, $last );
				next;
			}
			if (   ( $self->{'_is_in_within'} && uc($token) eq 'GROUP' )
				|| ( $self->{'_is_in_over'} && uc($token) eq 'ORDER' ) )
			{
				$self->_add_token($token);
				$last = $self->_set_last( $token, $last );
				next;
			}
			if ( $self->{'_has_over_in_join'} and uc($token) eq 'GROUP' ) {
				$self->_back( $token, $last );
				$self->{'_has_over_in_join'} = 0;
			}
			$self->{'_is_in_join'} = 0;
			$self->{'_has_limit'}  = 1 if ( uc($token) eq 'LIMIT' );
			if ( $token !~ /^EXCEPTION/i ) {
				$self->_back( $token, $last );
			}
			else {
				$self->_set_level( $self->_pop_level( $token, $last ),
					$token, $last );
			}
			if (   uc($token) ne 'EXCEPTION'
				or not defined $last
				or uc($last) ne 'RAISE' )
			{
				# Excluding CREATE/DROP GROUP
				if ( uc($token) ne 'LIMIT' or !$self->{'_is_in_create'} ) {
					$self->_new_line( $token, $last )
					  if ( !$self->{'_is_in_function'}
						and ( not defined $last or $last !~ /^(CREATE|DROP)$/ )
					  );
				}
			}

			# Store current indent position to print END at the right level
			if ( uc($last) ne 'RAISE' and $token =~ /^EXCEPTION$/i ) {
				$self->{'_is_in_exception'} = 1;
				if ( $#{ $self->{'_begin_level'} } >= 0 ) {
					$self->_set_level( $self->{'_begin_level'}[-1],
						$token, $last );
				}
			}
			elsif ( uc($last) eq 'RAISE' and $token =~ /^EXCEPTION$/i ) {
				$self->_push_level( $self->{'_level'}, $token, $last );
				$self->_over( $token, $last );
			}
			$self->{'_is_in_where'}-- if ( $self->{'_is_in_where'} );
			$self->_add_token($token);
			if ( $token =~ /^EXCEPTION$/i && $self->{'_level'} == 0 ) {
				$self->_over( $token, $last );
			}
		}

		elsif ( $token =~ /^(?:BY)$/i
			and $last !~ /^(?:INCREMENT|OWNED|PARTITION|GENERATED)$/i )
		{
			$self->_add_token($token);
			$self->{'_col_count'} = 0
			  if ( defined $last && $last =~ /^(?:GROUP|ORDER)/i );
			if ( !$self->{'_has_order_by'} and !$self->{'_is_in_over'} ) {
				$self->_new_line( $token, $last )
				  if ( !$self->{'wrap_after'} and !$self->{'_is_in_function'} );
				$self->_over( $token, $last );
			}
		}

		elsif ( $token =~ /^(?:CASE)$/i and uc($last) ne 'END' ) {
			if ( $self->{'_is_in_policy'} ) {
				$self->_new_line( $token, $last );
				$self->_over( $token, $last );
				$self->_add_token($token);
				$self->{'_is_in_policy'}++;
			}
			else {
				$self->_add_token($token);
			}

			# Store current indent position to print END at the right level
			$self->_push_level( $self->{'_level'}, $token, $last );

			# Mark next WHEN statement as first element of a case
			# to force indentation only after this element
			$self->{'_first_when_in_case'} = 1;
			push( @{ $self->{'_is_in_case'} }, $self->{'_level'} );
		}

		elsif ($token =~ /^(?:WHEN)$/i
			&& $self->_is_keyword( $token, $self->_next_token(), $last ) )
		{
			if (    !$self->{'_first_when_in_case'}
				and !$self->{'_is_in_trigger'}
				and defined $last
				and uc($last) ne 'CASE' )
			{
				if ( !$self->{'_is_in_exception'} ) {
					$self->_set_level( $self->{'_level_stack'}[-1],
						$token, $last )
					  if ( $#{ $self->{'_level_stack'} } >= 0 );
				}
				elsif ( $#{ $self->{'_begin_level'} } >= 0 ) {

			 #$self->_set_level($self->{ '_begin_level' }[-1]+1, $token, $last);
					$self->_set_level( $self->{'_begin_level'}[-1] + 1,
						$token, $last );
				}
			}
			$self->_new_line( $token, $last )
			  if ( not defined $last or $last !~ /^(CASE|,|\()$/i );
			$self->_add_token($token);
			if ( $#{ $self->{'_is_in_case'} } < 0
				&& !$self->{'_is_in_trigger'} )
			{
				$self->_over( $token, $last );
			}
			$self->{'_first_when_in_case'} = 0;
		}

		elsif ($token =~ /^(?:IF|LOOP)$/i
			&& $self->{'_current_sql_stmt'} ne 'GRANT' )
		{
			if ( $self->{'_is_in_join'} ) {
				$self->{'_is_in_join'} = 0;
				$self->_back( $token, $last );
				$self->_add_token($token);
			}
			else {
				$self->_add_token($token);
			}
			$self->{'no_break'} = 0;
			if ( defined $self->_next_token
				and $self->_next_token !~ /^(EXISTS|;)$/i )
			{
				if (   uc( $self->_next_token ) ne 'NOT'
					|| uc( $self->{'_tokens'}->[1] ) ne 'EXISTS' )
				{
					$self->_new_line( $token, $last )
					  if ( $token =~ /^LOOP$/i );
					$self->_over( $token, $last );
					$self->_push_level( $self->{'_level'}, $token, $last );
					if ( $token =~ /^IF$/i ) {
						$self->{'_is_in_if'} = 1;
					}
				}
			}
		}

		elsif ( $token =~ /^THEN$/i ) {
			$self->_add_token($token);
			$self->_new_line( $token, $last );
			$self->_set_level( $self->{'_level_stack'}[-1], $token, $last )
			  if (  $self->{'_is_in_if'}
				and $#{ $self->{'_level_stack'} } >= 0 );
			if ( $#{ $self->{'_is_in_case'} } >= 0
				&& defined $self->_next_token()
				and $self->_next_token() !~ /^(\(|RAISE)$/i )
			{
				$self->_set_level( $self->{'_level_stack'}[-1], $token, $last )
				  if ( $#{ $self->{'_level_stack'} } >= 0 );
				$self->_over( $token, $last );
			}
			if ( $#{ $self->{'_is_in_case'} } >= 0
				&& defined $self->_next_token()
				and $self->_next_token() eq '('
				and $self->{'_tokens'}[1] !~ /^(SELECT|CASE)$/i )
			{
				$self->_set_level( $self->{'_level_stack'}[-1], $token, $last )
				  if ( $#{ $self->{'_level_stack'} } >= 0 );
				$self->_over( $token, $last );
			}
			$self->{'_is_in_if'} = 0;
		}

		elsif ( $token =~ /^(?:ELSE|ELSIF)$/i ) {
			if ( $#{ $self->{'_is_in_case'} } < 0 ) {
				$self->_back( $token, $last );
			}
			else {
				$self->_set_level( $self->{'_is_in_case'}[-1], $token, $last );
			}
			$self->_new_line( $token, $last );
			$self->_add_token($token);
			$self->_new_line( $token, $last ) if ( $token !~ /^ELSIF$/i );
			$self->_over( $token, $last );
		}

		elsif ( $token =~ /^(?:END)$/i ) {
			$self->{'_first_when_in_case'} = 0;
			if ( $#{ $self->{'_is_in_case'} } >= 0 ) {
				pop( @{ $self->{'_is_in_case'} } );
				$self->_back( $token, $last );
				$self->_set_level( $self->_pop_level( $token, $last ),
					$token, $last );
				if (  !$self->{'_is_in_create_function'}
					or $self->_next_token eq ';' )
				{
					$self->_new_line( $token, $last );
					$self->_add_token($token);
					next;
				}
			}

# When we are not in a function code block (0 is the main begin/end block of a function)
			elsif ( $self->{'_is_in_block'} == -1 && $last ne ',' ) {

	  # END is closing a create function statement so reset position to begining
				if ( $self->_next_token !~
					/^(IF|LOOP|CASE|INTO|FROM|END|ELSE|AND|OR|WHEN|AS|,)$/i )
				{
					$self->_reset_level( $token, $last );
				}
				else {
					# otherwise back to last level stored at CASE keyword
					$self->_set_level( $self->_pop_level( $token, $last ),
						$token, $last );
				}
			}

			# We reach the last end of the code
			elsif ( $self->{'_is_in_block'} > -1
				and $self->_next_token =~ /^(;|\$.*\$)$/
				and !$self->{'_is_in_exception'} )
			{
				if ( $self->{'_is_in_block'} == 0 ) {
					$self->_reset_level( $token, $last );
				}
				else {
					$self->_set_level( $self->_pop_level( $token, $last ) - 1,
						$token, $last );
					$self->{'_is_in_block'}--;
				}
			}

			# We are in code block
			elsif ( $last ne ',' ) {

			   # decrease the block level if this is a END closing a BEGIN block
				if ( $self->_next_token !~
					/^(IF|LOOP|CASE|INTO|FROM|END|ELSE|AND|OR|WHEN|AS|,)$/i )
				{
					$self->{'_is_in_block'}--;
				}

				# Go back to level stored with IF/LOOP/BEGIN/EXCEPTION block
				if ( $self->{'_is_in_block'} > -1 ) {
					$self->_set_level( $self->_pop_level( $token, $last ),
						$token, $last );
				}
				else {
					$self->_reset_level( $token, $last );
				}
			}
			if ( $self->_next_token eq ';' ) {
				$self->_set_level( pop( @{ $self->{'_begin_level'} } ),
					$token, $last );
			}
			elsif (!$self->{'_is_in_exception'}
				and $self->_next_token !~ /^(AS|CASE|FROM|,)$/i )
			{
				$self->_back( $token, $last )
				  if ( $self->_next_token =~
					/^(IF|LOOP|CASE|INTO|FROM|END|ELSE|AND|OR|WHEN|AS|,)$/i );
			}
			$self->_new_line( $token, $last );
			$self->_add_token($token);
		}

		elsif ( $token =~ /^(?:END::[^\s]+)$/i
			and $#{ $self->{'_is_in_case'} } >= 0 )
		{
			$self->{'_first_when_in_case'} = 0;
			pop( @{ $self->{'_is_in_case'} } );
			$self->_back( $token, $last );
			$self->_set_level( $self->_pop_level( $token, $last ),
				$token, $last );
			$self->_new_line( $token, $last );
			$self->_add_token($token);
		}

		elsif ( $token =~ /^(?:UNION|INTERSECT|EXCEPT)$/i ) {
			$self->{'no_break'} = 0;
			if ( $self->{'_is_in_join'} ) {
				$self->_back( $token, $last );
				$self->{'_is_in_join'} = 0;
			}
			$self->_back( $token, $last ) unless defined $last and $last eq '(';
			$self->_new_line( $token, $last );
			$self->_add_token($token);
			$self->_new_line( $token, $last )
			  if (  defined $self->_next_token
				and $self->_next_token ne '('
				and $self->_next_token !~ /^ALL$/i );
			$self->{'_is_in_where'}-- if ( $self->{'_is_in_where'} );
			$self->{'_is_in_from'} = 0;
		}

		elsif ( $token =~ /^(?:LEFT|RIGHT|FULL|INNER|OUTER|CROSS|NATURAL)$/i
			and ( not defined $last or uc($last) ne 'MATCH' ) )
		{
			$self->{'no_break'} = 0;
			if ( !$self->{'_is_in_join'} and ( $last and $last ne ')' ) ) {
				$self->_back( $token, $last ) if ($#{ $self->{'_level_stack'} } < 0 or $self->{'_level'} > $self->{'_level_stack'}[-1]+1);
			}
			if ( $self->{'_has_over_in_join'} ) {
				$self->{'_has_over_in_join'} = 0;
				$self->_back( $token, $last );
			}

			if ( $token =~ /(?:LEFT|RIGHT|FULL|CROSS|NATURAL)$/i ) {
				$self->_new_line( $token, $last );
				$self->_over( $token, $last )
				  if (
					$self->{'_level'} == 0
					|| ( $self->{'_is_in_with'} > 1 and $self->{'_level'} == 1 )
				  );
			}
			if (   ( $token =~ /(?:INNER|OUTER)$/i )
				&& ( $last !~ /(?:LEFT|RIGHT|CROSS|NATURAL|FULL)$/i ) )
			{
				$self->_new_line( $token, $last );
				$self->_over( $token, $last ) if ( !$self->{'_is_in_join'} );
			}
			$self->_add_token($token);
		}

		elsif ( $token =~ /^(?:JOIN)$/i and !$self->{'_is_in_operator'} ) {
			$self->{'no_break'} = 0;
			if ( not defined $last
				or $last !~ /^(?:LEFT|RIGHT|FULL|INNER|OUTER|CROSS|NATURAL)$/i )
			{
				$self->_new_line( $token, $last );
				$self->_back( $token, $last )
				  if ( $self->{'_has_over_in_join'} );
				$self->{'_has_over_in_join'} = 0;
			}
			$self->_add_token($token);
			$self->{'_is_in_join'} = 1;
		}

		elsif ( $token =~ /^(?:AND|OR)$/i ) {
			$self->{'_is_in_where'} = 0;

			# Try to detect AND in BETWEEN clause to prevent newline insert
			if (
				uc($token) eq 'AND'
				and (
					$self->{'_is_in_between'}
					|| ( defined $last
						&& $last =~ /^(PRECEDING|FOLLOWING|ROW)$/i )
				)
			  )
			{
				$self->_add_token($token);
				$last = $self->_set_last( $token, $last );
				$self->{'_is_in_between'} = 0;
				next;
			}
			$self->{'no_break'} = 0;
			if ( $self->{'_is_in_join'} ) {
				$self->_over( $token, $last );
				$self->{'_has_over_in_join'} = 1;
			}
			$self->{'_is_in_join'} = 0;
			if (    !$self->{'_is_in_if'}
				and !$self->{'_is_in_index'}
				and ( !$last or $last !~ /^(?:CREATE)$/i )
				and ( $self->{'_is_in_create'} <= 2 )
				and !$self->{'_is_in_trigger'} )
			{
				$self->_new_line( $token, $last );
				if ( !$self->{'_and_level'}
					and ( !$self->{'_level'} || $self->{'_is_in_alter'} ) )
				{
					$self->_over( $token, $last );
				}
				elsif ( $self->{'_and_level'}
					and !$self->{'_level'}
					and uc($token) eq 'OR' )
				{
					$self->_over( $token, $last );
				}
				elsif ( $#{ $self->{'_level_stack'} } >= 0
					and $self->{'_level'} == $self->{'_level_stack'}[-1] )
				{
					$self->_over( $token, $last );
				}
			}
			$self->_add_token($token);
			$self->{'_and_level'}++;
		}

		elsif ( $token =~ /^\/\*.*\*\/$/s ) {
			if ( !$self->{'no_comments'} ) {
				$token =~ s/\n[\s\t]+\*/\n\*/gs;
				if ( !$self->{'_is_in_over'} and !$self->{'_is_in_function'} ) {
					$self->_new_line( $token, $last ), $self->_add_token('')
					  if ( defined $last and $last eq ';' );
					$self->_new_line( $token, $last );
				}
				$self->_add_token($token);
				$self->{'break'} = "\n" unless ( $self->{'spaces'} != 0 );
				if (
						!$self->{'_is_in_function'}
					and !$self->{'_is_in_over'}
					and (  !$self->_is_comment($token)
						or !defined $self->_next_token
						or $self->_next_token ne ')' )
				  )
				{
					$self->_new_line( $token, $last );
				}
				$self->{'break'} = " " unless ( $self->{'spaces'} != 0 );
			}
		}

		elsif (
			(
					$token =~ /^USING$/i
				and !$self->{'_is_in_order_by'}
				and !$self->{'_is_in_exception'}
				and ( $self->{'_current_sql_stmt'} ne 'DELETE'
					or uc( $self->_next_token ) !~ /^(\(|LATERAL)$/i )
			)
			or (    uc($token) eq 'WITH'
				and uc( $self->_next_token() ) eq 'CHECK'
				and $self->{'_is_in_policy'} )
		  )
		{
			if ( !$self->{'_is_in_from'} ) {
				$self->_over( $token, $last )
				  if (
					$self->{'_is_in_operator'}
					|| (   $self->{'_is_in_policy'}
						&& !$self->{'format_type'}
						&& !$self->{'_is_in_using'} )
				  );
				$self->_push_level( $self->{'_level'}, $token, $last )
				  if ( $token =~ /^USING$/i );
				$self->_set_level( $self->_pop_level( $token, $last ),
					$token, $last )
				  if ( uc($token) eq 'WITH'
					and $self->{'_is_in_policy'} > 1
					&& !$self->{'format_type'}
					&& $self->{'_is_in_using'} );
				$self->_new_line( $token, $last )
				  if (  uc($last) ne 'EXCLUDE'
					and !$self->{'_is_in_index'}
					and !$self->{'_is_in_function'} );
			}
			else {
				# USING from join clause disable line break like in function
				$self->{'_is_in_function'}++;

				# Restore FROM position
				$self->_set_level( $self->_pop_level( $token, $last ),
					$token, $last )
				  if ( !$self->{'_is_in_join'} );
			}
			$self->_add_token($token);
			$self->{'_is_in_using'} = 1;
			$self->{'_is_in_policy'}++
			  if ( !$self->{'_is_in_from'}
				&& !$self->{'_is_in_join'}
				&& uc($last) ne 'EXCLUDE'
				&& !$self->{'_is_in_function'}
				&& !$self->{'_is_in_operator'}
				&& !$self->{'_is_in_create'}
				&& !$self->{'_is_in_index'} );
		}

		elsif ( $token =~ /^EXCLUDE$/i ) {
			if (   $last !~ /^(FOLLOWING|ADD)$/i
				or $self->_next_token !~ /^USING$/i )
			{
				$self->_new_line( $token, $last )
				  if ( $last !~ /^(FOLLOWING|ADD)$/i );
			}
			$self->_add_token($token);
			$self->{'_is_in_using'} = 1;
		}

		elsif ( $token =~ /^\\\S/ ) {

# treat everything starting with a \ and at least one character as psql meta command.
			$self->_add_token($token);
			$self->_new_line( $token, $last )
			  if (  $token ne "\\\\"
				and defined $self->_next_token
				and $self->_next_token ne "\\\\" );
		}

		elsif (
			$token =~ /^(ADD|DROP)$/i
			&& (   $self->{'_current_sql_stmt'} eq 'SEQUENCE'
				|| $self->{'_current_sql_stmt'} eq 'ALTER' )
		  )
		{
			if (
				$self->_next_token !~ /^(NOT|NULL|DEFAULT)$/i
				and (  not defined $last
					or !$self->{'_is_in_alter'}
					or $last ne '(' )
			  )
			{
				$self->_new_line( $token, $last );
				if ( $self->{'_is_in_alter'} < 2 ) {
					$self->_over( $token, $last );
				}
			}
			$self->_add_token( $token, $last );
			$self->{'_is_in_alter'}++ if ( $self->{'_is_in_alter'} == 1 );
		}

		elsif ($token =~ /^INCREMENT$/i
			&& $self->{'_current_sql_stmt'} eq 'SEQUENCE' )
		{
			$self->_new_line( $token, $last );
			$self->_add_token($token);
		}

		elsif ( $token =~ /^NO$/i
			and $self->_next_token =~ /^(MINVALUE|MAXVALUE)$/i )
		{
			$self->_new_line( $token, $last );
			$self->_add_token($token);
		}

		elsif ( $last !~ /^(\(|NO)$/i and $token =~ /^(MINVALUE|MAXVALUE)$/i ) {
			$self->_new_line( $token, $last );
			$self->_add_token($token);
		}

		elsif ( $token =~ /^CACHE$/i ) {
			$self->_new_line( $token, $last );
			$self->_add_token($token);
		}
		else {
			next if ( $self->{'keep_newline'} and $token =~ /^\s+$/ );

			if (    $self->{'_fct_code_delimiter'}
				and $self->{'_fct_code_delimiter'} =~ /^'.*'$/ )
			{
				$self->{'_fct_code_delimiter'} = "";
				$self->{'_language_sql'}       = 0;
			}
			if ( $self->{'_is_in_block'} != -1
				and !$self->{'_fct_code_delimiter'} )
			{
				$self->{'_is_in_block'}     = -1;
				$self->{'_is_in_procedure'} = 0;
				$self->{'_is_in_function'}  = 0;
			}

			# special case with comment
			if ( $token =~ /(?:\s*--)[\ \t\S]*/s ) {
				if ( !$self->{'no_comments'} ) {
					$token =~ s/^(\s*)(--.*)/$2/s;
					my $start = $1 || '';
					if ( $start =~ /\n/s ) {
						$self->_new_line( $token, $last ), $self->_add_token('')
						  if (  defined $last
							and $last eq ';'
							and $self->{'content'} !~ /\n$/s );
						$self->_new_line( $token, $last );
					}
					$token =~ s/\s+$//s;
					$token =~ s/^\s+//s;
					$self->_add_token($token);
					$self->_new_line( $token, $last )
					  if (
						$start
						|| (   $self->{'content'} !~ /\n$/s
							&& defined $self->_next_token
							&& uc( $self->_next_token ) ne 'AS' )
					  );

# Add extra newline after the last comment if we are not in a block or a statement
					if ( defined $self->_next_token
						and $self->_next_token !~ /^\s*--/ )
					{
						$self->{'content'} .= "\n"
						  if (  $self->{'_is_in_block'} == -1
							and !$self->{'_is_in_declare'}
							and !$self->{'_fct_code_delimiter'}
							and !$self->{'_current_sql_stmt'}
							and defined $last
							and $self->_is_comment($last)
							and $self->{'content'} !~ /\n$/s );
					}
					$last = $self->_set_last( $token, $last );
				}
				next;
			}

			if (    $last =~ /^(?:SEQUENCE)$/i
				and $self->_next_token !~ /^(OWNED|;)$/i )
			{
				$self->_add_token($token);
				$self->_new_line( $token, $last );
				$self->_over( $token, $last );
			}
			else {
				if (
					   defined $last
					&& $last eq ')'
					&& ( !defined $self->_next_token
						|| $self->_next_token ne ';' )
				  )
				{
					if (  !$self->{'_parenthesis_level'}
						&& $self->{'_is_in_from'} )
					{
						$self->_set_level(
							pop( @{ $self->{'_level_parenthesis'} } ) || 1,
							$token, $last );
					}
				}
				if (    defined $last
					and uc($last) eq 'UPDATE'
					and $self->{'_current_sql_stmt'} eq 'UPDATE' )
				{
					$self->_new_line( $token, $last );
					$self->_over( $token, $last );
				}

				if (    defined $last
					and uc($last) eq 'AS'
					and uc($token) eq 'WITH' )
				{
					$self->_new_line( $token, $last );
				}

				if ( uc($token) eq 'INSERT' and defined $last and $last eq ';' )
				{
					if ( $#{ $self->{'_level_stack'} } >= 0 ) {
						$self->_set_level( $self->{'_level_stack'}[-1],
							$token, $last );
					}
					else {
						if (  !$self->{_is_in_procedure}
							|| $self->{'_level'} > 1 )
						{
							$self->_back( $token, $last );
						}
					}
				}

				if (
					(
						$self->{'_is_in_policy'} > 1
						|| (   $self->{'_is_in_policy'}
							&& $self->{'_is_in_sub_query'} )
					)
					&& $token =~ /^(ALL|SELECT|UPDATE|DELETE|INSERT)$/i
				  )
				{
					$self->_new_line( $token, $last );
					$self->_over( $token, $last );
					$self->_add_token($token);
					$self->_new_line( $token, $last );
					$self->_over( $token, $last );
					$last = $self->_set_last( $token, $last );
					next;
				}
				$self->{'_is_in_policy'}++
				  if ( $token =~ /^SELECT$/i and $self->{'_is_in_policy'} );
				if (    $self->{'comma_break'}
					and $self->{'_current_sql_stmt'} eq 'INSERT'
					&& $last eq '(' )
				{
					$self->_new_line( $token, $last );
				}

				# Remove extra newline at end of code of SQL functions
				if (    $token eq "'"
					and $last eq ';'
					and $self->_next_token =~
					/^(;|LANGUAGE|STRICT|SET|IMMUTABLE|STABLE|VOLATILE)$/i )
				{
					$self->{'content'} =~ s/\s+$/\n/s;
				}

				# Finally add the token without further condition
				$self->_add_token( $token, $last );

				if ( $last eq "'" and $token =~ /^(BEGIN|DECLARE)$/i ) {
					$last = $self->_set_last( $token, $last );
					$self->_new_line( $token, $last );
					$self->_over( $token, $last );
				}

				# Reset CREATE statement flag when using CTE
				if (   $self->{'_is_in_create'}
					&& $self->{'_is_in_with'}
					&& uc($token) eq 'WITH'
					&& uc($last) eq 'AS' )
				{
					$self->{'_is_in_create'} = 0;
				}
				if (
					   defined $last
					&& uc($last) eq 'LANGUAGE'
					&& $self->_is_keyword( $last, $token )
					&& ( !defined $self->_next_token
						|| $self->_next_token ne ';' )
				  )
				{
					$self->_new_line( $token, $last );
				}
			}
		}

		$last = $self->_set_last( $token, $last );
		$pos++;
	}

	if ( $self->{'no_extra_line'} ) {
		$self->_new_line() if ( $self->{'content'} !~ /;$/s );
		$self->{'content'} =~ s/\s+$/\n/s;
	}
	else {
		$self->_new_line();
	}

	# Attempt to remove usless spaces
	$self->{'content'} =~ s/\s+CHECK\s+\(\s+/ CHECK (/igs;

	# Attempt to eliminate redundant parenthesis in DML queries
	if ( !$self->{'redundant_parenthesis'} ) {
		while ( $self->{'content'} =~
s/(\s+(?:WHERE|SELECT|FROM)\s+[^;]+)[\(]{2}([^\(\)]+)[\)]{2}([^;]+)/$1($2)$3/igs
		  )
		{
		}
	}

	return;
}

sub _lower {
	my ( $self, $token ) = @_;

	if ($DEBUG) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_ADD: line: $line => token=$token\n";
	}

	return lc($token);
}

=head2 _add_token

Add a token to the beautified string.

Code lifted from SQL::Beautify

=cut

sub _add_token {
	my ( $self, $token, $last_token ) = @_;

	if ($DEBUG) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_ADD: line: $line => last=", ( $last_token || '' ),
		  ", token=$token\n";
	}

	if ( $self->{'wrap'} ) {
		my $wrap;
		if ( $self->_is_keyword( $token, $self->_next_token(), $last_token ) ) {
			$wrap = $self->{'wrap'}->{'keywords'};
		}
		elsif ( $self->_is_constant($token) ) {
			$wrap = $self->{'wrap'}->{'constants'};
		}

		if ($wrap) {
			$token = $wrap->[0] . $token . $wrap->[1];
		}
	}

	if (    $self->{keep_newline}
		and $self->{'_is_in_block'} >= 0
		and $token =~ /^[\r\n]+$/s
		and defined $last_token
		and $last_token eq ';' )
	{
		$token =~ s/^[\r\n]+$/\n/s;
		$self->{'content'} =~ s/\s+$/\n/s;
		$self->{'content'} .= $token if ( $self->{'content'} !~ /[\n]{2,}$/s );
		return;
	}

	my $last_is_dot = defined($last_token) && $last_token eq '.';

	#$DEBUG_SP = 1;
	my $sp = $self->_indent;
	if ( !$self->_is_punctuation($token) and !$last_is_dot ) {
		if (   ( !defined($last_token) || $last_token ne '(' )
			&& $token ne ')'
			&& $token !~ /^::/ )
		{
			if (
				   $token ne ')'
				&& defined($last_token)
				&& $last_token !~ '::$'
				&& $last_token ne '['
				&& ( $token ne '(' || !$self->_is_type($last_token) )
				&& (   $token ne '('
					|| !$self->_is_function($last_token)
					|| $self->{'_is_in_type'} )
			  )
			{
				print STDERR "DEBUG_SPC: 1) last=", ( $last_token || '' ),
				  ", token=$token\n"
				  if ($DEBUG_SP);
				if (    ( $token !~ /PGFESCQ[12]/ or $last_token !~ /'$/ )
					and ( $last_token !~ /PGFESCQ[12]/ or $token !~ /^'/ ) )
				{
					if ( $token !~ /^['"].*['"]$/ or $last_token ne ':' ) {
						if ( $token =~ /AAKEYWCONST\d+AA\s+AAKEYWCONST\d+AA/ ) {
							$token =~ s/(AAKEYWCONST\d+AA)/$sp$1/gs;
						}
						else {
							$self->{'content'} .= $sp
							  if (
								  !$self->{'no_space_function'}
								or $token ne '('
								or (    !$self->{'_is_in_drop_function'}
									and !$self->{'_is_in_create_function'}
									and !$self->{'_is_in_trigger'} )
							  );
							if (
									$self->{'no_space_function'}
								and $token eq '('
								and (
									!$self->_is_keyword( $last_token, $token,
										undef )
									or $self->_is_type($last_token)
								)
							  )
							{
								$self->{'content'} =~ s/$sp$//s;
							}
						}
					}
				}
			}
			elsif ( !defined($last_token) && $token ) {
				print STDERR "DEBUG_SPC: 2) last=", ( $last_token || '' ),
				  ", token=$token\n"
				  if ($DEBUG_SP);
				$self->{'content'} .= $sp;
			}
			elsif ( $token eq '('
				and $self->{'_is_in_create'} == 2
				and $self->{'content'} !~ /$sp$/ )
			{
				print STDERR "DEBUG_SPC: 2b) last=", ( $last_token || '' ),
				  ", token=$token\n"
				  if ($DEBUG_SP);
				$self->{'content'} .= $sp;
			}
			elsif ( defined $last_token && $self->_is_comment($last_token) ) {
				print STDERR "DEBUG_SPC: 2c) last=", ( $last_token || '' ),
				  ", token=$token\n"
				  if ($DEBUG_SP);
				$self->{'content'} .= $sp;
			}
		}
		elsif (defined $last_token
			&& $last_token eq '('
			&& $token ne ')'
			&& $token !~ /^::/
			&& !$self->{'wrap_after'}
			&& $self->{'_is_in_with'} == 1 )
		{
			print STDERR "DEBUG_SPC: 3) last=", ( $last_token || '' ),
			  ", token=$token\n"
			  if ($DEBUG_SP);
			$self->{'content'} .= $sp;
		}
		elsif ( $self->{'_is_in_create'} == 2 && defined($last_token) ) {
			if (    $last_token ne '::'
				and !$self->{'_is_in_partition'}
				and !$self->{'_is_in_policy'}
				and !$self->{'_is_in_trigger'}
				and !$self->{'_is_in_aggregate'}
				and ( $last_token ne '(' || !$self->{'_is_in_index'} ) )
			{
				print STDERR "DEBUG_SPC: 4) last=", ( $last_token || '' ),
				  ", token=$token\n"
				  if ($DEBUG_SP);
				$self->{'content'} .= $sp
				  if ( $last_token ne '(' or !$self->{'_is_in_function'});
				if ($token =~ /^::/) {
					$self->{'content'} =~ s/$sp$//s;
				}
			}
		}
		elsif ( defined $last_token
			and ( !$self->{'_is_in_operator'} or !$self->{'_is_in_alter'} ) )
		{
			if (
				$last_token eq '('
				and (
					$self->{'_is_in_type'}
					or (
						$self->{'_is_in_operator'}
						and !$self->_is_type(
							$token, $last_token, $self->_next_token
						)
					)
				)
			  )
			{
				print STDERR "DEBUG_SPC: 5a) last=", ( $last_token || '' ),
				  ", token=$token\n"
				  if ($DEBUG_SP);
				$self->{'content'} .= $sp
				  if ( !$self->{'_is_in_type'} || $token !~ /^\d+$/ );
			}
			elsif ( $self->{'comma_break'}
				and $self->{'_current_sql_stmt'} eq 'INSERT' )
			{
				print STDERR "DEBUG_SPC: 5b) last=", ( $last_token || '' ),
				  ", token=$token\n"
				  if ($DEBUG_SP);
				$self->{'content'} .= $sp;
			}
		}
		elsif ( $token eq ')'
			and $self->{'_is_in_block'} >= 0 && $self->{'_is_in_create'} )
		{
			print STDERR "DEBUG_SPC: 6) last=", ( $last_token || '' ),
			  ", token=$token\n"
			  if ($DEBUG_SP);
			$self->{'content'} .= $sp;
		}
		else { 
			print STDERR "DEBUG_SPC: 7) last=", ( $last_token || '' ),
			  ", token=$token\n"
			  if ($DEBUG_SP);
		}

		if ( $self->_is_comment($token) ) {
			my @lines = split( /\n/, $token );
			for ( my $i = 1 ; $i <= $#lines ; $i++ ) {
				if ( $lines[$i] =~ /^\s*\*/ ) {
					$lines[$i] =~ s/^\s*\*/$sp */;
				}
				elsif ( $lines[$i] =~ /^\s+[^\*]/ ) {
					$lines[$i] =~ s/^\s+/$sp /;
				}
			}
			$token = join( "\n", @lines );
		}
		else {
			$token =~ s/\n/\n$sp/gs
			  if (  $self->{'_is_in_function'}
				and $self->{'_fct_code_delimiter'} eq "'" );
		}
	}

	my $next_token = $self->_next_token || '';
	my @cast       = ();
	my @next_cast  = ();

	# Be sure that we not going to modify a constant
	if ( $self->{'_is_in_create'} < 2 and $token !~ /^[E]*'.*'$/ ) {
		@cast       = split( /::/, $token, -1 );
		$token      = shift(@cast) if ( $#cast >= 0 );
		@next_cast  = split( /::/, $next_token );
		$next_token = shift(@next_cast) if ( $#next_cast >= 0 );
	}

	# lowercase/uppercase keywords taking care of function with same name
	if (
		$self->_is_keyword( $token, $next_token, $last_token )
		and (
			  !$self->_is_type($next_token)
			or $self->{'_is_in_create'} < 2
			or $self->{'_is_in_cast'}
			or
			( $self->{'_is_in_create'} == 2 and $token =~ /^(WITH|WITHOUT)$/i )
			or $self->{'_is_in_create_function'}
			or uc($token) eq 'AS'
		)
		and (  $next_token ne '('
			or ( defined $last_token and $last_token =~ /^(CREATE|ALTER)$/i )
			or !$self->_is_function($token) )
	  )
	{
		# Be sure that we are not formating with time zone
		if (   uc($token) ne 'WITH'
			or not defined $next_token
			or $next_token !~ /^(time|timestamp)$/i )
		{
			$token = lc($token)            if ( $self->{'uc_keywords'} == 1 );
			$token = uc($token)            if ( $self->{'uc_keywords'} == 2 );
			$token = ucfirst( lc($token) ) if ( $self->{'uc_keywords'} == 3 );
		}
	}
	else {
  # lowercase/uppercase known functions or words followed by an open parenthesis
  # if the token is not a keyword, an open parenthesis or a comment
		my $fct = $self->_is_function( $token, $last_token, $next_token ) || '';
		if ( $fct and
			((
				$next_token eq '('
				and defined $last_token
				and uc($last_token) ne 'CREATE'
			)
			or (    !$self->_is_keyword( $token, $next_token, $last_token )
				and $next_token ne '('
				and $token ne '('
				and !$self->_is_comment($token) ))
		  )
		{
			$token =~ s/$fct/\L$fct\E/i if ( $self->{'uc_functions'} == 1 );
			$token =~ s/$fct/\U$fct\E/i if ( $self->{'uc_functions'} == 2 );
			$fct = ucfirst( lc($fct) );
			$token =~ s/$fct/$fct/i if ( $self->{'uc_functions'} == 3 );
		}

		# case of (NEW|OLD).colname keyword that need to formatted too
		if (
			(
				   $self->{'_is_in_create_function'}
				or $self->{'_fct_code_delimiter'}
				or $self->{'_is_in_rule'}
			)
			and $token =~ /^(NEW|OLD)\./i
		  )
		{
			$token =~ s/^(OLD|NEW)\./\L$1\E\./i
			  if ( $self->{'uc_keywords'} == 1 );
			$token =~ s/^(OLD|NEW)\./\U$1\E\./i
			  if ( $self->{'uc_keywords'} == 2 );
			$token =~ s/^OLD\./\UOld\E\./i if ( $self->{'uc_keywords'} == 3 );
			$token =~ s/^NEW\./\UNew\E\./i if ( $self->{'uc_keywords'} == 3 );
		}
	}

	my $tk_is_type = $self->_is_type( $token, $last_token, $next_token );

	if ( $token =~ /^(AT|SET)$/i ) {
		$self->{'_not_a_type'} = 1;
	}
	elsif ( !$tk_is_type ) {
		$self->{'_not_a_type'} = 0;
	}

	# Type are always lowercase
	if (
		!$self->{'_not_a_type'}
		and (  $self->{'_is_in_create'}
			or $self->{'_is_in_declare'}
			or $self->{'_is_in_cast'}
			or $self->{'_is_in_type'}
			or $self->{'_is_in_alter'} )
	  )
	{
		if (
			$tk_is_type and defined $last_token
			or (    $token =~ /^(WITH|WITHOUT)$/i
				and $next_token =~ /^(time|timestamp)$/i )
		  )
		{
			if (   $last_token =~ /^(AS|RETURNS|INOUT|IN|OUT)$/i
				or !$self->_is_keyword($last_token)
				or $self->_is_type($last_token)
				or $self->_is_type($next_token) )
			{
				$token = lc($token)            if ( $self->{'uc_types'} == 1 );
				$token = uc($token)            if ( $self->{'uc_types'} == 2 );
				$token = ucfirst( lc($token) ) if ( $self->{'uc_types'} == 3 );
			}
		}
	}

	# Add formatting for HTML output
	if ( $self->{'colorize'} && $self->{'format'} eq 'html' ) {
		$token = $self->highlight_code( $token, $last_token, $next_token );
	}

	foreach my $c (@cast) {
		my @words = split( /(\s+)/, $c );
		$c = '';
		foreach my $w (@words) {
			if ( !$self->_is_type($token) ) {
				$c .= $w;
			}
			else {
				$c .= lc($w)            if ( $self->{'uc_types'} == 1 );
				$c .= uc($w)            if ( $self->{'uc_types'} == 2 );
				$c .= ucfirst( lc($w) ) if ( $self->{'uc_types'} == 3 );
			}
		}
		$token .= '::' . $c;
	}

	# Format cast in function code
	my $reg = join( '|', @{ $self->{'types'} } );
	$reg =
'(?:TIMESTAMP(\s*\(\s*\d+\s*\))? WITH TIME ZONE|TIMESTAMP(\s*\(\s*\d+\s*\))? WITHOUT TIME ZONE|CHARACTER VARYING|'
	  . $reg . ')';
	if ( $token =~ /::/ ) {
		$token =~ s/::($reg)/'::' . lc($1)/igse if ( $self->{'uc_types'} == 1 );
		$token =~ s/::($reg)/'::' . uc($1)/igse if ( $self->{'uc_types'} == 2 );
		$token =~ s/::($reg)/'::' . ucfirst(lc($1))/igse
		  if ( $self->{'uc_types'} == 3 );
	}

	# special case for MySQL
	if ( $token =~ /^(;|\$\$|\/\/)$/ and $self->{'content'} =~ /DELIMITER\s*$/ )
	{
		$self->{'content'} .= ' ' if ( $self->{'content'} !~ /DELIMITER\s$/ );
	}
	$self->{'content'} .= $token;

	# This can't be the beginning of a new line anymore.
	$self->{'_new_line'} = 0;
}

=head2 _over

Increase the indentation level.

Code lifted from SQL::Beautify

=cut

sub _over {
	my ( $self, $token, $last ) = @_;

	if ($DEBUG) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_OVER: line: $line => last=$last, token=$token\n";
	}
	++$self->{'_level'};
}

=head2 _back

Decrease the indentation level.

Code lifted from SQL::Beautify

=cut

sub _back {
	my ( $self, $token, $last ) = @_;

	if ($DEBUG) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_BACK: line: $line => last=$last, token=$token\n";
	}
	--$self->{'_level'} if ( $self->{'_level'} > 0 );
}

=head2 _indent

Return a string of spaces according to the current indentation level and the
spaces setting for indenting.

Code lifted from SQL::Beautify

=cut

sub _indent {
	my ($self) = @_;

	if ( $self->{'_new_line'} ) {
		return $self->{'space'} x
		  ( $self->{'spaces'} * ( $self->{'_level'} // 0 ) );
	}

	# When this is not for identation force using space
	else {
		return ' ';
	}
}

=head2 _new_line

Add a line break, but make sure there are no empty lines.

Code lifted from SQL::Beautify

=cut

sub _new_line {
	my ( $self, $token, $last ) = @_;

	if ( $DEBUG and defined $token ) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_NL: line: $line => last=", ( $last || '' ),
		  ", token=$token\n";
	}

	$self->{'content'} .= $self->{'break'} unless ( $self->{'_new_line'} );
	$self->{'_new_line'} = 1;
}

=head2 _next_token

Have a look at the token that's coming up next.

Code lifted from SQL::Beautify

=cut

sub _next_token {
	my ($self) = @_;

	return @{ $self->{'_tokens'} } ? $self->{'_tokens'}->[0] : undef;
}

=head2 _next_token_skip_comment

Have a look at the token that's coming up next omitting comments.

Code lifted from SQL::Beautify

=cut

sub _next_token_skip_comment {
	my ($self) = @_;

	for ( my $i = 0 ; $i <= $#{ $self->{'_tokens'} } ; $i++ ) {
		next if ( $self->{'_tokens'}->[$i] =~ /^\s*(--|\/\*)/ );
		return $self->{'_tokens'}->[$i];
	}

	return undef;
}

=head2 _token

Get the next token, removing it from the list of remaining tokens.

Code lifted from SQL::Beautify

=cut

sub _token {
	my ($self) = @_;

	return shift @{ $self->{'_tokens'} };
}

=head2 _is_keyword

Check if a token is a known SQL keyword.

Code lifted from SQL::Beautify

=cut

sub _is_keyword {
	my ( $self, $token, $next_token, $last_token ) = @_;

	if ($DEBUG) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_KEYWORD: line: $line => last=",
		  ( $last_token || '' ), ", token=$token\n";
	}

	return 0 if ( !$token );

	# Remove cast if any
	$token =~ s/::[^:]+$//;

	$next_token //= '';

	# Fix some false positive
	if ( defined $next_token ) {
		return 0 if ( uc($token) eq 'LEVEL' and uc($next_token) ne 'SECURITY' );
		return 0 if ( uc($token) eq 'EVENT' and uc($next_token) ne 'TRIGGER' );
		return 0
		  if (  $self->{'_current_sql_stmt'} =~ /(INSERT|UPDATE)/
			and $next_token =~ /^[,\)=]$/
			and ( not defined $last_token or $last_token =~ /^[,\(]$/ )
			and $token !~
			/^(TRUE|FALSE|DEFAULT|NULL|CURRENT_.*|LEXIZE|END)$/i );
	}
	return 0
	  if (  $token =~ /^(LOGIN|RULE)$/i
		and !$self->{'_is_in_create'}
		and !$self->{'_is_in_alter'}
		and !$self->{'_is_in_drop'}
		and !$self->{'_is_in_rule'} );
	return 0
	  if ( uc($token) eq 'COMMENT'
		and ( not defined $next_token or $next_token ) !~ /^ON|IS$/i );

	if ( defined $last_token ) {
		return 0
		  if ( uc($token) eq 'KEY'
			and $last_token !~ /^(PRIMARY|FOREIGN|PARTITION|NO)$/i );
		return 0
		  if (  $token =~ /^(BTREE|HASH|GIST|SPGIST|GIN|BRIN)$/i
			and $last_token !~ /^(USING|BY)$/i );
		return 0 if ( uc($token) eq 'NOTICE' and uc($last_token) ne 'RAISE' );
		return 0
		  if ( ( $self->{'_is_in_type'} or $self->{'_is_in_create'} )
			and $last_token =~ /^(OF|FROM)$/i );
		return 0
		  if ( uc($last_token) eq 'AS'
			and $token !~
/^(IDENTITY|SELECT|ENUM|TRANSACTION|UPDATE|DELETE|INSERT|MATERIALIZED|ON|VALUES|RESTRICTIVE|PERMISSIVE|UGLY|EXECUTE|STORAGE|OPERATOR|RANGE|NOT)$/i
		  );
		return 0
		  if (  $token =~ /^(TYPE|SCHEMA)$/i
			and $last_token =~ /^(COLUMN|\(|,|\||\))/i );
		return 0
		  if (  $token =~ /^TYPE$/i
			and $last_token !~ /^(CREATE|DROP|ALTER|FOR)$/i
			and !$self->{'_is_in_alter'}
			and !grep( { uc($_) eq uc($next_token) } @{ $self->{'types'} } ) );
	}

	if (    $DEBUG
		and defined $token
		and grep { $_ eq uc($token) } @{ $self->{'keywords'} } )
	{
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_KEYWORD: line: $line => last=",
		  ( $last_token || '' ), ", token=$token, next=",
		  ( $next_token || '' ), "\n";
	}

	return ~~ grep { $_ eq uc($token) } @{ $self->{'keywords'} };
}

=head2 _is_type

Check if a token is a known SQL type

=cut

sub _is_type {
	my ( $self, $token, $last_token, $next_token ) = @_;

	return if ( !defined $token );
	return if ( defined $next_token and $next_token =~ /^(SEARCH)$/i );

	if ( $DEBUG and defined $token ) {
		my ( $package, $filename, $line ) = caller;
		print STDERR "DEBUG_TYPE: line: $line => token=[$token], last=",
		  ( $last_token || '' ), ", next=", ( $next_token || '' ), ", type=",
		  ( grep { uc($_) eq uc($token) } @{ $self->{'types'} } ), "\n";
	}

	return 0
	  if ( $token =~ /^(int4|int8|num|tstz|ts|date)range$/i
		and ( not defined $next_token or $next_token eq '(' ) );

	my @composite_types = ( 'VARYING', 'PRECISION', 'WITH', 'WITHOUT', 'ZONE' );

	# Typically case of a data type used as an object name
	if ( defined $next_token ) {
		if (    grep { $_ eq uc($token) } @{ $self->{'types'} }
			and grep  { $_ eq uc($next_token) } @{ $self->{'types'} }
			and !grep { $_ eq uc($next_token) } @composite_types )
		{
			return 0;
		}
	}

	$token =~ s/\s*\(.*//;    # remove any parameter to the type
	return ~~ grep { $_ eq uc($token) } @{ $self->{'types'} };
}

sub _is_sql_keyword {
	my ( $self, $token ) = @_;

	return ~~ grep { $_ eq uc($token) } @{ $self->{'sql_keywords'} };
}

=head2 _is_comment

Check if a token is a SQL or C style comment

=cut

sub _is_comment {
	my ( $self, $token ) = @_;

	return 1 if ( $token =~ m#^\s*((?:--)[\ \t\S]*|/\*[\ \t\r\n\S]*?\*/)$#s );

	return 0;
}

=head2 _is_function

Check if a token is a known SQL function.

Code lifted from SQL::Beautify and rewritten to check one long regexp instead of a lot of small ones.

=cut

sub _is_function {
	my ( $self, $token, $last_token, $next_token ) = @_;

	return undef if ( !$token );

	if ( $token =~ $self->{'functions_re'} ) {

		# Check the context of the function
		if ( defined $last_token and defined $next_token ) {
			return undef if ( $next_token ne '(' );
			return undef if ( $self->{'_is_in_create'} == 1 );
		}
		return $1;
	}
	else {
		return undef;
	}
}

=head2 add_keywords

Add new keywords to highlight.

Code lifted from SQL::Beautify

=cut

sub add_keywords {
	my $self = shift;

	for my $keyword (@_) {
		push @{ $self->{'keywords'} }, ref($keyword) ? @{$keyword} : $keyword;
	}
}

=head2 _re_from_list

Create compiled regexp from prefix, suffix and and a list of values to match.

=cut

sub _re_from_list {
	my $prefix = shift;
	my $suffix = shift;
	my ( @joined_list, $ret_re );

	for my $list_item (@_) {
		push @joined_list, ref($list_item) ? @{$list_item} : $list_item;
	}

	$ret_re = "$prefix(" . join( '|', @joined_list ) . ")$suffix";

	return qr/$ret_re/i;
}

=head2 _refresh_functions_re

Refresh compiled regexp for functions.

=cut

sub _refresh_functions_re {
	my $self = shift;
	$self->{'functions_re'} =
	  _re_from_list( '\b[\.]*', '$', @{ $self->{'functions'} } );
}

=head2 add_functions

Add new functions to highlight.

Code lifted from SQL::Beautify

=cut

sub add_functions {
	my $self = shift;

	for my $function (@_) {
		push @{ $self->{'functions'} },
		  ref($function) ? @{$function} : $function;
	}

	$self->_refresh_functions_re();
}

=head2 add_rule

Add new rules.

Code lifted from SQL::Beautify

=cut

sub add_rule {
	my ( $self, $format, $token ) = @_;

	my $rules = $self->{'rules'}  ||= {};
	my $group = $rules->{$format} ||= [];

	push @{$group}, ref($token) ? @{$token} : $token;
}

=head2 _get_rule

Find custom rule for a token.

Code lifted from SQL::Beautify

=cut

sub _get_rule {
	my ( $self, $token ) = @_;

	values %{ $self->{'rules'} };    # Reset iterator.

	while ( my ( $rule, $list ) = each %{ $self->{'rules'} } ) {
		return $rule if ( grep { uc($token) eq uc($_) } @$list );
	}

	return;
}

=head2 _process_rule

Applies defined rule.

Code lifted from SQL::Beautify

=cut

sub _process_rule {
	my ( $self, $rule, $token ) = @_;

	my $format = {
		break => sub { $self->_new_line() },
		over  => sub { $self->_over() },
		back  => sub { $self->_back() },
		token => sub { $self->_add_token($token) },
		push  => sub { push @{ $self->{'_level_stack'} }, $self->{'_level'} },
		pop   => sub { $self->{'_level'} = $self->_pop_level( $token, '' ) },
		reset =>
		  sub { $self->{'_level'} = 0; @{ $self->{'_level_stack'} } = (); },
	};

	for ( split /-/, lc $rule ) {
		&{ $format->{$_} } if ( $format->{$_} );
	}
}

=head2 _is_constant

Check if a token is a constant.

Code lifted from SQL::Beautify

=cut

sub _is_constant {
	my ( $self, $token ) = @_;

	return ( $token =~ /^\d+$/ or $token =~ /^(['"`]).*\1$/ );
}

=head2 _is_punctuation

Check if a token is punctuation.

Code lifted from SQL::Beautify

=cut

sub _is_punctuation {
	my ( $self, $token ) = @_;
	if ( $self->{'comma'} eq 'start' and $token eq ',' ) {
		return 0;
	}
	return ( $token =~ /^[,;.\[\]]$/ );
}

=head2 _generate_anonymized_string

Simply generate a random string, thanks to Perlmonks.

Returns original in certain cases which don't require anonymization, like
timestamps, or intervals.

=cut

sub _generate_anonymized_string {
	my $self = shift;
	my ( $before, $original, $after ) = @_;

	# Prevent dates from being anonymized
	return $original if $original =~ m{\A\d\d\d\d[/:-]\d\d[/:-]\d\d\z};
	return $original if $original =~ m{\A\d\d[/:-]\d\d[/:-]\d\d\d\d\z};

	# Prevent dates format like DD/MM/YYYY HH24:MI:SS from being anonymized
	return $original if $original =~ m{
        \A
        (?:FM|FX|TM)?
        (?:
            HH | HH12 | HH24
            | MI
            | SS
            | MS
            | US
            | SSSS
            | AM | A\.M\. | am | a\.m\.
            | PM | P\.M\. | pm | p\.m\.
            | Y,YYY | YYYY | YYY | YY | Y
            | IYYY | IYY | IY | I
            | BC | B\.C\. | bc | b\.c\.
            | AD | A\.D\. | ad | a\.d\.
            | MONTH | Month | month | MON | Mon | mon | MM
            | DAY | Day | day | DY | Dy | dy | DDD | DD | D
            | W | WW | IW
            | CC
            | J
            | Q
            | RM | rm
            | TZ | tz
            | [\s/:-]
        )+
        (?:TH|th|SP)?
        \z
    };

	# Prevent interval from being anonymized

	return $original if ( $before && ( $before =~ /interval/i ) );
	return $original if ( $after  && ( $after  =~ /^\)*::interval/i ) );

	# Shortcut
	my $cache = $self->{'_anonymization_cache'};

	# Range of characters to use in anonymized strings
	my @chars = ( 'A' .. 'Z', 0 .. 9, 'a' .. 'z', '-', '_', '.' );

	unless ( $cache->{$original} ) {

		# Actual anonymized version generation
		$cache->{$original} = join( '', map { $chars[ rand @chars ] } 1 .. 10 );
	}

	return $cache->{$original};
}

=head2 anonymize

Anonymize litteral in SQL queries by replacing parameters with fake values

=cut

sub anonymize {
	my $self  = shift;
	my $query = $self->{'query'};

	# just in case it has not been called in the main script
	$query = $self->query() if ( !$query );

	return if ( !$query );

	# Variable to hold anonymized versions, so we can provide the same value
	# for the same input, within single query.
	$self->{'_anonymization_cache'} = {};

	# Remove comments
	$query =~ s/\/\*(.*?)\*\///gs;

	# Clean query
	$query =~ s/\\'//gs;
	$query =~ s/('')+/\$EMPTYSTRING\$/gs;

	# Anonymize each values
	$query =~ s{
        ([^\s\']+[\s\(]*)       # before
        '([^']*)'               # original
        ([\)]*::\w+)?           # after
    }{$1 . "'" . $self->_generate_anonymized_string($1, $2, $3) . "'" . ($3||'')}xeg;

	$query =~ s/\$EMPTYSTRING\$/''/gs;

	foreach my $k ( keys %{ $self->{'keyword_constant'} } ) {
		$self->{'keyword_constant'}{$k} = "'"
		  . $self->_generate_anonymized_string( '',
			$self->{'keyword_constant'}{$k}, '' )
		  . "'";
	}

	$self->query($query);
}

=head2 set_defaults

Sets defaults for newly created objects.

Currently defined defaults:

=over

=item spaces => 4

=item space => ' '

=item break => "\n"

=item uc_keywords => 2

=item uc_functions => 0

=item uc_types => 1

=item no_comments => 0

=item no_grouping => 0

=item placeholder => ''

=item multiline => 0

=item separator => ''

=item comma => 'end'

=item format => 'text'

=item colorize => 1

=item format_type => 0

=item wrap_limit => 0

=item wrap_after => 0

=item wrap_comment => 0

=item no_extra_line => 0

=item keep_newline => 0

=item no_space_function => 0

=item redundant_parenthesis => 0

=back

=cut

sub set_defaults {
	my $self = shift;
	$self->set_dicts();

	# Set some defaults.
	$self->{'query'}        = '';
	$self->{'spaces'}       = 4;
	$self->{'space'}        = ' ';
	$self->{'break'}        = "\n";
	$self->{'wrap'}         = {};
	$self->{'rules'}        = {};
	$self->{'uc_keywords'}  = 2;
	$self->{'uc_functions'} = 0;
	$self->{'uc_types'}     = 1;
	$self->{'no_comments'}  = 0;
	$self->{'no_grouping'}  = 0;
	$self->{'placeholder'}  = '';
	$self->{'multiline'}    = 0;
	$self->{'keywords'}     = $self->{'dict'}->{'pg_keywords'};
	$self->{'types'}        = $self->{'dict'}->{'pg_types'};
	$self->{'functions'}    = ();
	push(
		@{ $self->{'functions'} },
		keys %{ $self->{'dict'}->{'pg_functions'} }
	);
	$self->_refresh_functions_re();
	$self->{'separator'}             = '';
	$self->{'comma'}                 = 'end';
	$self->{'format'}                = 'text';
	$self->{'colorize'}              = 1;
	$self->{'format_type'}           = 0;
	$self->{'wrap_limit'}            = 0;
	$self->{'wrap_after'}            = 0;
	$self->{'wrap_comment'}          = 0;
	$self->{'no_extra_line'}         = 0;
	$self->{'keep_newline'}          = 0;
	$self->{'no_space_function'}     = 0;
	$self->{'redundant_parenthesis'} = 0;

	return;
}

=head2 format

Set output format - possible values: 'text' and 'html'

Default is text output. Returns 0 in case or wrong format and use default.

=cut

sub format {
	my $self   = shift;
	my $format = shift;

	if ( grep( /^$format$/i, 'text', 'html' ) ) {
		$self->{'format'} = lc($format);
		return 1;
	}
	return 0;
}

=head2 set_dicts

Sets various dictionaries (lists of keywords, functions, symbols, and the like)

This was moved to separate function, so it can be put at the very end of module
so it will be easier to read the rest of the code.

=cut

sub set_dicts {
	my $self = shift;

# First load it all as "my" variables, to make it simpler to modify/map/grep/add
# Afterwards, when everything is ready, put it in $self->{'dict'}->{...}

	my @pg_keywords = map { uc } qw(
	  ADD AFTER AGGREGATE ALL ALSO ALTER ALWAYS ANALYSE ANALYZE AND ANY ARRAY AS ASC ASYMMETRIC ATOMIC AUTHORIZATION ATTACH AUTO_INCREMENT
	  BACKWARD BEFORE BEGIN BERNOULLI BETWEEN BINARY BOTH BY CACHE CASCADE CASE CAST CHECK CHECKPOINT CLOSE CLUSTER
	  COLLATE COLLATION COLUMN COMMENT COMMIT COMMITTED CONCURRENTLY CONFLICT CONSTRAINT CONSTRAINT CONTINUE COPY
	  COST COSTS CREATE CROSS CUBE CURRENT CURRENT_DATE CURRENT_ROLE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR
	  CYCLE DATABASE DEALLOCATE DECLARE DEFAULT DEFERRABLE DEFERRED DEFINER DELETE DELIMITER DESC DETACH DISABLE DISTINCT
	  DO DOMAIN DROP EACH ELSE ELSIF ENABLE ENCODING END EVENT EXCEPTION EXCEPT EXCLUDE EXCLUDING EXECUTE EXISTS EXPLAIN EXTENSION FALSE FETCH FILTER
	  FIRST FOLLOWING FOR FOREIGN FORWARD FREEZE FROM FULL FUNCTION GENERATED GRANT GROUP GROUPING HAVING HASHES HASH
	  IDENTITY IF ILIKE IMMUTABLE IN INCLUDING INCREMENT INDEX INHERITS INITIALLY INNER INOUT INSERT INSTEAD
	  INTERSECT INTO INVOKER IS ISNULL ISOLATION JOIN KEY LANGUAGE LAST LATERAL LC_COLLATE LC_CTYPE LEADING
	  LEAKPROOF LEFT LEFTARG LEVEL LEXIZE LIKE LIMIT LIST LISTEN LOAD LOCALTIME LOCALTIMESTAMP LOCK LOCKED LOGGED LOGIN
	  LOOP MAPPING MATCH MAXVALUE MERGES MINVALUE MODULUS MOVE NATURAL NEXT NOTHING NOTICE ORDINALITY
	  NO NOCREATEDB NOCREATEROLE NOSUPERUSER NOT NOTIFY NOTNULL NOWAIT NULL OFFSET OFF OF OIDS ON ONLY OPEN OPERATOR OR ORDER
	  OUTER OVER OVERLAPS OWNER PARTITION PASSWORD PERFORM PLACING POLICY PRECEDING PREPARE PRIMARY PROCEDURE RANGE
	  REASSIGN RECURSIVE REFERENCES REINDEX REMAINDER RENAME REPEATABLE REPLACE REPLICA RESET RESTART RESTRICT RETURN RETURNING
	  RETURNS REVOKE RIGHT RIGHTARG ROLE ROLLBACK ROLLUP ROWS ROW RULE SAVEPOINT SCHEMA SCROLL SECURITY SELECT SEQUENCE
	  SEQUENCE SERIALIZABLE SERVER SESSION_USER SET SETOF SETS SHOW SIMILAR SKIP SNAPSHOT SOME STABLE START STRICT
	  SYMMETRIC SYSTEM TABLE TABLESAMPLE TABLESPACE TEMPLATE TEMPORARY THEN TO TRAILING TRANSACTION TRIGGER TRUE
	  TRUNCATE TYPE UNBOUNDED UNCOMMITTED UNION UNIQUE UNLISTEN UNLOCK UNLOGGED UPDATE USER USING VACUUM VALUES
	  VARIADIC VERBOSE VIEW VOLATILE WHEN WHERE WINDOW WITH WITHIN WORK XOR ZEROFILL
	  CALL GROUPS INCLUDE OTHERS PROCEDURES ROUTINE ROUTINES TIES READ_ONLY SHAREABLE READ_WRITE
	  BASETYPE SFUNC STYPE SFUNC1 STYPE1 SSPACE FINALFUNC FINALFUNC_EXTRA FINALFUNC_MODIFY COMBINEFUNC SERIALFUNC DESERIALFUNC
	  INITCOND MSFUNC MINVFUNC MSTYPE MSSPACE MFINALFUNC MFINALFUNC_EXTRA MFINALFUNC_MODIFY MINITCOND SORTOP
	  STORED REFRESH MATERIALIZED RAISE WITHOUT
	);

	my @pg_types = qw(
	  BIGINT BIGSERIAL BIT BOOLEAN BOOL BOX BYTEA CHARACTER CHAR CIDR CIRCLE DATE DOUBLE INET INTEGER INTERVAL
	  JSONB JSON LINE LSEG MACADDR8 MACADDR MONEY NUMERIC OID PG_LSN POINT POLYGON PRECISION REAL SMALLINT SMALLSERIAL
	  SERIAL TEXT TIMESTAMPTZ TIMESTAMP TSQUERY TSVECTOR TXID_SNAPSHOT UUID XML VARYING VARCHAR ZONE FLOAT4
	  FLOAT8 FLOAT NAME TID INT4RANGE INT8RANGE NUMRANGE TSRANGE TSTZRANGE DATERANGE INT2 INT4 INT8 INT TIME
	  REGCLASS REGCONFIG REGDICTIONARY REGNAMESPACE REGOPER REGOPERATOR REGPROC REGPROCEDURE REGROLE REGTYPE
	);

	my @sql_keywords = map { uc } qw(
	  ABORT ABSOLUTE ACCESS ACTION ADMIN ALSO ALWAYS ASSERTION ASSIGNMENT AT ATTRIBUTE BIGINT BOOLEAN
	  CALLED CASCADED CATALOG CHAIN CHANGE CHARACTER CHARACTERISTICS COLUMNS COMMENTS CONFIGURATION
	  CONNECTION CONSTRAINTS CONTENT CONVERSION CSV CURRENT DATA DATABASES DAY DEC DECIMAL DEFAULTS DELAYED
	  DELIMITERS DESCRIBE DICTIONARY DISABLE DISCARD DOCUMENT DOUBLE ENABLE ENCLOSED ENCRYPTED ENUM ESCAPE ESCAPED
	  EXCLUSIVE EXTERNAL FIELD FIELDS FLOAT FLUSH FOLLOWING FORCE FUNCTIONS GLOBAL GRANTED GREATEST HANDLER
	  HEADER HOLD HOUR IDENTIFIED IGNORE IMMEDIATE IMPLICIT INDEXES INFILE INHERIT INLINE INPUT INSENSITIVE
	  INT INTEGER KEYS KILL LABEL LARGE LEAST LEVEL LINES LOCAL LOW_PRIORITY MATCH MINUTE MODE MODIFY MONTH NAMES
	  NATIONAL NCHAR NONE NOTHING NULLIF NULLS OBJECT OFF OPERATOR OPTIMIZE OPTION OPTIONALLY OPTIONS OUT OUTFILE
	  OWNED PARSER PARTIAL PASSING PLANS PRECISION PREPARED PRESERVE PRIOR PRIVILEGES PROCEDURAL QUOTE READ
	  REAL RECHECK REF REGEXP RELATIVE RELEASE RLIKE ROW SEARCH SECOND SEQUENCES SESSION SHARE SIMPLE
	  SMALLINT SONAME STANDALONE STATEMENT STATISTICS STATUS STORAGE STRAIGHT_JOIN SYSID TABLES TEMP TERMINATED
	  TREAT TRUSTED TYPES UNENCRYPTED UNKNOWN UNSIGNED UNTIL USE VALID VALIDATE VALIDATOR VALUE VARIABLES VARYING
	  WHITESPACE WORK WRAPPER WRITE XMLATTRIBUTES YEAR YES ZONE
	);

	my @redshift_keywords = map { uc } qw(
	  AES128 AES256 ALLOWOVERWRITE BACKUP BLANKSASNULL BYTEDICT BZIP2 CREDENTIALS CURRENT_USER_ID DEFLATE DEFRAG
	  DELTA DELTA32K DISABLE DISTKEY EMPTYASNULL ENABLE ENCODE ENCRYPT ENCRYPTION ESCAPE EXPLICIT GLOBALDICT256
	  GLOBALDICT64K GZIP INTERLEAVED LUN LUNS LZO LZOP MINUS MOSTLY13 MOSTLY32 MOSTLY8 NEW OFFLINE OFFSET OLD OID
	  PARALLEL PERCENT PERMISSIONS RAW READRATIO RECOVER REJECTLOG RESORT RESPECT RESTORE SORTKEY SYSDATE TAG TDES
	  TEXT255 TEXT32K TIMESTAMP TOP TRUNCATECOLUMNS UNLOAD WALLET ADDQUOTES
	);

	for my $k (@pg_keywords) {
		next if grep { $k eq $_ } @sql_keywords;
		push @sql_keywords, $k;
	}

	my @pg_functions = map { lc } qw(
	  ascii age bit_length btrim cardinality cast char_length character_length coalesce
	  brin_summarize_range brin_summarize_new_values
	  convert chr current_date current_time current_timestamp count decode date_part date_trunc
	  encode extract get_byte get_bit initcap isfinite interval justify_hours justify_days
	  lower length lpad ltrim localtime localtimestamp md5 now octet_length overlay position pg_client_encoding
	  quote_ident quote_literal repeat replace rpad rtrim substring split_part strpos substr set_byte set_bit
	  trim to_ascii to_hex translate to_char to_date to_timestamp to_number timeofday upper
	  abbrev abs abstime abstimeeq abstimege abstimegt abstimein abstimele
	  abstimelt abstimene abstimeout abstimerecv abstimesend aclcontains acldefault
	  aclexplode aclinsert aclitemeq aclitemin aclitemout aclremove acos
	  any_in any_out anyarray_in anyarray_out anyarray_recv anyarray_send anyelement_in
	  anyelement_out anyenum_in anyenum_out anynonarray_in anynonarray_out anyrange_in anyrange_out
	  anytextcat area areajoinsel areasel armor array_agg array_agg_finalfn
	  array_agg_transfn array_append array_cat array_dims array_eq array_fill array_ge array_positions
	  array_gt array_in array_larger array_le array_length array_lower array_lt array_position
	  array_ndims array_ne array_out array_prepend array_recv array_remove array_replace array_send array_smaller
	  array_to_json array_to_string array_typanalyze array_upper arraycontained arraycontains arraycontjoinsel
	  arraycontsel arrayoverlap ascii_to_mic ascii_to_utf8 asin atan atan2
	  avg big5_to_euc_tw big5_to_mic big5_to_utf8 bit bit_and bit_in
	  bit_or bit_out bit_recv bit_send bitand bitcat bitcmp
	  biteq bitge bitgt bitle bitlt bitne bitnot
	  bitor bitshiftleft bitshiftright bittypmodin bittypmodout bitxor bool
	  bool_and bool_or booland_statefunc boolean booleq boolge boolgt boolin
	  boolle boollt boolne boolor_statefunc boolout boolrecv boolsend
	  box box_above box_above_eq box_add box_below box_below_eq box_center
	  box_contain box_contain_pt box_contained box_distance box_div box_eq box_ge
	  box_gt box_in box_intersect box_le box_left box_lt box_mul
	  box_out box_overabove box_overbelow box_overlap box_overleft box_overright box_recv
	  box_right box_same box_send box_sub bpchar bpchar_larger bpchar_pattern_ge
	  bpchar_pattern_gt bpchar_pattern_le bpchar_pattern_lt bpchar_smaller bpcharcmp bpchareq bpcharge
	  bpchargt bpchariclike bpcharicnlike bpcharicregexeq bpcharicregexne bpcharin bpcharle
	  bpcharlike bpcharlt bpcharne bpcharnlike bpcharout bpcharrecv bpcharregexeq
	  bpcharregexne bpcharsend bpchartypmodin bpchartypmodout broadcast btabstimecmp btarraycmp
	  btbeginscan btboolcmp btbpchar_pattern_cmp btbuild btbuildempty btbulkdelete btcanreturn
	  btcharcmp btcostestimate btendscan btfloat48cmp btfloat4cmp btfloat4sortsupport btfloat84cmp
	  btfloat8cmp btfloat8sortsupport btgetbitmap btgettuple btinsert btint24cmp btint28cmp
	  btint2cmp btint2sortsupport btint42cmp btint48cmp btint4cmp btint4sortsupport btint82cmp
	  btint84cmp btint8cmp btint8sortsupport btmarkpos btnamecmp btnamesortsupport btoidcmp
	  btoidsortsupport btoidvectorcmp btoptions btrecordcmp btreltimecmp btrescan btrestrpos
	  bttext_pattern_cmp bttextcmp bttidcmp bttintervalcmp btvacuumcleanup bytea_string_agg_finalfn
	  bytea_string_agg_transfn byteacat byteacmp byteaeq byteage byteagt byteain byteale
	  bytealike bytealt byteane byteanlike byteaout bytearecv byteasend
	  cash_cmp cash_div_cash cash_div_flt4 cash_div_flt8 cash_div_int2 cash_div_int4 cash_eq
	  cash_ge cash_gt cash_in cash_le cash_lt cash_mi cash_mul_flt4
	  cash_mul_flt8 cash_mul_int2 cash_mul_int4 cash_ne cash_out cash_pl cash_recv
	  cash_send cash_words cashlarger cashsmaller cbrt ceil ceiling
	  center char chareq charge chargt charin charle
	  charlt charne charout charrecv charsend cideq cidin
	  cidout cidr cidr_in cidr_out cidr_recv cidr_send cidrecv
	  cidsend circle circle_above circle_add_pt circle_below circle_center circle_contain
	  circle_contain_pt circle_contained circle_distance circle_div_pt circle_eq circle_ge circle_gt
	  circle_in circle_le circle_left circle_lt circle_mul_pt circle_ne circle_out
	  circle_overabove circle_overbelow circle_overlap circle_overleft circle_overright circle_recv circle_right
	  circle_same circle_send circle_sub_pt clock_timestamp close_lb close_ls close_lseg
	  close_pb close_pl close_ps close_sb close_sl col_description concat
	  concat_ws contjoinsel contsel convert_from convert_to corr cos
	  cot covar_pop covar_samp crypt cstring_in cstring_out cstring_recv
	  cstring_send cume_dist current_database current_query current_schema current_schemas current_setting
	  current_user currtid currtid2 currval date date_cmp date_cmp_timestamp date_cmp_timestamptz date_eq
	  date_eq_timestamp date_eq_timestamptz date_ge date_ge_timestamp date_ge_timestamptz date_gt date_gt_timestamp
	  date_gt_timestamptz date_in date_larger date_le date_le_timestamp date_le_timestamptz date_lt
	  date_lt_timestamp date_lt_timestamptz date_mi date_mi_interval date_mii date_ne date_ne_timestamp
	  date_ne_timestamptz date_out date_pl_interval date_pli date_recv date_send date_smaller
	  date_sortsupport daterange daterange_canonical daterange_subdiff datetime_pl datetimetz_pl
	  dblink_connect_u dblink_connect dblink_disconnect dblink_exec dblink_open dblink_fetch dblink_close
	  dblink_get_connections dblink_error_message dblink_send_query dblink_is_busy dblink_get_notify
	  dblink_get_result dblink_cancel_query dblink_get_pkey dblink_build_sql_insert dblink_build_sql_delete
	  dblink_build_sql_update dblink dcbrt dearmor decrypt decrypt_iv degrees dense_rank dexp diagonal
	  decimal diameter digest dispell_init dispell_lexize dist_cpoly dist_lb dist_pb
	  dist_pc dist_pl dist_ppath dist_ps dist_sb dist_sl div
	  dlog1 dlog10 domain_in domain_recv dpow dround dsimple_init
	  dsimple_lexize dsnowball_init dsnowball_lexize dsqrt dsynonym_init dsynonym_lexize dtrunc
	  elem_contained_by_range encrypt encrypt_iv enum_cmp enum_eq enum_first enum_ge
	  enum_gt enum_in enum_larger enum_last enum_le enum_lt enum_ne
	  enum_out enum_range enum_recv enum_send enum_smaller eqjoinsel eqsel
	  euc_cn_to_mic euc_cn_to_utf8 euc_jis_2004_to_shift_jis_2004 euc_jis_2004_to_utf8
	  euc_jp_to_mic euc_jp_to_sjis euc_jp_to_utf8
	  euc_kr_to_mic euc_kr_to_utf8 euc_tw_to_big5 euc_tw_to_mic euc_tw_to_utf8 every exp
	  factorial family fdw_handler_in fdw_handler_out first_value float4 float48div
	  float48eq float48ge float48gt float48le float48lt float48mi float48mul
	  float48ne float48pl float4_accum float4abs float4div float4eq float4ge
	  float4gt float4in float4larger float4le float4lt float4mi float4mul
	  float4ne float4out float4pl float4recv float4send float4smaller float4um
	  float4up float8 float84div float84eq float84ge float84gt float84le
	  float84lt float84mi float84mul float84ne float84pl float8_accum float8_avg
	  float8_combine float8_regr_combine float8_corr float8_covar_pop float8_covar_samp
	  float8_regr_accum float8_regr_avgx float8_regr_avgy float8_regr_intercept
	  float8_regr_r2 float8_regr_slope float8_regr_sxx float8_regr_sxy float8_regr_syy
	  float8_stddev_pop float8_stddev_samp
	  float8_var_pop float8_var_samp float8abs float8div float8eq float8ge float8gt
	  float8in float8larger float8le float8lt float8mi float8mul float8ne
	  float8out float8pl float8recv float8send float8smaller float8um float8up
	  floor flt4_mul_cash flt8_mul_cash fmgr_c_validator fmgr_internal_validator fmgr_sql_validator format
	  format_type gb18030_to_utf8 gbk_to_utf8 gen_random_bytes gen_salt generate_series generate_subscripts
	  geometry get_current_ts_config getdatabaseencoding getpgusername gin_cmp_prefix gin_cmp_tslexeme
	  gin_extract_tsquery gin_extract_tsvector gin_tsquery_consistent ginarrayconsistent ginarrayextract
	  ginbeginscan ginbuild ginbuildempty ginbulkdelete gincostestimate ginendscan gingetbitmap gininsert
	  ginmarkpos ginoptions ginqueryarrayextract ginrescan ginrestrpos ginvacuumcleanup gist_box_compress
	  gist_box_consistent gist_box_decompress gist_box_penalty gist_box_picksplit gist_box_same gist_box_union
	  gist_circle_compress gist_circle_consistent gist_point_compress gist_point_consistent gist_point_distance
	  gist_poly_compress gist_poly_consistent gistbeginscan gistbuild gistbuildempty gistbulkdelete
	  gistcostestimate gistendscan gistgetbitmap gistgettuple gistinsert gistmarkpos gistoptions gistrescan
	  gistrestrpos gistvacuumcleanup group_concat gtsquery_compress gtsquery_consistent gtsquery_decompress gtsquery_penalty
	  gtsquery_picksplit gtsquery_same gtsquery_union gtsvector_compress gtsvector_consistent gtsvector_decompress
	  gtsvector_penalty gtsvector_picksplit gtsvector_same gtsvector_union gtsvectorin gtsvectorout
	  has_any_column_privilege has_column_privilege has_database_privilege has_foreign_data_wrapper_privilege
	  has_function_privilege has_language_privilege has_schema_privilege has_sequence_privilege has_server_privilege
	  has_table_privilege has_tablespace_privilege has_type_privilege hash_aclitem hash_array hash_numeric hash_range
	  hashbeginscan hashbpchar hashbuild hashbuildempty hashbulkdelete hashchar hashcostestimate hash_aclitem_extended
	  hashendscan hashenum hashfloat4 hashfloat8 hashgetbitmap hashgettuple hashinet hashinsert hashint2
	  hashint2extended hashint2vector hashint4 hashint4extended hashint8 hashint8extended hashmacaddr
	  hashfloat4extended hashfloat8extended hashcharextended hashoidextended hashnameextended hashmarkpos
	  hashoidvectorextended hashmacaddrextended hashinetextended hashname hashoid hashoidvector hashoptions
	  hash_numeric_extended hashmacaddr8extended hash_array_extended hashrescan hashrestrpos hashtext
	  hashbpcharextended time_hash_extended timetz_hash_extended interval_hash_extended timestamp_hash_extended
	  uuid_hash_extended pg_lsn_hash_extended hashenumextended jsonb_hash_extended hash_range_extended
	  hashtextextended hashvacuumcleanup hashvarlena height hmac host hostmask iclikejoinsel
	  iclikesel icnlikejoinsel icnlikesel icregexeqjoinsel icregexeqsel icregexnejoinsel icregexnesel
	  inet_client_addr inet_client_port inet_in inet_out inet_recv inet_send inet_server_addr
	  inet_server_port inetand inetmi inetmi_int8 inetnot inetor inetpl
	  int int2 int24div int24eq int24ge int24gt int24le int24lt integer
	  int24mi int24mul int24ne int24pl int28div int28eq int28ge
	  int28gt int28le int28lt int28mi int28mul int28ne int28pl
	  int2_accum int2_avg_accum int2_mul_cash int2_sum int2abs int2and int2div
	  int2eq int2ge int2gt int2in int2larger int2le int2lt
	  int2mi int2mod int2mul int2ne int2not int2or int2out
	  int2pl int2recv int2send int2shl int2shr int2smaller int2um
	  int2up int2vectoreq int2vectorin int2vectorout int2vectorrecv int2vectorsend int2xor
	  int4 int42div int42eq int42ge int42gt int42le int42lt
	  int42mi int42mul int42ne int42pl int48div int48eq int48ge
	  int48gt int48le int48lt int48mi int48mul int48ne int48pl
	  int4_accum int4_avg_accum int4_mul_cash int4_sum int4abs int4and int4div
	  int4eq int4ge int4gt int4in int4inc int4larger int4le
	  int4lt int4mi int4mod int4mul int4ne int4not int4or
	  int4out int4pl int4range int4range_canonical int4range_subdiff int4recv int4send
	  int4shl int4shr int4smaller int4um int4up int4xor int8
	  int82div int82eq int82ge int82gt int82le int82lt int82mi
	  int82mul int82ne int82pl int84div int84eq int84ge int84gt
	  int84le int84lt int84mi int84mul int84ne int84pl int8_accum
	  int8_avg int8_avg_accum int8_sum int8abs int8and int8div int8eq
	  int8ge int8gt int8in int8inc int8inc_any int8inc_float8_float8 int8larger
	  int8le int8lt int8mi int8mod int8mul int8ne int8not
	  int8or int8out int8pl int8pl_inet int8range int8range_canonical int8range_subdiff
	  int8recv int8send int8shl int8shr int8smaller int8um int8up
	  int8xor integer_pl_date inter_lb inter_sb inter_sl internal_in internal_out
	  interval_accum interval_avg interval_cmp interval_div interval_eq interval_ge interval_gt
	  interval_hash interval_in interval_larger interval_le interval_lt interval_mi interval_mul
	  interval_ne interval_out interval_pl interval_pl_date interval_pl_time interval_pl_timestamp interval_pl_timestamptz
	  interval_pl_timetz interval_recv interval_send interval_smaller interval_transform interval_um intervaltypmodin
	  intervaltypmodout intinterval isclosed isempty ishorizontal iso8859_1_to_utf8 iso8859_to_utf8
	  iso_to_koi8r iso_to_mic iso_to_win1251 iso_to_win866 isopen isparallel isperp
	  isvertical johab_to_utf8 json_agg jsonb_agg json_array_elements jsonb_array_elements
	  json_array_elements_text jsonb_array_elements_text json_to_tsvector jsonb_insert
	  json_array_length jsonb_array_length json_build_array json_build_object json_each jsonb_each json_each_text
	  jsonb_each_text json_extract_path jsonb_extract_path json_extract_path_text jsonb_extract_path_text json_in
	  json_object json_object_agg jsonb_object_agg json_object_keys jsonb_object_keys json_out json_populate_record
	  jsonb_populate_record json_populate_recordset jsonb_pretty jsonb_populate_recordset json_recv json_send
	  jsonb_set json_typeof jsonb_typeof json_to_record jsonb_to_record json_to_recordset jsonb_to_recordset
	  justify_interval koi8r_to_iso koi8r_to_mic koi8r_to_utf8 koi8r_to_win1251 koi8r_to_win866 koi8u_to_utf8
	  jsonb_path_query jsonb_build_object jsonb_object jsonb_build_array jsonb_path_match jsonb_path_exists
	  lag language_handler_in language_handler_out last_value lastval latin1_to_mic latin2_to_mic latin2_to_win1250
	  latin3_to_mic latin4_to_mic lead like_escape likejoinsel jsonb_path_query_first jsonb_path_query_array
	  likesel line line_distance line_eq line_horizontal line_in line_interpt
	  line_intersect line_out line_parallel line_perp line_recv line_send line_vertical
	  ln lo_close lo_creat lo_create lo_export lo_import lo_lseek lo_compat lo_from_bytea lo_get lo_import_with_oid
	  lo_open lo_tell lo_truncate lo_unlink log lo_read lower_inc lo_seek64 lo_put lo_tell64 lo_truncate64 lo_write
	  lower_inf lowrite lseg lseg_center lseg_distance lseg_eq lseg_ge
	  lseg_gt lseg_horizontal lseg_in lseg_interpt lseg_intersect lseg_le lseg_length
	  lseg_lt lseg_ne lseg_out lseg_parallel lseg_perp lseg_recv lseg_send
	  lseg_vertical macaddr_and macaddr_cmp macaddr_eq macaddr_ge macaddr_gt macaddr_in
	  macaddr_le macaddr_lt macaddr_ne macaddr_not macaddr_or macaddr_out macaddr_recv
	  macaddr_send makeaclitem make_interval make_tsrange masklen max mic_to_ascii mic_to_big5 mic_to_euc_cn
	  mic_to_euc_jp mic_to_euc_kr mic_to_euc_tw mic_to_iso mic_to_koi8r mic_to_latin1 mic_to_latin2
	  mic_to_latin3 mic_to_latin4 mic_to_sjis mic_to_win1250 mic_to_win1251 mic_to_win866 min
	  mktinterval mode mod money mul_d_interval name nameeq namege make_timestamptz make_timestamp
	  namegt nameiclike nameicnlike nameicregexeq nameicregexne namein namele make_time make_date
	  namelike namelt namene namenlike nameout namerecv nameregexeq make_interval
	  nameregexne namesend neqjoinsel neqsel netmask network network_cmp
	  network_eq network_ge network_gt network_le network_lt network_ne network_sub
	  network_subeq network_sup network_supeq nextval nlikejoinsel nlikesel notlike
	  npoints nth_value ntile numeric numeric_abs numeric_accum numeric_add
	  numeric_avg numeric_avg_accum numeric_cmp numeric_div numeric_div_trunc numeric_eq numeric_exp
	  numeric_fac numeric_ge numeric_gt numeric_in numeric_inc numeric_larger numeric_le
	  numeric_ln numeric_log numeric_lt numeric_mod numeric_mul numeric_ne numeric_out
	  numeric_power numeric_recv numeric_send numeric_smaller numeric_sqrt numeric_stddev_pop numeric_stddev_samp
	  numeric_sub numeric_transform numeric_uminus numeric_uplus numeric_var_pop numeric_var_samp numerictypmodin
	  numerictypmodout numnode numrange numrange_subdiff obj_description oid oideq
	  oidge oidgt oidin oidlarger oidle oidlt oidne
	  oidout oidrecv oidsend oidsmaller oidvectoreq oidvectorge oidvectorgt
	  oidvectorin oidvectorle oidvectorlt oidvectorne oidvectorout oidvectorrecv oidvectorsend
	  oidvectortypes on_pb on_pl on_ppath on_ps on_sb on_sl
	  opaque_in opaque_out overlaps path path_add path_add_pt path_center
	  path_contain_pt path_distance path_div_pt path_in path_inter path_length path_mul_pt
	  path_n_eq path_n_ge path_n_gt path_n_le path_n_lt path_npoints path_out parse_ident
	  path_recv path_send path_sub_pt pclose percent_rank percentile_cont percentile_disc
	  pg_advisory_lock pg_advisory_lock_shared pg_advisory_unlock pg_advisory_unlock_all pg_advisory_unlock_shared
	  pg_advisory_xact_lock pg_advisory_xact_lock_shared pg_available_extension_versions pg_available_extensions
	  pg_backend_pid pg_cancel_backend pg_char_to_encoding pg_collation_for pg_collation_is_visible pg_column_size
	  pg_conf_load_time pg_conversion_is_visible pg_create_restore_point pg_current_xlog_insert_location
	  pg_current_xlog_location pg_cursor pg_database_size pg_describe_object pg_encoding_max_length
	  pg_encoding_to_char pg_export_snapshot pg_extension_config_dump pg_extension_update_paths pg_function_is_visible
	  pg_get_constraintdef pg_get_expr pg_get_function_arguments pg_filenode_relation pg_indexam_has_property
	  pg_get_function_identity_arguments pg_get_function_result pg_get_functiondef pg_get_indexdef pg_get_keywords
	  pg_get_ruledef pg_get_serial_sequence pg_get_triggerdef pg_get_userbyid pg_get_viewdef pg_has_role
	  pg_indexes_size pg_is_in_recovery pg_is_other_temp_schema pg_is_xlog_replay_paused pg_last_xact_replay_timestamp
	  pg_last_xlog_receive_location pg_last_xlog_replay_location pg_listening_channels pg_lock_status pg_ls_dir
	  pg_my_temp_schema pg_node_tree_in pg_node_tree_out pg_node_tree_recv pg_node_tree_send pg_notify
	  pg_opclass_is_visible pg_operator_is_visible pg_opfamily_is_visible pg_options_to_table pg_index_has_property
	  pg_postmaster_start_time pg_prepared_statement pg_prepared_xact pg_read_binary_file pg_read_file
	  pg_relation_filenode pg_relation_filepath pg_relation_size pg_reload_conf pg_rotate_logfile
	  pg_sequence_parameters pg_show_all_settings pg_size_pretty pg_sleep pg_start_backup pg_index_column_has_property
	  pg_stat_clear_snapshot pg_stat_file pg_stat_get_activity pg_stat_get_analyze_count pg_stat_get_autoanalyze_count
	  pg_stat_get_autovacuum_count pg_get_object_address pg_identify_object_as_address pg_stat_get_backend_activity
	  pg_stat_get_backend_activity_start pg_stat_get_backend_client_addr pg_stat_get_backend_client_port
	  pg_stat_get_backend_dbid pg_stat_get_backend_idset pg_stat_get_backend_pid pg_stat_get_backend_start
	  pg_stat_get_backend_userid pg_stat_get_backend_waiting pg_stat_get_backend_xact_start
	  pg_stat_get_bgwriter_buf_written_checkpoints pg_stat_get_bgwriter_buf_written_clean
	  pg_stat_get_bgwriter_maxwritten_clean pg_stat_get_bgwriter_requested_checkpoints
	  pg_stat_get_bgwriter_stat_reset_time pg_stat_get_bgwriter_timed_checkpoints pg_stat_get_blocks_fetched
	  pg_stat_get_blocks_hit pg_stat_get_buf_alloc pg_stat_get_buf_fsync_backend pg_stat_get_buf_written_backend
	  pg_stat_get_checkpoint_sync_time pg_stat_get_checkpoint_write_time pg_stat_get_db_blk_read_time
	  pg_stat_get_db_blk_write_time pg_stat_get_db_blocks_fetched pg_stat_get_db_blocks_hit
	  pg_stat_get_db_conflict_all pg_stat_get_db_conflict_bufferpin pg_stat_get_db_conflict_lock
	  pg_stat_get_db_conflict_snapshot pg_stat_get_db_conflict_startup_deadlock pg_stat_get_db_conflict_tablespace
	  pg_stat_get_db_deadlocks pg_stat_get_db_numbackends pg_stat_get_db_stat_reset_time pg_stat_get_db_temp_bytes
	  pg_stat_get_db_temp_files pg_stat_get_db_tuples_deleted pg_stat_get_db_tuples_fetched
	  pg_stat_get_db_tuples_inserted pg_stat_get_db_tuples_returned pg_stat_get_db_tuples_updated
	  pg_stat_get_db_xact_commit pg_stat_get_db_xact_rollback pg_stat_get_dead_tuples pg_stat_get_function_calls
	  pg_stat_get_function_self_time pg_stat_get_function_total_time pg_stat_get_last_analyze_time
	  pg_stat_get_last_autoanalyze_time pg_stat_get_last_autovacuum_time pg_stat_get_last_vacuum_time
	  pg_stat_get_live_tuples pg_stat_get_numscans pg_stat_get_tuples_deleted pg_stat_get_tuples_fetched
	  pg_stat_get_tuples_hot_updated pg_stat_get_tuples_inserted pg_stat_get_tuples_returned
	  pg_stat_get_tuples_updated pg_stat_get_vacuum_count pg_stat_get_wal_senders pg_stat_get_xact_blocks_fetched
	  pg_stat_get_xact_blocks_hit pg_stat_get_xact_function_calls pg_stat_get_xact_function_self_time
	  pg_stat_get_xact_function_total_time pg_stat_get_xact_numscans pg_stat_get_xact_tuples_deleted
	  pg_stat_get_xact_tuples_fetched pg_stat_get_xact_tuples_hot_updated pg_stat_get_xact_tuples_inserted
	  pg_stat_get_xact_tuples_returned pg_stat_get_xact_tuples_updated pg_stat_reset pg_stat_reset_shared
	  pg_stat_reset_single_function_counters pg_stat_reset_single_table_counters pg_stop_backup pg_switch_xlog
	  pg_table_is_visible pg_table_size pg_tablespace_databases pg_tablespace_location pg_tablespace_size
	  pg_terminate_backend pg_timezone_abbrevs pg_timezone_names pg_total_relation_size pg_trigger_depth
	  pg_try_advisory_lock pg_try_advisory_lock_shared pg_try_advisory_xact_lock pg_try_advisory_xact_lock_shared
	  pg_ts_config_is_visible pg_ts_dict_is_visible pg_ts_parser_is_visible pg_ts_template_is_visible
	  pg_type_is_visible pg_typeof pg_xact_commit_timestamp pg_last_committed_xact pg_xlog_location_diff
	  pg_xlog_replay_pause pg_xlog_replay_resume pg_xlogfile_name pg_xlogfile_name_offset pgp_key_id pgp_pub_decrypt
	  pgp_pub_decrypt_bytea pgp_pub_encrypt pgp_pub_encrypt_bytea pgp_sym_decrypt pgp_sym_decrypt_bytea
	  pgp_sym_encrypt pgp_sym_encrypt_bytea pi plainto_tsquery plpgsql_call_handler plpgsql_inline_handler
	  plpgsql_validator point point_above point_add point_below point_distance point_div point_eq
	  point_horiz point_in point_left point_mul point_ne point_out point_recv
	  point_right point_send point_sub point_vert poly_above poly_below poly_center
	  poly_contain poly_contain_pt poly_contained poly_distance poly_in poly_left poly_npoints
	  poly_out poly_overabove poly_overbelow poly_overlap poly_overleft poly_overright poly_recv
	  poly_right poly_same poly_send polygon popen positionjoinsel positionsel
	  postgresql_fdw_validator pow power prsd_end prsd_headline prsd_lextype prsd_nexttoken
	  prsd_start pt_contained_circle pt_contained_poly querytree
	  quote_nullable radians radius random range_adjacent range_after range_before
	  range_cmp range_contained_by range_contains range_contains_elem range_eq range_ge range_gist_compress
	  range_gist_consistent range_gist_decompress range_gist_penalty range_gist_picksplit range_gist_same
	  range_gist_union range_gt range_merge
	  range_in range_intersect range_le range_lt range_minus range_ne range_out
	  range_overlaps range_overleft range_overright range_recv range_send range_typanalyze range_union
	  rank record_eq record_ge record_gt record_in record_le record_lt regexp_match
	  record_ne record_out record_recv record_send regclass regclassin regclassout
	  regclassrecv regclasssend regconfigin regconfigout regconfigrecv regconfigsend regdictionaryin
	  regnamespace regoper regoperator regproc regprocedure regrole regtype regdictionaryout
	  regdictionaryrecv regdictionarysend regexeqjoinsel regexeqsel regexnejoinsel regexnesel regexp_matches
	  regexp_replace regexp_split_to_array regexp_split_to_table regoperatorin regoperatorout regoperatorrecv
	  regoperatorsend regoperin regoperout regoperrecv regopersend regprocedurein regprocedureout
	  regprocedurerecv regproceduresend regprocin regprocout regprocrecv regprocsend regr_avgx
	  regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy
	  regr_syy regtypein regtypeout regtyperecv regtypesend reltime reltimeeq
	  reltimege reltimegt reltimein reltimele reltimelt reltimene reltimeout
	  reltimerecv reltimesend reverse round row_number row_to_json
	  scalargtjoinsel scalargtsel scalarltjoinsel scalarltsel
	  session_user set_config set_masklen setseed setval setweight shell_in
	  shell_out shift_jis_2004_to_euc_jis_2004 shift_jis_2004_to_utf8 shobj_description sign similar_escape sin
	  sjis_to_euc_jp sjis_to_mic sjis_to_utf8 slope smgreq smgrin smgrne
	  smgrout spg_kd_choose spg_kd_config spg_kd_inner_consistent spg_kd_picksplit spg_quad_choose spg_quad_config
	  spg_quad_inner_consistent spg_quad_leaf_consistent spg_quad_picksplit spg_text_choose spg_text_config spg_text_inner_consistent spg_text_leaf_consistent
	  spg_text_picksplit spgbeginscan spgbuild spgbuildempty spgbulkdelete spgcanreturn spgcostestimate
	  spgendscan spggetbitmap spggettuple spginsert spgmarkpos spgoptions spgrescan
	  spgrestrpos spgvacuumcleanup sqrt statement_timestamp stddev stddev_pop stddev_samp
	  string_agg string_agg_finalfn string_agg_transfn string_to_array strip sum
	  tan text text_ge text_gt text_larger
	  text_le text_lt text_pattern_ge text_pattern_gt text_pattern_le text_pattern_lt text_smaller
	  textanycat textcat texteq texticlike texticnlike texticregexeq texticregexne
	  textin textlen textlike textne textnlike textout textrecv
	  textregexeq textregexne textsend thesaurus_init thesaurus_lexize tideq tidge
	  tidgt tidin tidlarger tidle tidlt tidne tidout
	  tidrecv tidsend tidsmaller time time_cmp time_eq time_ge
	  time_gt time_hash time_in time_larger time_le time_lt time_mi_interval
	  time_mi_time time_ne time_out time_pl_interval time_recv time_send time_smaller
	  time_transform timedate_pl timemi timenow timepl timestamp timestamp_cmp
	  timestamp_cmp_date timestamp_cmp_timestamptz timestamp_eq timestamp_eq_date timestamp_eq_timestamptz timestamp_ge timestamp_ge_date
	  timestamp_ge_timestamptz timestamp_gt timestamp_gt_date timestamp_gt_timestamptz timestamp_hash timestamp_in timestamp_larger
	  timestamp_le timestamp_le_date timestamp_le_timestamptz timestamp_lt timestamp_lt_date timestamp_lt_timestamptz timestamp_mi
	  timestamp_mi_interval timestamp_ne timestamp_ne_date timestamp_ne_timestamptz timestamp_out timestamp_pl_interval timestamp_recv
	  timestamp_send timestamp_smaller timestamp_sortsupport timestamp_transform timestamptypmodin timestamptypmodout timestamptz
	  timestamptz_cmp timestamptz_cmp_date timestamptz_cmp_timestamp timestamptz_eq timestamptz_eq_date timestamptz_eq_timestamp timestamptz_ge
	  timestamptz_ge_date timestamptz_ge_timestamp timestamptz_gt timestamptz_gt_date timestamptz_gt_timestamp timestamptz_in timestamptz_larger
	  timestamptz_le timestamptz_le_date timestamptz_le_timestamp timestamptz_lt timestamptz_lt_date timestamptz_lt_timestamp timestamptz_mi
	  timestamptz_mi_interval timestamptz_ne timestamptz_ne_date timestamptz_ne_timestamp timestamptz_out timestamptz_pl_interval timestamptz_recv
	  timestamptz_send timestamptz_smaller timestamptztypmodin timestamptztypmodout timetypmodin timetypmodout timetz
	  timetz_cmp timetz_eq timetz_ge timetz_gt timetz_hash timetz_in timetz_larger
	  timetz_le timetz_lt timetz_mi_interval timetz_ne timetz_out timetz_pl_interval timetz_recv
	  timetz_send timetz_smaller timetzdate_pl timetztypmodin timetztypmodout timezone tinterval
	  tintervalct tintervalend tintervaleq tintervalge tintervalgt tintervalin tintervalle
	  tintervalleneq tintervallenge tintervallengt tintervallenle tintervallenlt tintervallenne tintervallt
	  tintervalne tintervalout tintervalov tintervalrecv tintervalrel tintervalsame tintervalsend
	  tintervalstart to_json to_tsquery to_tsvector to_regclass to_regnamespace to_regoper to_regoperator
	  to_regproc to_regprocedure to_regrole to_regtype transaction_timestamp trigger_out trunc ts_debug
	  ts_headline ts_lexize ts_match_qv ts_match_tq ts_match_tt ts_match_vq ts_parse ts_delete ts_filter
	  ts_rank ts_rank_cd ts_rewrite ts_stat ts_token_type ts_typanalyze tsmatchjoinsel tsquery_phrase
	  tsmatchsel tsq_mcontained tsq_mcontains tsquery_and tsquery_cmp tsquery_eq tsquery_ge
	  tsquery_gt tsquery_le tsquery_lt tsquery_ne tsquery_not tsquery_or tsqueryin websearch_to_tsquery
	  tsqueryout tsqueryrecv tsquerysend tsrange tsrange_subdiff tstzrange tstzrange_subdiff phraseto_tsquery
	  tsvector_cmp tsvector_concat tsvector_eq tsvector_ge tsvector_gt tsvector_le tsvector_lt
	  tsvector_ne tsvectorin tsvectorout tsvectorrecv tsvectorsend txid_current txid_current_snapshot
	  txid_snapshot_in txid_snapshot_out txid_snapshot_recv txid_snapshot_send txid_snapshot_xip
	  txid_snapshot_xmax txid_snapshot_xmin
	  txid_visible_in_snapshot uhc_to_utf8 unknownin unknownout unknownrecv unknownsend unnest
	  upper_inc upper_inf utf8_to_ascii utf8_to_big5 utf8_to_euc_cn utf8_to_euc_jis_2004 utf8_to_euc_jp
	  utf8_to_euc_kr utf8_to_euc_tw utf8_to_gb18030 utf8_to_gbk utf8_to_iso8859 utf8_to_iso8859_1 utf8_to_johab
	  utf8_to_koi8r utf8_to_koi8u utf8_to_shift_jis_2004 utf8_to_sjis utf8_to_uhc utf8_to_win uuid_cmp
	  uuid_eq uuid_ge uuid_gt uuid_hash uuid_in uuid_le uuid_lt
	  uuid_ne uuid_out uuid_recv uuid_send var_pop var_samp varbit
	  varbit_in varbit_out varbit_recv varbit_send varbit_transform varbitcmp varbiteq
	  varbitge varbitgt varbitle varbitlt varbitne varbittypmodin varbittypmodout
	  varchar varying varchar_transform varcharin varcharout varcharrecv varcharsend varchartypmodin
	  varchartypmodout variance version void_in void_out void_recv void_send
	  width width_bucket win1250_to_latin2 win1250_to_mic win1251_to_iso win1251_to_koi8r win1251_to_mic
	  win1251_to_win866 win866_to_iso win866_to_koi8r win866_to_mic win866_to_win1251 win_to_utf8 xideq
	  xideqint4 xidin xidout xidrecv xidsend xml xml_in xmlcomment xpath xpath_exists table_to_xmlschema
	  query_to_xmlschema cursor_to_xmlschema table_to_xml_and_xmlschema query_to_xml_and_xmlschema
	  schema_to_xml schema_to_xmlschema schema_to_xml_and_xmlschema database_to_xml database_to_xmlschema xmlroot
	  database_to_xml_and_xmlschema table_to_xml query_to_xmlcursor_to_xml xmlcomment xmlconcat xmlelement xmlforest
	  xml_is_well_formed_content xml_is_well_formed_document xml_is_well_formed xml_out xml_recv xml_send xmlagg
	  xmlpi query_to_xml cursor_to_xml xmlserialize xmltable
	);

	my @copy_keywords = ( 'STDIN', 'STDOUT' );

	my %symbols = (
		'='  => '=',
		'<'  => '&lt;',
		'>'  => '&gt;',
		'|'  => '|',
		','  => ',',
		'.'  => '.',
		'+'  => '+',
		'-'  => '-',
		'*'  => '*',
		'/'  => '/',
		'!=' => '!=',
		'%'  => '%',
		'<=' => '&lt;=',
		'>=' => '&gt;=',
		'<>' => '&lt;&gt;'
	);

	my @brackets = ( '(', ')' );

# All setting and modification of dicts is done, can set them now to $self->{'dict'}->{...}
	$self->{'dict'}->{'pg_keywords'}       = \@pg_keywords;
	$self->{'dict'}->{'pg_types'}          = \@pg_types;
	$self->{'dict'}->{'sql_keywords'}      = \@sql_keywords;
	$self->{'dict'}->{'redshift_keywords'} = \@redshift_keywords;
	$self->{'dict'}->{'pg_functions'}      = ();
	map { $self->{'dict'}->{'pg_functions'}{$_} = ''; } @pg_functions;
	$self->{'dict'}->{'copy_keywords'} = \@copy_keywords;
	$self->{'dict'}->{'symbols'}       = \%symbols;
	$self->{'dict'}->{'brackets'}      = \@brackets;

	return;
}

=head2 _remove_dynamic_code

Internal function used to hide dynamic code in plpgsql to the parser.
The original values are restored with function _restore_dynamic_code().

=cut

sub _remove_dynamic_code {
	my ( $self, $str, $code_sep ) = @_;

	my @dynsep = ();
	push( @dynsep, $code_sep ) if ( $code_sep && $code_sep ne "'" );

	# Try to auto detect the string separator if none are provided.
	# Note that default single quote separtor is natively supported.
	if ( $#dynsep == -1 ) {

		# if a dollar sign is found after EXECUTE then the following string
		# until an other dollar is found will be understand as a text delimiter
		@dynsep = $$str =~ /EXECUTE\s+(\$[^\$\s]*\$)/igs;
	}

	foreach my $sep (@dynsep) {
		while ( $$str =~ s/(\Q$sep\E.*?\Q$sep\E)/TEXTVALUE$self->{idx_code}/s )
		{
			$self->{dynamic_code}{ $self->{idx_code} } = $1;
			$self->{idx_code}++;
		}
	}

	# Replace any COMMENT constant between single quote
	while ( $$str =~ s/IS\s+('(?:.*?)')\s*;/IS TEXTVALUE$self->{idx_code};/s ) {
		$self->{dynamic_code}{ $self->{idx_code} } = $1;
		$self->{idx_code}++;
	}

	# keep untouched parts between double single quotes
	while ( $$str =~
		s/(PGFESCQ1(?:[^\r\n\|;]*?)PGFESCQ1)/TEXTVALUE$self->{idx_code}/s )
	{
		$self->{dynamic_code}{ $self->{idx_code} } = $1;
		$self->{idx_code}++;
	}
}

=head2 _restore_dynamic_code

Internal function used to restore plpgsql dynamic code in plpgsql
that was removed by the _remove_dynamic_code() method.

=cut

sub _restore_dynamic_code {
	my ( $self, $str ) = @_;

	$$str =~ s/TEXTVALUE(\d+)/$self->{dynamic_code}{$1}/gs;

}

=head2 _quote_operator

Internal function used to quote operator with multiple character
to be tokenized as a single word.
The original values are restored with function _restore_operator().

=cut

sub _quote_operator {
	my ( $self, $str ) = @_;

	my @lines = split( /[\n]/, $$str );
	for ( my $i = 0 ; $i <= $#lines ; $i++ ) {
		if ( $lines[$i] =~
s/((?:CREATE|DROP|ALTER)\s+OPERATOR\s+(?:IF\s+EXISTS)?)\s*((:?[a-z0-9]+\.)?[\+\-\*\/<>=\~\!\@\#\%\^\&\|\`\?]+)\s*/$1 "$2" /i
		  )
		{
			push( @{ $self->{operator} }, $2 )
			  if ( !grep( /^\Q$2\E$/, @{ $self->{operator} } ) );
		}
	}
	$$str = join( "\n", @lines );

	my $idx = 0;
	while ( $$str =~ s/(NEGATOR|COMMUTATOR)\s*=\s*([^,\)\s]+)/\U$1\E$idx/is ) {
		$self->{ uc($1) }{$idx} = "$1 = $2";
		$idx++;
	}
}

=head2 _restore_operator

Internal function used to restore operator that was removed
by the _quote_operator() method.

=cut

sub _restore_operator {
	my ( $self, $str ) = @_;

	foreach my $op ( @{ $self->{operator} } ) {
		$$str =~ s/"$op"/$op/gs;
	}
	if ( exists $self->{COMMUTATOR} ) {
		$$str =~ s/COMMUTATOR(\d+)/$self->{COMMUTATOR}{$1}/igs;
	}
	if ( exists $self->{NEGATOR} ) {
		$$str =~ s/NEGATOR(\d+)/$self->{NEGATOR}{$1}/igs;
	}
}

=head2 _quote_comment_stmt

Internal function used to replace constant in a COMMENT statement
to be tokenized as a single word.
The original values are restored with function _restore_comment_stmt().

=cut

sub _quote_comment_stmt {
	my ( $self, $str ) = @_;

	my $idx = 0;
	while ( $$str =~
		s/(COMMENT\s+ON\s+(?:.*?)\s+IS)\s+(\$[^;]+?\$)\s*;/$1 PGF_CMTSTR$idx;/is
	  )
	{
		$self->{comment_str}{$idx} = $2;
		$idx++;
	}
}

=head2 _restore_comment_stmt

Internal function used to restore comment string that was removed
by the _quote_comment_stmt() method.

=cut

sub _restore_comment_stmt {
	my ( $self, $str ) = @_;

	if ( exists $self->{comment_str} ) {
		$$str =~ s/PGF_CMTSTR(\d+)/$self->{comment_str}{$1}/igs;
	}
}

=head2 _remove_comments

Internal function used to remove comments in SQL code
to simplify the work of the wrap_lines. Comments must be
restored with the _restore_comments() method.

=cut

sub _remove_comments {
	my $self = shift;

	my $idx = 0;

	while ( $self->{'content'} =~ s/(\/\*(.*?)\*\/)/PGF_COMMENT${idx}A/s ) {
		$self->{'comments'}{"PGF_COMMENT${idx}A"} = $1;
		$idx++;
	}
	my @lines = split( /\n/, $self->{'content'} );
	for ( my $j = 0 ; $j <= $#lines ; $j++ ) {
		$lines[$j] //= '';

		# Extract multiline comments as a single placeholder
		my $old_j = $j;
		my $cmt   = '';
		while ( $j <= $#lines && $lines[$j] =~ /^(\s*\-\-.*)$/ ) {
			$cmt .= "$1\n";
			$j++;
		}
		if ( $j > $old_j ) {
			chomp($cmt);
			$lines[$old_j] =~ s/^(\s*\-\-.*)$/PGF_COMMENT${idx}A/;
			$self->{'comments'}{"PGF_COMMENT${idx}A"} = $cmt;
			$idx++;
			$j--;
			while ( $j > $old_j ) {
				delete $lines[$j];
				$j--;
			}
		}
		if ( $lines[$j] =~ s/(\s*\-\-.*)$/PGF_COMMENT${idx}A/ ) {
			$self->{'comments'}{"PGF_COMMENT${idx}A"} = $1;
			$idx++;
		}

		# Mysql supports differents kinds of comment's starter
		if (   ( $lines[$j] =~ s/(\s*COMMENT\s+'.*)$/PGF_COMMENT${idx}A/ )
			|| ( $lines[$j] =~ s/(\s*\# .*)$/PGF_COMMENT${idx}A/ ) )
		{
			$self->{'comments'}{"PGF_COMMENT${idx}A"} = $1;

			# Normalize start of comment
			$self->{'comments'}{"PGF_COMMENT${idx}A"} =~
			  s/^(\s*)COMMENT/$1\-\- /;
			$self->{'comments'}{"PGF_COMMENT${idx}A"} =~ s/^(\s*)\#/$1\-\- /;
			$idx++;
		}
	}
	$self->{'content'} = join( "\n", @lines );

	# Remove extra newline after comment
	while ( $self->{'content'} =~ s/(PGF_COMMENT\d+A[\n])[\n]+/$1/s ) { }

	# Replace subsequent comment by a single one
	while ( $self->{'content'} =~
		s/(PGF_COMMENT\d+A\s*PGF_COMMENT\d+A)/PGF_COMMENT${idx}A/s )
	{
		$self->{'comments'}{"PGF_COMMENT${idx}A"} = $1;
		$idx++;
	}
}

=head2 _restore_comments

Internal function used to restore comments in SQL code
that was removed by the _remove_comments() method.

=cut

sub _restore_comments {
	my ( $self, $wrap_comment ) = @_;

	if ( $self->{'wrap_limit'} && $wrap_comment ) {
		foreach my $k ( keys %{ $self->{'comments'} } ) {
			if ( $self->{'comments'}{$k} =~ /^(\s*)--[\r\n]/s ) {
				next;
			}
			elsif ( $self->{'comments'}{$k} =~ /^(\s*)--/ ) {
				my $indent = $1 || '';
				if (
					length( $self->{'comments'}{$k} ) > $self->{'wrap_limit'} +
					( $self->{'wrap_limit'} * 10 / 100 ) )
				{
					my @data = split( /\n/, $self->{'comments'}{$k} );
					map { s/^\s*--//; } @data;
					$self->{'comments'}{$k} = join( "\n", @data );
					$Text::Wrap::columns = $self->{'wrap_limit'};
					my $t = wrap( '', ' ', $self->{'comments'}{$k} );
					@data = split( /\n/, $t );
					map { s/^/$indent--/; } @data;
					$self->{'comments'}{$k} = join( "\n", @data );
				}
				else {
					$self->{'comments'}{$k} =~ s/^\s*--//s;
					$self->{'comments'}{$k} =
					  $indent . "--$self->{'comments'}{$k}";
				}

				# remove extra spaces after comment characters
				$self->{'comments'}{$k} =~ s/--[ ]+/-- /gs;
			}
		}
	}

	while (
		$self->{'content'} =~ s/(PGF_COMMENT\d+A)/$self->{'comments'}{$1}/s )
	{
		delete $self->{'comments'}{$1};
	}
}

=head2 wrap_lines

Internal function used to wrap line at a certain length.

=cut

sub wrap_lines {
	my ( $self, $wrap_comment ) = @_;

	return if ( !$self->{'wrap_limit'} || !$self->{'content'} );

	$self->_remove_comments();

	my @lines = split( /\n/, $self->{'content'} );
	$self->{'content'} = '';

	foreach my $l (@lines) {

		# Remove and store the indentation of the line
		my $indent = '';
		if ( $l =~ s/^(\s+)// ) {
			$indent = $1;
		}
		if (
			length($l) >
			$self->{'wrap_limit'} + ( $self->{'wrap_limit'} * 10 / 100 ) )
		{
			$Text::Wrap::columns = $self->{'wrap_limit'};
			my $t = wrap( $indent, " " x $self->{'spaces'} . $indent, $l );
			$self->{'content'} .= "$t\n";
		}
		else {
			$self->{'content'} .= $indent . "$l\n";
		}
	}

	$self->_restore_comments( $wrap_comment || $self->{'wrap_comment'} )
	  if ( $self->{'content'} );

	return;
}

sub _dump_var {
	my $self = shift;
	foreach my $v ( sort keys %{$self} ) {
		next if ( $v !~ /^_/ );
		if ( $self->{$v} =~ /ARRAY/ ) {
			print STDERR "$v => (", join( ',', @{ $self->{$v} } ), ")\n";
		}
		else {
			print STDERR "$v => $self->{$v}\n";
		}
	}
}

=head1 AUTHOR

pgFormatter is an original work from Gilles Darold

=head1 BUGS

Please report any bugs or feature requests to: https://github.com/darold/pgFormatter/issues

=head1 COPYRIGHT

Copyright 2012-2025 Gilles Darold. All rights reserved.

=head1 LICENSE

pgFormatter is free software distributed under the PostgreSQL Licence.

A modified version of the SQL::Beautify Perl Module is embedded in pgFormatter
with copyright (C) 2009 by Jonas Kramer and is published under the terms of
the Artistic License 2.0.

=cut

1;