aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/sql/v1/node.h
blob: ba14584543c8da9f22a3363001dc9bc02bf51124 (plain) (blame)
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
#pragma once

#include <google/protobuf/message.h>
#include <yql/essentials/utils/resetable_setting.h>
#include <yql/essentials/parser/proto_ast/common.h>
#include <yql/essentials/public/udf/udf_data_type.h>
#include <yql/essentials/ast/yql_ast.h>
#include <yql/essentials/ast/yql_expr.h>
#include <util/generic/vector.h>
#include <util/generic/set.h>
#include <util/generic/map.h>
#include <util/generic/hash.h>
#include <util/generic/hash_set.h>
#include <util/generic/maybe.h>
#include <util/string/builder.h>

#include <library/cpp/enumbitset/enumbitset.h>

#include <array>
#include <functional>
#include <variant>

namespace NSQLTranslationV1 {
    constexpr const size_t SQL_MAX_INLINE_SCRIPT_LEN = 24;

    using NYql::TPosition;
    using NYql::TAstNode;

    enum class ENodeState {
        Begin,
        Precached = Begin,
        Initialized,
        CountHint,
        Const,
        MaybeConst,
        Aggregated,
        AggregationKey,
        OverWindow,
        OverWindowDistinct,
        Failed,
        End,
    };
    typedef TEnumBitSet<ENodeState, static_cast<int>(ENodeState::Begin), static_cast<int>(ENodeState::End)> TNodeState;

    enum class ESQLWriteColumnMode {
        InsertInto,
        InsertOrAbortInto,
        InsertOrIgnoreInto,
        InsertOrRevertInto,
        UpsertInto,
        ReplaceInto,
        InsertIntoWithTruncate,
        Update,
        Delete,
    };

    enum class EWriteColumnMode {
        Default,
        Insert,
        InsertOrAbort,
        InsertOrIgnore,
        InsertOrRevert,
        Upsert,
        Replace,
        Renew,
        Update,
        UpdateOn,
        Delete,
        DeleteOn,
    };

    enum class EAlterTableIntentnt {
        AddColumn,
        DropColumn
    };

    enum class ETableType {
        Table,
        TableStore,
        ExternalTable
    };

    class TContext;
    class ITableKeys;
    class ISource;
    class IAggregation;
    class TObjectOperatorContext;
    typedef TIntrusivePtr<IAggregation> TAggregationPtr;
    class TColumnNode;
    class TTupleNode;
    class TCallNode;
    class TStructNode;
    class TAccessNode;
    class TLambdaNode;
    class TUdfNode;
    typedef TIntrusivePtr<ISource> TSourcePtr;

    struct TScopedState;
    typedef TIntrusivePtr<TScopedState> TScopedStatePtr;

    inline TString DotJoin(const TString& lhs, const TString& rhs) {
        TStringBuilder sb;
        sb << lhs << "." << rhs;
        return sb;
    }

    TString ErrorDistinctByGroupKey(const TString& column);
    TString ErrorDistinctWithoutCorrelation(const TString& column);

    class INode: public TSimpleRefCount<INode> {
    public:
        typedef TIntrusivePtr<INode> TPtr;

        struct TIdPart {
            TString Name;
            TPtr Expr;

            TIdPart(const TString& name)
                : Name(name)
            {
            }
            TIdPart(TPtr expr)
                : Expr(expr)
            {
            }
            TIdPart Clone() const {
                TIdPart res(Name);
                res.Expr = Expr ? Expr->Clone() : nullptr;
                return res;
            }
        };

    public:
        INode(TPosition pos);
        virtual ~INode();

        TPosition GetPos() const;
        const TString& GetLabel() const;
        TMaybe<TPosition> GetLabelPos() const;
        void SetLabel(const TString& label, TMaybe<TPosition> pos = {});
        bool IsImplicitLabel() const;
        void MarkImplicitLabel(bool isImplicitLabel);
        void SetRefPos(TPosition pos);
        TMaybe<TPosition> GetRefPos() const;

        void SetCountHint(bool isCount);
        bool GetCountHint() const;
        bool Init(TContext& ctx, ISource* src);
        virtual bool InitReference(TContext& ctx);

        bool IsConstant() const;
        bool MaybeConstant() const;
        bool IsAggregated() const;
        bool IsAggregationKey() const;
        bool IsOverWindow() const;
        bool IsOverWindowDistinct() const;
        bool HasState(ENodeState state) const {
            PrecacheState();
            return State.Test(state);
        }

        virtual bool IsNull() const;
        virtual bool IsLiteral() const;
        virtual TString GetLiteralType() const;
        virtual TString GetLiteralValue() const;
        virtual bool IsIntegerLiteral() const;
        virtual TPtr ApplyUnaryOp(TContext& ctx, TPosition pos, const TString& opName) const;
        virtual bool IsAsterisk() const;
        virtual const TString* SubqueryAlias() const;
        virtual TString GetOpName() const;
        virtual const TString* GetLiteral(const TString& type) const;
        virtual const TString* GetColumnName() const;
        virtual bool IsPlainColumn() const;
        virtual bool IsTableRow() const;
        virtual void AssumeColumn();
        virtual const TString* GetSourceName() const;
        virtual const TString* GetAtomContent() const;
        virtual bool IsOptionalArg() const;
        virtual size_t GetTupleSize() const;
        virtual TPtr GetTupleElement(size_t index) const;
        virtual ITableKeys* GetTableKeys();
        virtual ISource* GetSource();
        virtual TVector<INode::TPtr>* ContentListPtr();
        virtual TAstNode* Translate(TContext& ctx) const = 0;
        virtual TAggregationPtr GetAggregation() const;
        virtual void CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs);
        virtual TPtr WindowSpecFunc(const TPtr& type) const;
        virtual bool SetViewName(TContext& ctx, TPosition pos, const TString& view);
        virtual bool SetPrimaryView(TContext& ctx, TPosition pos);
        void UseAsInner();
        void DisableSort();
        virtual bool UsedSubquery() const;
        virtual bool IsSelect() const;
        virtual bool HasSelectResult() const;
        virtual const TString* FuncName() const;
        virtual const TString* ModuleName() const;
        virtual bool HasSkip() const;

        virtual TColumnNode* GetColumnNode();
        virtual const TColumnNode* GetColumnNode() const;

        virtual TTupleNode* GetTupleNode();
        virtual const TTupleNode* GetTupleNode() const;

        virtual TCallNode* GetCallNode();
        virtual const TCallNode* GetCallNode() const;

        virtual TStructNode* GetStructNode();
        virtual const TStructNode* GetStructNode() const;

        virtual TAccessNode* GetAccessNode();
        virtual const TAccessNode* GetAccessNode() const;

        virtual TLambdaNode* GetLambdaNode();
        virtual const TLambdaNode* GetLambdaNode() const;

        virtual TUdfNode* GetUdfNode();
        virtual const TUdfNode* GetUdfNode() const;

        using TVisitFunc = std::function<bool (const INode&)>;
        using TVisitNodeSet = std::unordered_set<const INode*>;

        void VisitTree(const TVisitFunc& func) const;
        void VisitTree(const TVisitFunc& func, TVisitNodeSet& visited) const;

        TPtr AstNode() const;
        TPtr AstNode(TAstNode* node) const;
        TPtr AstNode(TPtr node) const;
        TPtr AstNode(const TString& str) const;

        template <typename TVal, typename... TVals>
        void Add(TVal val, TVals... vals) {
            DoAdd(AstNode(val));
            Add(vals...);
        }

        void Add() {}

        // Y() Q() L()
        TPtr Y() const {
            return AstNode();
        }

        template <typename... TVals>
        TPtr Y(TVals... vals) const {
            TPtr node(AstNode());
            node->Add(vals...);
            return node;
        }

        template <typename T>
        TPtr Q(T a) const {
            return Y("quote", a);
        }

        template <typename... TVals>
        TPtr L(TPtr list, TVals... vals) const {
            Y_DEBUG_ABORT_UNLESS(list);
            auto copy = list->ShallowCopy();
            copy->Add(vals...);
            return copy;
        }

        TPtr Clone() const;
    protected:
        virtual TPtr ShallowCopy() const;
        virtual void DoUpdateState() const;
        virtual TPtr DoClone() const = 0;
        void PrecacheState() const;

        virtual void DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const;
    private:
        virtual bool DoInit(TContext& ctx, ISource* src);
        virtual void DoAdd(TPtr node);

    protected:
        TPosition Pos;
        TString Label;
        TMaybe<TPosition> LabelPos;
        bool ImplicitLabel = false;
        TMaybe<TPosition> RefPos;
        mutable TNodeState State;
        bool AsInner = false;
        bool DisableSort_ = false;
    };
    typedef INode::TPtr TNodePtr;

    class IProxyNode : public INode {
    public:
        IProxyNode(TPosition pos, const TNodePtr& parent)
            : INode(pos)
            , Inner(parent)
        {}

    protected:
        virtual bool IsNull() const override;
        virtual bool IsLiteral() const override;
        virtual TString GetLiteralType() const override;
        virtual TString GetLiteralValue() const override;
        virtual bool IsIntegerLiteral() const override;
        virtual TPtr ApplyUnaryOp(TContext& ctx, TPosition pos, const TString& opName) const override;
        virtual bool IsAsterisk() const override;
        virtual const TString* SubqueryAlias() const override;
        virtual TString GetOpName() const override;
        virtual const TString* GetLiteral(const TString &type) const override;
        virtual const TString* GetColumnName() const override;
        virtual bool IsPlainColumn() const override;
        virtual bool IsTableRow() const override;
        virtual void AssumeColumn() override;
        virtual const TString* GetSourceName() const override;
        virtual const TString* GetAtomContent() const override;
        virtual bool IsOptionalArg() const override;
        virtual size_t GetTupleSize() const override;
        virtual TPtr GetTupleElement(size_t index) const override;
        virtual ITableKeys* GetTableKeys() override;
        virtual ISource* GetSource() override;
        virtual TVector<INode::TPtr>* ContentListPtr() override;
        virtual TAggregationPtr GetAggregation() const override;
        virtual void CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) override;
        virtual TPtr WindowSpecFunc(const TPtr& type) const override;
        virtual bool SetViewName(TContext& ctx, TPosition pos, const TString& view) override;
        virtual bool SetPrimaryView(TContext& ctx, TPosition pos) override;
        virtual bool UsedSubquery() const override;
        virtual bool IsSelect() const override;
        virtual bool HasSelectResult() const override;
        virtual const TString* FuncName() const override;
        virtual const TString* ModuleName() const override;
        virtual bool HasSkip() const override;

        virtual TColumnNode* GetColumnNode() override;
        virtual const TColumnNode* GetColumnNode() const override;

        virtual TTupleNode* GetTupleNode() override;
        virtual const TTupleNode* GetTupleNode() const override;

        virtual TCallNode* GetCallNode() override;
        virtual const TCallNode* GetCallNode() const override;

        virtual TStructNode* GetStructNode() override;
        virtual const TStructNode* GetStructNode() const override;

        virtual TAccessNode* GetAccessNode() override;
        virtual const TAccessNode* GetAccessNode() const override;

        virtual TLambdaNode* GetLambdaNode() override;
        virtual const TLambdaNode* GetLambdaNode() const override;

        virtual TUdfNode* GetUdfNode() override;
        virtual const TUdfNode* GetUdfNode() const override;

    protected:
        virtual void DoUpdateState() const override;
        virtual void DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const override;
        virtual bool InitReference(TContext& ctx) override;
        virtual bool DoInit(TContext& ctx, ISource* src) override;

    private:
        virtual void DoAdd(TPtr node) override;

    protected:
        const TNodePtr Inner;
    };

    using TTableHints = TMap<TString, TVector<TNodePtr>>;
    void MergeHints(TTableHints& base, const TTableHints& overrides);

    template<class T>
    inline T SafeClone(const T& node) {
        return node ? node->Clone() : nullptr;
    }

    template<class T>
    inline TVector<T> CloneContainer(const TVector<T>& args) {
        TVector<T> cloneArgs;
        cloneArgs.reserve(args.size());
        for (const auto& arg: args) {
            cloneArgs.emplace_back(SafeClone(arg));
        }
        return cloneArgs;
    }

    TTableHints CloneContainer(const TTableHints& hints);

    class TAstAtomNode: public INode {
    public:
        TAstAtomNode(TPosition pos, const TString& content, ui32 flags, bool isOptionalArg);

        ~TAstAtomNode() override;

        TAstNode* Translate(TContext& ctx) const override;
        const TString& GetContent() const {
            return Content;
        }

        const TString* GetAtomContent() const override;
        bool IsOptionalArg() const override;

    protected:
        TString Content;
        ui32 Flags;
        bool IsOptionalArg_;

        void DoUpdateState() const override;
    };

    class TAstAtomNodeImpl final: public TAstAtomNode {
    public:
        TAstAtomNodeImpl(TPosition pos, const TString& content, ui32 flags, bool isOptionalArg = false)
            : TAstAtomNode(pos, content, flags, isOptionalArg)
        {}

        TNodePtr DoClone() const final {
            return new TAstAtomNodeImpl(Pos, Content, Flags, IsOptionalArg_);
        }
    };

    class TAstDirectNode final: public INode {
    public:
        TAstDirectNode(TAstNode* node);

        TAstNode* Translate(TContext& ctx) const override;

        TPtr DoClone() const final {
            return new TAstDirectNode(Node);
        }
    protected:
        TAstNode* Node;
    };

    class TAstListNode: public INode {
    public:
        TAstListNode(TPosition pos);
        virtual ~TAstListNode();

        TAstNode* Translate(TContext& ctx) const override;

    protected:
        explicit TAstListNode(const TAstListNode& node);
        explicit TAstListNode(TPosition pos, TVector<TNodePtr>&& nodes);
        TPtr ShallowCopy() const override;
        bool DoInit(TContext& ctx, ISource* src) override;
        void DoAdd(TNodePtr node) override;
        void DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const override;

        void DoUpdateState() const override;

        void UpdateStateByListNodes(const TVector<TNodePtr>& Nodes) const;

    protected:
        TVector<TNodePtr> Nodes;
        mutable TMaybe<bool> CacheGroupKey;
    };

    class TAstListNodeImpl final: public TAstListNode {
    public:
        TAstListNodeImpl(TPosition pos);
        TAstListNodeImpl(TPosition pos, TVector<TNodePtr> nodes);
        void CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) override;

    protected:
        TNodePtr DoClone() const final;
    };

    class TCallNode: public TAstListNode {
    public:
        TCallNode(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args);
        TCallNode(TPosition pos, const TString& opName, const TVector<TNodePtr>& args)
            : TCallNode(pos, opName, args.size(), args.size(), args)
        {}

        TString GetOpName() const override;
        const TString* GetSourceName() const override;

        const TVector<TNodePtr>& GetArgs() const;
        TCallNode* GetCallNode() override;
        const TCallNode* GetCallNode() const override;

    protected:
        bool DoInit(TContext& ctx, ISource* src) override;
        bool ValidateArguments(TContext& ctx) const;
        TString GetCallExplain() const;
        void CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) override;

    protected:
        TString OpName;
        i32 MinArgs;
        i32 MaxArgs;
        TVector<TNodePtr> Args;
        mutable TMaybe<bool> CacheGroupKey;

        void DoUpdateState() const override;
    };

    class TCallNodeImpl final: public TCallNode {
        TPtr DoClone() const final;
    public:
        TCallNodeImpl(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args);
        TCallNodeImpl(TPosition pos, const TString& opName, const TVector<TNodePtr>& args);
    };

    class TFuncNodeImpl final : public TCallNode {
        TPtr DoClone() const final;
    public:
        TFuncNodeImpl(TPosition pos, const TString& opName);
        const TString* FuncName() const override;
    };

    class TCallNodeDepArgs final : public TCallNode {
        TPtr DoClone() const final;
    public:
        TCallNodeDepArgs(ui32 reqArgsCount, TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args);
        TCallNodeDepArgs(ui32 reqArgsCount, TPosition pos, const TString& opName, const TVector<TNodePtr>& args);
    protected:
        bool DoInit(TContext& ctx, ISource* src) override;

    private:
        const ui32 ReqArgsCount;
    };

    class TCallDirectRow final : public TCallNode {
        TPtr DoClone() const final;
    public:
        TCallDirectRow(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args);
        TCallDirectRow(TPosition pos, const TString& opName, const TVector<TNodePtr>& args);
    protected:
        bool DoInit(TContext& ctx, ISource* src) override;
        void DoUpdateState() const override;
    };

    class TWinAggrEmulation: public TCallNode {
    protected:
        void DoUpdateState() const override;
        bool DoInit(TContext& ctx, ISource* src) override;
        TPtr WindowSpecFunc(const TNodePtr& type) const override;
    public:
        TWinAggrEmulation(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args);
    protected:
        template<class TNodeType>
        TPtr CallNodeClone() const {
            return new TNodeType(GetPos(), OpName, MinArgs, MaxArgs, CloneContainer(Args));
        }
        TString FuncAlias;
    };

    using TFunctionConfig = TMap<TString, TNodePtr>;

    class TExternalFunctionConfig final: public TAstListNode {
    public:
        TExternalFunctionConfig(TPosition pos, const TFunctionConfig& config)
        : TAstListNode(pos)
        , Config(config)
        {
        }

        bool DoInit(TContext& ctx, ISource* src) override;
        TPtr DoClone() const final;

    private:
        TFunctionConfig Config;
    };

    class TWinRowNumber final: public TWinAggrEmulation {
        TPtr DoClone() const final {
            return CallNodeClone<TWinRowNumber>();
        }
    public:
        TWinRowNumber(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args);
    };

    class TWinCumeDist final: public TWinAggrEmulation {
        TPtr DoClone() const final {
            return CallNodeClone<TWinCumeDist>();
        }

        bool DoInit(TContext& ctx, ISource* src) override;
    public:
        TWinCumeDist(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args);
    };

    class TWinNTile final: public TWinAggrEmulation {
        TPtr DoClone() const final {
            return CallNodeClone<TWinNTile>();
        }
        bool DoInit(TContext& ctx, ISource* src) override;
    public:
        TWinNTile(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args);

    private:
        TSourcePtr FakeSource;
    };

    class TWinLeadLag final: public TWinAggrEmulation {
        TPtr DoClone() const final {
            return CallNodeClone<TWinLeadLag>();
        }
        bool DoInit(TContext& ctx, ISource* src) override;
    public:
        TWinLeadLag(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args);
    };

    class TWinRank final: public TWinAggrEmulation {
        TPtr DoClone() const final {
            return CallNodeClone<TWinRank>();
        }
        bool DoInit(TContext& ctx, ISource* src) override;
    public:
        TWinRank(TPosition pos, const TString& opName, i32 minArgs, i32 maxArgs, const TVector<TNodePtr>& args);
    };

    struct TViewDescription {
        TString ViewName = "";
        bool PrimaryFlag = false;

        bool empty() const { return *this == TViewDescription(); }
        bool operator == (const TViewDescription&) const = default;
    };

    class ITableKeys: public INode {
    public:
        enum class EBuildKeysMode {
            CREATE,
            DROP,
            INPUT,
            WRITE
        };

        ITableKeys(TPosition pos);
        virtual const TString* GetTableName() const;
        virtual TNodePtr BuildKeys(TContext& ctx, EBuildKeysMode mode) = 0;

    protected:
        TNodePtr AddView(TNodePtr key, const TViewDescription& view);

    private:
        /// all TableKeys no clonnable
        TPtr DoClone() const final {
            return {};
        }

        ITableKeys* GetTableKeys() override;
        TAstNode* Translate(TContext& ctx) const override;
    };

    enum class ESampleClause {
        TableSample, //from SQL standard, percantage rate (0..100)
        Sample //simplified (implied Bernulli mode), fraction (0..1)
    };

    enum class ESampleMode {
        Bernoulli,
        System
    };

    class TDeferredAtom {
    public:
        TDeferredAtom();
        TDeferredAtom(TPosition pos, const TString& str);
        TDeferredAtom(TNodePtr node, TContext& ctx);
        const TString* GetLiteral() const;
        bool GetLiteral(TString& value, TContext& ctx) const;
        TNodePtr Build() const;
        TString GetRepr() const;
        bool Empty() const;
        bool HasNode() const;

    private:
        TMaybe<TString> Explicit;
        TNodePtr Node; // atom or evaluation node
        TString Repr;
    };

    struct TTopicRef {
        TString RefName;
        TDeferredAtom Cluster;
        TNodePtr Consumers;
        TNodePtr Settings;
        TNodePtr Keys;

        TTopicRef() = default;
        TTopicRef(const TString& refName, const TDeferredAtom& cluster, TNodePtr keys);
        TTopicRef(const TTopicRef&) = default;
        TTopicRef& operator=(const TTopicRef&) = default;
    };

    struct TIdentifier {
        TPosition Pos;
        TString Name;

        TIdentifier(TPosition pos, const TString& name)
            : Pos(pos)
            , Name(name) {}
    };

    struct TColumnConstraints {
        TNodePtr DefaultExpr;
        bool Nullable = true;

        TColumnConstraints(TNodePtr defaultExpr, bool nullable);
    };

    struct TColumnSchema {
        enum class ETypeOfChange {
            Nothing,
            DropNotNullConstraint,
            SetNotNullConstraint, // todo flown4qqqq
            SetFamily
        };

        TPosition Pos;
        TString Name;
        TNodePtr Type;
        bool Nullable;
        TVector<TIdentifier> Families;
        bool Serial;
        TNodePtr DefaultExpr;
        const ETypeOfChange TypeOfChange;

        TColumnSchema(TPosition pos, const TString& name, const TNodePtr& type, bool nullable,
            TVector<TIdentifier> families, bool serial, TNodePtr defaultExpr, ETypeOfChange typeOfChange = ETypeOfChange::Nothing);
    };

    struct TColumns: public TSimpleRefCount<TColumns> {
        TSet<TString> Real;
        TSet<TString> Artificial;
        TVector<TString> List;
        TVector<bool> NamedColumns;
        bool All = false;
        bool QualifiedAll = false;
        bool HasUnreliable = false;
        bool HasUnnamed = false;

        bool Add(const TString* column, bool countHint, bool isArtificial = false, bool isReliable = true);
        TString AddUnnamed();
        void Merge(const TColumns& columns);
        void SetPrefix(const TString& prefix);
        void SetAll();
        bool IsColumnPossible(TContext& ctx, const TString& column) const;
    };

    class TSortSpecification: public TSimpleRefCount<TSortSpecification> {
    public:
        TSortSpecification(const TNodePtr& orderExpr, bool ascending);
        const TNodePtr OrderExpr;
        const bool Ascending;
        TIntrusivePtr<TSortSpecification> Clone() const;
        ~TSortSpecification() {}
    private:
        const TNodePtr CleanOrderExpr;
    };
    typedef TIntrusivePtr<TSortSpecification> TSortSpecificationPtr;

    enum EFrameType {
        FrameByRows,
        FrameByRange,
        FrameByGroups,
    };
    enum EFrameExclusions {
        FrameExclNone, // same as EXCLUDE NO OTHERS
        FrameExclCurRow,
        FrameExclGroup,
        FrameExclTies,
    };
    enum EFrameSettings {
        // keep order
        FrameUndefined,
        FramePreceding,
        FrameCurrentRow,
        FrameFollowing,
    };

    struct TFrameBound: public TSimpleRefCount<TFrameBound> {
        TPosition Pos;
        TNodePtr Bound;
        EFrameSettings Settings = FrameUndefined;

        TIntrusivePtr<TFrameBound> Clone() const;
        ~TFrameBound() {}
    };
    typedef TIntrusivePtr<TFrameBound> TFrameBoundPtr;


    struct TFrameSpecification: public TSimpleRefCount<TFrameSpecification> {
        EFrameType FrameType = FrameByRows;
        TFrameBoundPtr FrameBegin;
        TFrameBoundPtr FrameEnd;
        EFrameExclusions FrameExclusion = FrameExclNone;

        TIntrusivePtr<TFrameSpecification> Clone() const;
        ~TFrameSpecification() {}
    };
    typedef TIntrusivePtr<TFrameSpecification> TFrameSpecificationPtr;

    struct TLegacyHoppingWindowSpec: public TSimpleRefCount<TLegacyHoppingWindowSpec> {
        TNodePtr TimeExtractor;
        TNodePtr Hop;
        TNodePtr Interval;
        TNodePtr Delay;
        bool DataWatermarks;

        TIntrusivePtr<TLegacyHoppingWindowSpec> Clone() const;
        ~TLegacyHoppingWindowSpec() {}
    };
    typedef TIntrusivePtr<TLegacyHoppingWindowSpec> TLegacyHoppingWindowSpecPtr;

    struct TWindowSpecification: public TSimpleRefCount<TWindowSpecification> {
        TMaybe<TString> ExistingWindowName;
        TVector<TNodePtr> Partitions;
        bool IsCompact = false;
        TVector<TSortSpecificationPtr> OrderBy;
        TNodePtr Session;
        TFrameSpecificationPtr Frame;

        TIntrusivePtr<TWindowSpecification> Clone() const;
        ~TWindowSpecification() {}
    };
    typedef TIntrusivePtr<TWindowSpecification> TWindowSpecificationPtr;
    typedef TMap<TString, TWindowSpecificationPtr> TWinSpecs;

    TWinSpecs CloneContainer(const TWinSpecs& specs);

    void WarnIfAliasFromSelectIsUsedInGroupBy(TContext& ctx, const TVector<TNodePtr>& selectTerms, const TVector<TNodePtr>& groupByTerms,
        const TVector<TNodePtr>& groupByExprTerms);
    bool ValidateAllNodesForAggregation(TContext& ctx, const TVector<TNodePtr>& nodes);

    struct TWriteSettings {
        bool Discard = false;
        TDeferredAtom Label;
    };

    class TColumnNode final: public INode {
    public:
        TColumnNode(TPosition pos, const TString& column, const TString& source, bool maybeType);
        TColumnNode(TPosition pos, const TNodePtr& column, const TString& source);

        virtual ~TColumnNode();
        bool IsAsterisk() const override;
        virtual bool IsArtificial() const;
        const TString* GetColumnName() const override;
        const TString* GetSourceName() const override;
        TColumnNode* GetColumnNode() override;
        const TColumnNode* GetColumnNode() const override;
        TAstNode* Translate(TContext& ctx) const override;
        void ResetColumn(const TString& column, const TString& source);
        void ResetColumn(const TNodePtr& column, const TString& source);

        void SetUseSourceAsColumn();
        void SetUseSource();
        void ResetAsReliable();
        void SetAsNotReliable();
        bool IsReliable() const;
        bool IsUseSourceAsColumn() const;
        bool IsUseSource() const;
        bool CanBeType() const;

    private:
        bool DoInit(TContext& ctx, ISource* src) override;
        TPtr DoClone() const final;

        void DoUpdateState() const override;

    private:
        static const TString Empty;
        TNodePtr Node;
        TString ColumnName;
        TNodePtr ColumnExpr;
        TString Source;
        bool GroupKey = false;
        bool Artificial = false;
        bool Reliable = true;
        bool UseSource = false;
        bool UseSourceAsColumn = false;
        bool MaybeType = false;
    };

    class TArgPlaceholderNode final: public INode
    {
    public:
        TArgPlaceholderNode(TPosition pos, const TString &name);

        TAstNode* Translate(TContext& ctx) const override;

        TString GetName() const;
        TNodePtr DoClone() const final;

    protected:
        bool DoInit(TContext& ctx, ISource* src) override;

    private:
        TString Name;
    };

    enum class EAggregateMode {
        Normal,
        Distinct,
        OverWindow,
        OverWindowDistinct,
    };

    class TTupleNode: public TAstListNode {
    public:
        TTupleNode(TPosition pos, const TVector<TNodePtr>& exprs);

        bool IsEmpty() const;
        const TVector<TNodePtr>& Elements() const;
        TTupleNode* GetTupleNode() override;
        const TTupleNode* GetTupleNode() const override;
        bool DoInit(TContext& ctx, ISource* src) override;
        size_t GetTupleSize() const override;
        TPtr GetTupleElement(size_t index) const override;
        TNodePtr DoClone() const final;
    private:
        void CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) override;
        const TString* GetSourceName() const override;

        const TVector<TNodePtr> Exprs;
    };

    class TStructNode: public TAstListNode {
    public:
        TStructNode(TPosition pos, const TVector<TNodePtr>& exprs, const TVector<TNodePtr>& labels, bool ordered);

        bool DoInit(TContext& ctx, ISource* src) override;
        TNodePtr DoClone() const final;
        const TVector<TNodePtr>& GetExprs() {
            return Exprs;
        }
        TStructNode* GetStructNode() override;
        const TStructNode* GetStructNode() const override;

    private:
        void CollectPreaggregateExprs(TContext& ctx, ISource& src, TVector<INode::TPtr>& exprs) override;
        const TString* GetSourceName() const override;

        const TVector<TNodePtr> Exprs;
        const TVector<TNodePtr> Labels;
        const bool Ordered;
    };


    class TUdfNode: public INode {
    public:
        TUdfNode(TPosition pos, const TVector<TNodePtr>& args);
        bool DoInit(TContext& ctx, ISource* src) override final;
        TNodePtr DoClone() const override final;
        TAstNode* Translate(TContext& ctx) const override;
        const TNodePtr GetExternalTypes() const;
        const TString& GetFunction() const;
        const TString& GetModule() const;
        TNodePtr GetRunConfig() const;
        const TDeferredAtom& GetTypeConfig() const;
        TUdfNode* GetUdfNode() override;
        const TUdfNode* GetUdfNode() const override;
    private:
        TVector<TNodePtr> Args;
        const TString* FunctionName;
        const TString* ModuleName;
        TNodePtr ExternalTypesTuple = nullptr;
        TNodePtr RunConfig;
        TDeferredAtom TypeConfig;
    };

    class IAggregation: public INode {
    public:
        bool IsDistinct() const;

        void DoUpdateState() const override;

        virtual const TString* GetGenericKey() const;

        virtual bool InitAggr(TContext& ctx, bool isFactory, ISource* src, TAstListNode& node, const TVector<TNodePtr>& exprs) = 0;

        virtual std::pair<TNodePtr, bool> AggregationTraits(const TNodePtr& type, bool overState, bool many, bool allowAggApply, TContext& ctx) const;

        virtual TNodePtr AggregationTraitsFactory() const = 0;

        virtual std::vector<ui32> GetFactoryColumnIndices() const;

        virtual void AddFactoryArguments(TNodePtr& apply) const;

        virtual TNodePtr WindowTraits(const TNodePtr& type, TContext& ctx) const;

        const TString& GetName() const;

        EAggregateMode GetAggregationMode() const;
        void MarkKeyColumnAsGenerated();

        virtual void Join(IAggregation* aggr);

    private:
        virtual TNodePtr GetApply(const TNodePtr& type, bool many, bool allowAggApply, TContext& ctx) const = 0;

    protected:
        IAggregation(TPosition pos, const TString& name, const TString& func, EAggregateMode mode);
        TAstNode* Translate(TContext& ctx) const override;
        TNodePtr WrapIfOverState(const TNodePtr& input, bool overState, bool many, TContext& ctx) const;
        virtual TNodePtr GetExtractor(bool many, TContext& ctx) const = 0;

        TString Name;
        TString Func;
        const EAggregateMode AggMode;
        TString DistinctKey;
        bool IsGeneratedKeyColumn = false;
    };

    enum class EExprSeat: int {
        Open = 0,
        FlattenByExpr,
        FlattenBy,
        GroupBy,
        DistinctAggr,
        WindowPartitionBy,
        Max
    };

    enum class EExprType: int {
        WithExpression,
        ColumnOnly,
    };

    enum class EOrderKind: int {
        None,
        Sort,
        Assume,
        Passthrough
    };

    class TListOfNamedNodes final: public INode {
    public:
        TListOfNamedNodes(TPosition pos, TVector<TNodePtr>&& exprs);

        TVector<TNodePtr>* ContentListPtr() override;
        TAstNode* Translate(TContext& ctx) const override;
        TPtr DoClone() const final;
        void DoVisitChildren(const TVisitFunc& func, TVisitNodeSet& visited) const final;
    private:
        TVector<TNodePtr> Exprs;
        TString Meaning;
    };

    class TLiteralNode: public TAstListNode {
    public:
        TLiteralNode(TPosition pos, bool isNull);
        TLiteralNode(TPosition pos, const TString& type, const TString& value);
        TLiteralNode(TPosition pos, const TString& value, ui32 nodeFlags);
        TLiteralNode(TPosition pos, const TString& value, ui32 nodeFlags, const TString& type);
        bool IsNull() const override;
        const TString* GetLiteral(const TString& type) const override;
        void DoUpdateState() const override;
        TPtr DoClone() const override;
        bool IsLiteral() const override;
        TString GetLiteralType() const override;
        TString GetLiteralValue() const override;
    protected:
        bool Null;
        bool Void;
        TString Type;
        TString Value;
    };

    class TAsteriskNode: public INode {
    public:
        TAsteriskNode(TPosition pos);
        bool IsAsterisk() const override;
        TPtr DoClone() const override;
        TAstNode* Translate(TContext& ctx) const override;
    };

    template<typename T>
    class TLiteralNumberNode: public TLiteralNode {
    public:
        TLiteralNumberNode(TPosition pos, const TString& type, const TString& value, bool implicitType = false);
        TPtr DoClone() const override final;
        bool DoInit(TContext& ctx, ISource* src) override;
        bool IsIntegerLiteral() const override;
        TPtr ApplyUnaryOp(TContext& ctx, TPosition pos, const TString& opName) const override;
    private:
        const bool ImplicitType;
    };

    struct TTableArg {
        bool HasAt = false;
        TNodePtr Expr;
        TDeferredAtom Id;
        TViewDescription View;
    };

    class TTableRows final : public INode {
    public:
        TTableRows(TPosition pos, const TVector<TNodePtr>& args);
        TTableRows(TPosition pos, ui32 argsCount);

        bool DoInit(TContext& ctx, ISource* src) override;

        void DoUpdateState() const override;

        TNodePtr DoClone() const final;
        TAstNode* Translate(TContext& ctx) const override;

    private:
        ui32 ArgsCount;
        TNodePtr Node;
    };

    struct TStringContent {
        TString Content;
        NYql::NUdf::EDataSlot Type = NYql::NUdf::EDataSlot::String;
        TMaybe<TString> PgType;
        ui32 Flags = NYql::TNodeFlags::Default;
    };

    TMaybe<TStringContent> StringContent(TContext& ctx, TPosition pos, const TString& input);
    TMaybe<TStringContent> StringContentOrIdContent(TContext& ctx, TPosition pos, const TString& input);

    struct TTtlSettings {
        enum class EUnit {
            Seconds /* "seconds" */,
            Milliseconds /* "milliseconds" */,
            Microseconds /* "microseconds" */,
            Nanoseconds /* "nanoseconds" */,
        };

        struct TTierSettings {
            TNodePtr EvictionDelay;
            std::optional<TIdentifier> StorageName;

            TTierSettings(const TNodePtr& evictionDelay, const std::optional<TIdentifier>& storageName = std::nullopt);
        };

        TIdentifier ColumnName;
        std::vector<TTierSettings> Tiers;
        TMaybe<EUnit> ColumnUnit;

        TTtlSettings(const TIdentifier& columnName, const std::vector<TTierSettings>& tiers, const TMaybe<EUnit>& columnUnit = {});
    };

    struct TTableSettings {
        TNodePtr CompactionPolicy;
        TMaybe<TIdentifier> AutoPartitioningBySize;
        TNodePtr PartitionSizeMb;
        TMaybe<TIdentifier> AutoPartitioningByLoad;
        TNodePtr MinPartitions;
        TNodePtr MaxPartitions;
        TNodePtr PartitionCount;
        TNodePtr UniformPartitions;
        TVector<TVector<TNodePtr>> PartitionAtKeys;
        TMaybe<TIdentifier> KeyBloomFilter;
        TNodePtr ReadReplicasSettings;
        NYql::TResetableSetting<TTtlSettings, void> TtlSettings;
        NYql::TResetableSetting<TNodePtr, void> Tiering;
        TMaybe<TIdentifier> StoreType;
        TNodePtr PartitionByHashFunction;
        TMaybe<TIdentifier> StoreExternalBlobs;

        TNodePtr DataSourcePath;
        NYql::TResetableSetting<TNodePtr, void> Location;
        TVector<NYql::TResetableSetting<std::pair<TIdentifier, TNodePtr>, TIdentifier>> ExternalSourceParameters;

        bool IsSet() const {
            return CompactionPolicy || AutoPartitioningBySize || PartitionSizeMb || AutoPartitioningByLoad
                || MinPartitions || MaxPartitions || UniformPartitions || PartitionAtKeys || KeyBloomFilter
                || ReadReplicasSettings || TtlSettings || Tiering || StoreType || PartitionByHashFunction
                || StoreExternalBlobs || DataSourcePath || Location || ExternalSourceParameters;
        }
    };

    struct TFamilyEntry {
        TFamilyEntry(const TIdentifier& name)
            :Name(name)
        {}

        TIdentifier Name;
        TNodePtr Data;
        TNodePtr Compression;
        TNodePtr CompressionLevel;
    };

    struct TVectorIndexSettings {
        enum class EDistance {
              Cosine        /* "cosine" */
            , Manhattan     /* "manhattan" */
            , Euclidean     /* "euclidean" */
        };

        enum class ESimilarity {
              Cosine        /* "cosine" */
            , InnerProduct  /* "inner_product" */
        };

        enum class EVectorType {
              Float         /* "float" */
            , Uint8         /* "uint8" */
            , Int8          /* "int8" */
            , Bit           /* "bit" */
        };

        std::optional<EDistance> Distance;
        std::optional<ESimilarity> Similarity;
        std::optional<EVectorType> VectorType;
        ui32 VectorDimension = 0;
        ui32 Clusters = 0;
        ui32 Levels = 0;

        bool Validate(TContext& ctx) const;
    };

    struct TIndexDescription {
        enum class EType {
            GlobalSync,
            GlobalAsync,
            GlobalSyncUnique,
            GlobalVectorKmeansTree,
        };

        TIndexDescription(const TIdentifier& name, EType type = EType::GlobalSync)
            : Name(name)
            , Type(type)
        {}

        TIdentifier Name;
        EType Type;
        TVector<TIdentifier> IndexColumns;
        TVector<TIdentifier> DataColumns;
        TTableSettings TableSettings;

        using TIndexSettings = std::variant<std::monostate, TVectorIndexSettings>;
        TIndexSettings IndexSettings;
    };

    struct TChangefeedSettings {
        struct TLocalSinkSettings {
            // no special settings
        };

        TNodePtr Mode;
        TNodePtr Format;
        TNodePtr InitialScan;
        TNodePtr VirtualTimestamps;
        TNodePtr ResolvedTimestamps;
        TNodePtr RetentionPeriod;
        TNodePtr TopicAutoPartitioning;
        TNodePtr TopicPartitions;
        TNodePtr TopicMaxActivePartitions;
        TNodePtr AwsRegion;
        std::optional<std::variant<TLocalSinkSettings>> SinkSettings;
    };

    struct TChangefeedDescription {
        TChangefeedDescription(const TIdentifier& name)
            : Name(name)
            , Disable(false)
        {}

        TIdentifier Name;
        TChangefeedSettings Settings;
        bool Disable;
    };

    struct TCreateTableParameters {
        TVector<TColumnSchema> Columns;
        TVector<TIdentifier> PkColumns;
        TVector<TIdentifier> PartitionByColumns;
        TVector<std::pair<TIdentifier, bool>> OrderByColumns;
        TVector<TIndexDescription> Indexes;
        TVector<TFamilyEntry> ColumnFamilies;
        TVector<TChangefeedDescription> Changefeeds;
        TTableSettings TableSettings;
        ETableType TableType = ETableType::Table;
        bool Temporary = false;
    };

    struct TTableRef;
    struct TAnalyzeParams {
        std::shared_ptr<TTableRef> Table;
        TVector<TString> Columns;
    };

    struct TAlterTableParameters {
        TVector<TColumnSchema> AddColumns;
        TVector<TString> DropColumns;
        TVector<TColumnSchema> AlterColumns;
        TVector<TFamilyEntry> AddColumnFamilies;
        TVector<TFamilyEntry> AlterColumnFamilies;
        TTableSettings TableSettings;
        TVector<TIndexDescription> AddIndexes;
        TVector<TIndexDescription> AlterIndexes;
        TVector<TIdentifier> DropIndexes;
        TMaybe<std::pair<TIdentifier, TIdentifier>> RenameIndexTo;
        TMaybe<TIdentifier> RenameTo;
        TVector<TChangefeedDescription> AddChangefeeds;
        TVector<TChangefeedDescription> AlterChangefeeds;
        TVector<TIdentifier> DropChangefeeds;
        ETableType TableType = ETableType::Table;

        bool IsEmpty() const {
            return AddColumns.empty() && DropColumns.empty() && AlterColumns.empty()
                && AddColumnFamilies.empty() && AlterColumnFamilies.empty()
                && !TableSettings.IsSet()
                && AddIndexes.empty() && AlterIndexes.empty() && DropIndexes.empty() && !RenameIndexTo.Defined()
                && !RenameTo.Defined()
                && AddChangefeeds.empty() && AlterChangefeeds.empty() && DropChangefeeds.empty();
        }
    };

    struct TRoleParameters {
        TMaybe<TDeferredAtom> Password;
        bool IsPasswordEncrypted = false;
        TVector<TDeferredAtom> Roles;
    };

    struct TSequenceParameters {
        bool MissingOk = false;
        TMaybe<TDeferredAtom> StartValue;
        bool IsRestart = false;
        TMaybe<TDeferredAtom> RestartValue;
        TMaybe<TDeferredAtom> Increment;
    };

    struct TTopicConsumerSettings {
        struct TLocalSinkSettings {
            // no special settings
        };

        TNodePtr Important;
        NYql::TResetableSetting<TNodePtr, void> ReadFromTs;
        NYql::TResetableSetting<TNodePtr, void> SupportedCodecs;
    };

    struct TTopicConsumerDescription {
        TTopicConsumerDescription(const TIdentifier& name)
            : Name(name)
        {}

        TIdentifier Name;
        TTopicConsumerSettings Settings;
    };
    struct TTopicSettings {
        NYql::TResetableSetting<TNodePtr, void> MinPartitions;
        NYql::TResetableSetting<TNodePtr, void> MaxPartitions;
        NYql::TResetableSetting<TNodePtr, void> RetentionPeriod;
        NYql::TResetableSetting<TNodePtr, void> RetentionStorage;
        NYql::TResetableSetting<TNodePtr, void> SupportedCodecs;
        NYql::TResetableSetting<TNodePtr, void> PartitionWriteSpeed;
        NYql::TResetableSetting<TNodePtr, void> PartitionWriteBurstSpeed;
        NYql::TResetableSetting<TNodePtr, void> MeteringMode;
        NYql::TResetableSetting<TNodePtr, void> AutoPartitioningStabilizationWindow;
        NYql::TResetableSetting<TNodePtr, void> AutoPartitioningUpUtilizationPercent;
        NYql::TResetableSetting<TNodePtr, void> AutoPartitioningDownUtilizationPercent;
        NYql::TResetableSetting<TNodePtr, void> AutoPartitioningStrategy;

        bool IsSet() const {
            return MinPartitions ||
                   MaxPartitions ||
                   RetentionPeriod ||
                   RetentionStorage ||
                   SupportedCodecs ||
                   PartitionWriteSpeed ||
                   PartitionWriteBurstSpeed ||
                   MeteringMode ||
                   AutoPartitioningStabilizationWindow ||
                   AutoPartitioningUpUtilizationPercent ||
                   AutoPartitioningDownUtilizationPercent ||
                   AutoPartitioningStrategy
            ;
        }
    };


    struct TCreateTopicParameters {
        TVector<TTopicConsumerDescription> Consumers;
        TTopicSettings TopicSettings;
        bool ExistingOk;
    };

    struct TAlterTopicParameters {
        TVector<TTopicConsumerDescription> AddConsumers;
        THashMap<TString, TTopicConsumerDescription> AlterConsumers;
        TVector<TIdentifier> DropConsumers;
        TTopicSettings TopicSettings;
        bool MissingOk;
    };

    struct TDropTopicParameters {
        bool MissingOk;
    };

    struct TCreateBackupCollectionParameters {
        std::map<TString, TDeferredAtom> Settings;

        bool Database;
        TVector<TDeferredAtom> Tables;

        bool ExistingOk;
    };

    struct TAlterBackupCollectionParameters {
        enum class EDatabase {
            Unchanged,
            Add,
            Drop,
        };

        std::map<TString, TDeferredAtom> Settings;
        std::set<TString> SettingsToReset;

        EDatabase Database = EDatabase::Unchanged;
        TVector<TDeferredAtom> TablesToAdd;
        TVector<TDeferredAtom> TablesToDrop;

        bool MissingOk;
    };

    struct TDropBackupCollectionParameters {
        bool MissingOk;
    };

    struct TBackupParameters {
        bool Incremental = false;
    };

    struct TRestoreParameters {
        TString At;
    };

    TString IdContent(TContext& ctx, const TString& str);
    TString IdContentFromString(TContext& ctx, const TString& str);
    TTableHints GetContextHints(TContext& ctx);

    TString TypeByAlias(const TString& alias, bool normalize = true);

    TNodePtr BuildAtom(TPosition pos, const TString& content, ui32 flags = NYql::TNodeFlags::ArbitraryContent,
        bool isOptionalArg = false);
    TNodePtr BuildQuotedAtom(TPosition pos, const TString& content, ui32 flags = NYql::TNodeFlags::ArbitraryContent);

    TNodePtr BuildLiteralNull(TPosition pos);
    TNodePtr BuildLiteralVoid(TPosition pos);
    /// String is checked as quotable, support escaping and multiline
    TNodePtr BuildLiteralSmartString(TContext& ctx, const TString& value);

    struct TExprOrIdent {
        TNodePtr Expr;
        TString Ident;
    };
    TMaybe<TExprOrIdent> BuildLiteralTypedSmartStringOrId(TContext& ctx, const TString& value);

    TNodePtr BuildLiteralRawString(TPosition pos, const TString& value, bool isUtf8 = false);
    TNodePtr BuildLiteralBool(TPosition pos, bool value);
    TNodePtr BuildEmptyAction(TPosition pos);

    TNodePtr BuildTuple(TPosition pos, const TVector<TNodePtr>& exprs);

    TNodePtr BuildStructure(TPosition pos, const TVector<TNodePtr>& exprs);
    TNodePtr BuildStructure(TPosition pos, const TVector<TNodePtr>& exprsUnlabeled, const TVector<TNodePtr>& labels);
    TNodePtr BuildOrderedStructure(TPosition pos, const TVector<TNodePtr>& exprsUnlabeled, const TVector<TNodePtr>& labels);

    TNodePtr BuildListOfNamedNodes(TPosition pos, TVector<TNodePtr>&& exprs);

    TNodePtr BuildArgPlaceholder(TPosition pos, const TString& name);

    TNodePtr BuildColumn(TPosition pos, const TString& column = TString(), const TString& source = TString());
    TNodePtr BuildColumn(TPosition pos, const TNodePtr& column, const TString& source = TString());
    TNodePtr BuildColumn(TPosition pos, const TDeferredAtom& column, const TString& source = TString());
    TNodePtr BuildColumnOrType(TPosition pos, const TString& column = TString());
    TNodePtr BuildAccess(TPosition pos, const TVector<INode::TIdPart>& ids, bool isLookup);
    TNodePtr BuildMatchRecognizeVarAccess(TPosition pos, const TString& var, const TString& column, bool theSameVar);
    TNodePtr BuildBind(TPosition pos, const TString& module, const TString& alias);
    TNodePtr BuildLambda(TPosition pos, TNodePtr params, TNodePtr body, const TString& resName = TString());
    TNodePtr BuildLambda(TPosition pos, TNodePtr params, const TVector<TNodePtr>& bodies);
    TNodePtr BuildDataType(TPosition pos, const TString& typeName);
    TMaybe<TString> LookupSimpleType(const TStringBuf& alias, bool flexibleTypes, bool isPgType);
    TNodePtr BuildSimpleType(TContext& ctx, TPosition pos, const TString& typeName, bool dataOnly);
    TNodePtr BuildIsNullOp(TPosition pos, TNodePtr a);
    TNodePtr BuildBinaryOp(TContext& ctx, TPosition pos, const TString& opName, TNodePtr a, TNodePtr b);
    TNodePtr BuildBinaryOpRaw(TPosition pos, const TString& opName, TNodePtr a, TNodePtr b);

    TNodePtr BuildCalcOverWindow(TPosition pos, const TString& windowName, TNodePtr call);
    TNodePtr BuildYsonOptionsNode(TPosition pos, bool autoConvert, bool strict, bool fastYson);

    TNodePtr BuildDoCall(TPosition pos, const TNodePtr& node);
    TNodePtr BuildTupleResult(TNodePtr tuple, size_t ensureTupleSize);
    TNodePtr BuildNamedExprReference(TNodePtr parent, const TString& name, TMaybe<size_t> tupleIndex);
    TNodePtr BuildNamedExpr(TNodePtr parent);

    // Implemented in aggregation.cpp
    TAggregationPtr BuildFactoryAggregation(TPosition pos, const TString& name, const TString& func, EAggregateMode aggMode, bool multi = false);
    TAggregationPtr BuildKeyPayloadFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    TAggregationPtr BuildPayloadPredicateFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    TAggregationPtr BuildTwoArgsFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    TAggregationPtr BuildHistogramFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    TAggregationPtr BuildLinearHistogramFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    template <bool HasKey>
    TAggregationPtr BuildTopFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    TAggregationPtr BuildTopFreqFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    TAggregationPtr BuildCountDistinctEstimateFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    TAggregationPtr BuildListFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    TAggregationPtr BuildPercentileFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    TAggregationPtr BuildCountAggregation(TPosition pos, const TString& name, const TString& func, EAggregateMode aggMode);
    TAggregationPtr BuildUserDefinedFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);
    TAggregationPtr BuildPGFactoryAggregation(TPosition pos, const TString& name, EAggregateMode aggMode);
    TAggregationPtr BuildNthFactoryAggregation(TPosition pos, const TString& name, const TString& factory, EAggregateMode aggMode);


    // Implemented in builtin.cpp
    TNodePtr BuildCallable(TPosition pos, const TString& module, const TString& name, const TVector<TNodePtr>& args, bool forReduce = false);
    TNodePtr BuildUdf(TContext& ctx, TPosition pos, const TString& module, const TString& name, const TVector<TNodePtr>& args);
    TNodePtr BuildBuiltinFunc(
        TContext& ctx,
        TPosition pos,
        TString name,
        const TVector<TNodePtr>& args,
        const TString& nameSpace = TString(),
        EAggregateMode aggMode = EAggregateMode::Normal,
        bool* mustUseNamed = nullptr,
        bool warnOnYqlNameSpace = true
    );

    // Implemented in query.cpp
    TNodePtr BuildCreateUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TRoleParameters>& params, TScopedStatePtr scoped);
    TNodePtr BuildCreateGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TRoleParameters>& params, TScopedStatePtr scoped);
    TNodePtr BuildAlterUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TRoleParameters& params, TScopedStatePtr scoped);
    TNodePtr BuildRenameUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped);
    TNodePtr BuildAlterGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TVector<TDeferredAtom>& toChange, bool isDrop,
        TScopedStatePtr scoped);
    TNodePtr BuildRenameGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped);
    TNodePtr BuildDropRoles(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& toDrop, bool isUser, bool missingOk, TScopedStatePtr scoped);
    TNodePtr BuildGrantPermissions(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& permissions, const TVector<TDeferredAtom>& schemaPaths, const TVector<TDeferredAtom>& roleName, TScopedStatePtr scoped);
    TNodePtr BuildRevokePermissions(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& permissions, const TVector<TDeferredAtom>& schemaPaths, const TVector<TDeferredAtom>& roleName, TScopedStatePtr scoped);
    TNodePtr BuildUpsertObjectOperation(TPosition pos, const TString& objectId, const TString& typeId,
        std::map<TString, TDeferredAtom>&& features, const TObjectOperatorContext& context);
    TNodePtr BuildCreateObjectOperation(TPosition pos, const TString& objectId, const TString& typeId,
        bool existingOk, bool replaceIfExists, std::map<TString, TDeferredAtom>&& features, const TObjectOperatorContext& context);
    TNodePtr BuildAlterObjectOperation(TPosition pos, const TString& secretId, const TString& typeId,
        std::map<TString, TDeferredAtom>&& features, std::set<TString>&& featuresToReset, const TObjectOperatorContext& context);
    TNodePtr BuildDropObjectOperation(TPosition pos, const TString& secretId, const TString& typeId,
        bool missingOk, std::map<TString, TDeferredAtom>&& options, const TObjectOperatorContext& context);
    TNodePtr BuildCreateAsyncReplication(TPosition pos, const TString& id,
        std::vector<std::pair<TString, TString>>&& targets,
        std::map<TString, TNodePtr>&& settings,
        const TObjectOperatorContext& context);
    TNodePtr BuildAlterAsyncReplication(TPosition pos, const TString& id,
        std::map<TString, TNodePtr>&& settings,
        const TObjectOperatorContext& context);
    TNodePtr BuildDropAsyncReplication(TPosition pos, const TString& id, bool cascade, const TObjectOperatorContext& context);
    TNodePtr BuildWriteResult(TPosition pos, const TString& label, TNodePtr settings);
    TNodePtr BuildCommitClusters(TPosition pos);
    TNodePtr BuildRollbackClusters(TPosition pos);
    TNodePtr BuildQuery(TPosition pos, const TVector<TNodePtr>& blocks, bool topLevel, TScopedStatePtr scoped, bool useSeq);
    TNodePtr BuildPragma(TPosition pos, const TString& prefix, const TString& name, const TVector<TDeferredAtom>& values, bool valueDefault);
    TNodePtr BuildSqlLambda(TPosition pos, TVector<TString>&& args, TVector<TNodePtr>&& exprSeq);
    TNodePtr BuildWorldIfNode(TPosition pos, TNodePtr predicate, TNodePtr thenNode, TNodePtr elseNode, bool isEvaluate);
    TNodePtr BuildWorldForNode(TPosition pos, TNodePtr list, TNodePtr bodyNode, TNodePtr elseNode, bool isEvaluate, bool isParallel);

    TNodePtr BuildCreateTopic(TPosition pos, const TTopicRef& tr, const TCreateTopicParameters& params,
                              TScopedStatePtr scoped);
    TNodePtr BuildAlterTopic(TPosition pos, const TTopicRef& tr, const TAlterTopicParameters& params,
                              TScopedStatePtr scoped);
    TNodePtr BuildDropTopic(TPosition pos, const TTopicRef& topic, const TDropTopicParameters& params,
                            TScopedStatePtr scoped);

    TNodePtr BuildCreateBackupCollection(
        TPosition pos,
        const TString& prefix,
        const TString& id,
        const TCreateBackupCollectionParameters& params,
        const TObjectOperatorContext& context);
    TNodePtr BuildAlterBackupCollection(
        TPosition pos,
        const TString& prefix,
        const TString& id,
        const TAlterBackupCollectionParameters& params,
        const TObjectOperatorContext& context);
    TNodePtr BuildDropBackupCollection(
        TPosition pos,
        const TString& prefix,
        const TString& id,
        const TDropBackupCollectionParameters& params,
        const TObjectOperatorContext& context);

    TNodePtr BuildBackup(
        TPosition pos,
        const TString& prefix,
        const TString& id,
        const TBackupParameters& params,
        const TObjectOperatorContext& context);
    TNodePtr BuildRestore(
        TPosition pos,
        const TString& prefix,
        const TString& id,
        const TRestoreParameters& params,
        const TObjectOperatorContext& context);


    template<class TContainer>
    TMaybe<TString> FindMistypeIn(const TContainer& container, const TString& name) {
        for (auto& item: container) {
            if (NLevenshtein::Distance(name, item) < NYql::DefaultMistypeDistance) {
                return item;
            }
        }
        return {};
    }

    bool Parseui32(TNodePtr from, ui32& to);
    TNodePtr GroundWithExpr(const TNodePtr& ground, const TNodePtr& expr);
    const TString* DeriveCommonSourceName(const TVector<TNodePtr> &nodes);
}  // namespace NSQLTranslationV1