reifydb-rql 0.4.12

ReifyDB Query Language (RQL) parser and AST
Documentation
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 ReifyDB

use std::{collections, fmt};

use reifydb_catalog::catalog::{
	ringbuffer::RingBufferColumnToCreate, series::SeriesColumnToCreate, table::TableColumnToCreate,
	view::ViewColumnToCreate,
};
use reifydb_core::{
	common::{JoinType, WindowKind},
	interface::{
		catalog::{
			binding::{BindingFormat, BindingProtocol},
			id::{HandlerId, NamespaceId, ProcedureId, RingBufferId, SeriesId, TableId, TestId, ViewId},
			namespace::Namespace,
			procedure::{ProcedureParam, RqlTrigger},
			property::ColumnPropertyKind,
			series::SeriesKey,
		},
		resolved::{
			ResolvedColumn, ResolvedDictionary, ResolvedNamespace, ResolvedRingBuffer, ResolvedSequence,
			ResolvedSeries, ResolvedShape, ResolvedTable, ResolvedTableVirtual, ResolvedView,
		},
	},
	row::RowTtl,
	sort::{SortDirection, SortKey},
};
use reifydb_type::{
	fragment::Fragment,
	value::{
		constraint::TypeConstraint, dictionary::DictionaryId, duration::Duration, sumtype::SumTypeId,
		r#type::Type,
	},
};

use crate::{
	expression::{AliasExpression, Expression, VariableExpression},
	query::QueryPlan,
};

/// Owned primary key definition for physical plan nodes (materialized from bump-allocated logical plan)
#[derive(Debug, Clone)]
pub struct PrimaryKey {
	pub columns: Vec<PrimaryKeyColumn>,
}

/// Owned primary key column for physical plan nodes
#[derive(Debug, Clone)]
pub struct PrimaryKeyColumn {
	pub column: Fragment,
	pub order: Option<SortDirection>,
}

#[derive(Debug, Clone)]
pub enum PhysicalPlan {
	CreateDeferredView(CreateDeferredViewNode),
	CreateTransactionalView(CreateTransactionalViewNode),
	CreateNamespace(CreateNamespaceNode),
	CreateRemoteNamespace(CreateRemoteNamespaceNode),
	CreateTable(CreateTableNode),
	CreateRingBuffer(CreateRingBufferNode),
	CreateDictionary(CreateDictionaryNode),
	CreateSumType(CreateSumTypeNode),
	CreateSubscription(CreateSubscriptionNode),
	CreatePrimaryKey(CreatePrimaryKeyNode),
	CreateColumnProperty(CreateColumnPropertyNode),
	CreateProcedure(CreateProcedureNode),
	CreateSeries(CreateSeriesNode),
	CreateEvent(CreateEventNode),
	CreateTag(CreateTagNode),
	CreateTest(CreateTestNode),
	RunTests(RunTestsNode),

	CreateMigration(CreateMigrationNode),
	Migrate(MigrateNode),
	RollbackMigration(RollbackMigrationNode),
	Dispatch(DispatchNode),
	// Alter
	AlterSequence(AlterSequenceNode),
	AlterTable(AlterTableNode),
	AlterRemoteNamespace(AlterRemoteNamespaceNode),
	// Mutate
	Delete(DeleteTableNode),
	DeleteRingBuffer(DeleteRingBufferNode),
	InsertTable(InsertTableNode),
	InsertRingBuffer(InsertRingBufferNode),
	InsertDictionary(InsertDictionaryNode),
	Update(UpdateTableNode),
	UpdateRingBuffer(UpdateRingBufferNode),
	UpdateSeries(UpdateSeriesNode),
	// Variable assignment
	Declare(DeclareNode),
	Assign(AssignNode),
	Append(AppendPhysicalNode),
	// Variable resolution
	Variable(VariableNode),
	Environment(EnvironmentNode),
	// Control flow
	Conditional(ConditionalNode),
	Loop(LoopPhysicalNode),
	While(WhilePhysicalNode),
	For(ForPhysicalNode),
	Break,
	Continue,
	// User-defined functions
	DefineFunction(DefineFunctionNode),
	Return(ReturnNode),
	CallFunction(CallFunctionNode),

	// Query
	Aggregate(AggregateNode),
	Distinct(DistinctNode),
	Filter(FilterNode),
	IndexScan(IndexScanNode),
	// Row-number optimized access
	RowPointLookup(RowPointLookupNode),
	RowListLookup(RowListLookupNode),
	RowRangeScan(RowRangeScanNode),
	JoinInner(JoinInnerNode),
	JoinLeft(JoinLeftNode),
	JoinNatural(JoinNaturalNode),
	Take(TakeNode),
	Sort(SortNode),
	Map(MapNode),
	Extend(ExtendNode),
	Patch(PatchNode),
	Apply(ApplyNode),
	InlineData(InlineDataNode),
	RemoteScan(RemoteScanNode),
	TableScan(TableScanNode),
	TableVirtualScan(TableVirtualScanNode),
	ViewScan(ViewScanNode),
	RingBufferScan(RingBufferScanNode),
	DictionaryScan(DictionaryScanNode),
	SeriesScan(SeriesScanNode),
	// Series DML
	InsertSeries(InsertSeriesNode),
	DeleteSeries(DeleteSeriesNode),
	Generator(GeneratorNode),
	Window(WindowNode),
	// Auto-scalarization for 1x1 frames
	Scalarize(ScalarizeNode),
	// Auth/Permissions
	CreateIdentity(CreateIdentityNode),
	CreateRole(CreateRoleNode),
	Grant(GrantNode),
	Revoke(RevokeNode),
	DropIdentity(DropIdentityNode),
	DropRole(DropRoleNode),
	CreateAuthentication(CreateAuthenticationNode),
	DropAuthentication(DropAuthenticationNode),
	CreatePolicy(CreatePolicyNode),
	AlterPolicy(AlterPolicyNode),
	DropPolicy(DropPolicyNode),
}

#[derive(Debug, Clone)]
pub enum CompiledViewStorageKind {
	Table,
	RingBuffer {
		capacity: u64,
		propagate_evictions: bool,
		partition_by: Vec<String>,
	},
	Series {
		key: SeriesKey,
	},
}

#[derive(Debug, Clone)]
pub struct CreateDeferredViewNode {
	pub namespace: Namespace, // FIXME REsolvedNamespace
	pub view: Fragment,
	pub if_not_exists: bool,
	pub columns: Vec<ViewColumnToCreate>,
	pub as_clause: Box<QueryPlan>,
	pub storage_kind: CompiledViewStorageKind,
	pub tick: Option<Duration>,
	pub ttl: Option<RowTtl>,
}

#[derive(Debug, Clone)]
pub struct CreateTransactionalViewNode {
	pub namespace: Namespace, // FIXME REsolvedNamespace
	pub view: Fragment,
	pub if_not_exists: bool,
	pub columns: Vec<ViewColumnToCreate>,
	pub as_clause: Box<QueryPlan>,
	pub storage_kind: CompiledViewStorageKind,
	pub tick: Option<Duration>,
	pub ttl: Option<RowTtl>,
}

#[derive(Debug, Clone)]
pub struct CreateNamespaceNode {
	pub segments: Vec<Fragment>,
	pub if_not_exists: bool,
}

#[derive(Debug, Clone)]
pub struct CreateRemoteNamespaceNode {
	pub segments: Vec<Fragment>,
	pub if_not_exists: bool,
	pub grpc: Fragment,
	pub token: Option<Fragment>,
}

#[derive(Debug, Clone)]
pub struct AlterRemoteNamespaceNode {
	pub namespace: Fragment,
	pub grpc: Fragment,
}

#[derive(Debug, Clone)]
pub struct CreateTableNode {
	pub namespace: ResolvedNamespace,
	pub table: Fragment,
	pub if_not_exists: bool,
	pub columns: Vec<TableColumnToCreate>,
	pub ttl: Option<RowTtl>,
}

#[derive(Debug, Clone)]
pub struct CreateRingBufferNode {
	pub namespace: ResolvedNamespace,
	pub ringbuffer: Fragment,
	pub if_not_exists: bool,
	pub columns: Vec<RingBufferColumnToCreate>,
	pub capacity: u64,
	pub partition_by: Vec<String>,
	pub ttl: Option<RowTtl>,
}

#[derive(Debug, Clone)]
pub struct CreateDictionaryNode {
	pub namespace: Namespace,
	pub dictionary: Fragment,
	pub if_not_exists: bool,
	pub value_type: Type,
	pub id_type: Type,
}

#[derive(Debug, Clone)]
pub struct CreateSumTypeNode {
	pub namespace: Namespace,
	pub name: Fragment,
	pub if_not_exists: bool,
	pub variants: Vec<CreateSumTypeVariant>,
}

#[derive(Debug, Clone)]
pub struct CreateSumTypeVariant {
	pub name: String,
	pub columns: Vec<CreateSumTypeColumn>,
}

#[derive(Debug, Clone)]
pub struct CreateSumTypeColumn {
	pub name: String,
	pub column_type: TypeConstraint,
}

#[derive(Debug, Clone)]
pub struct SubscriptionColumnToCreate {
	pub name: String,
	pub ty: Type,
}

#[derive(Debug, Clone)]
pub struct CreateSubscriptionNode {
	pub columns: Vec<SubscriptionColumnToCreate>,
	pub as_clause: Option<Box<QueryPlan>>,
}

#[derive(Debug, Clone)]
pub struct AlterSequenceNode {
	pub sequence: ResolvedSequence,
	pub column: ResolvedColumn,
	pub value: Expression,
}

#[derive(Debug, Clone)]
pub struct AlterTableNode {
	pub namespace: ResolvedNamespace,
	pub table: Fragment,
	pub action: AlterTableAction,
}

#[derive(Debug, Clone)]
pub enum AlterTableAction {
	AddColumn {
		column: TableColumnToCreate,
	},
	DropColumn {
		column: Fragment,
	},
	RenameColumn {
		old_name: Fragment,
		new_name: Fragment,
	},
}

// Create Primary Key node
#[derive(Debug, Clone)]
pub struct CreatePrimaryKeyNode {
	pub namespace: ResolvedNamespace,
	pub table: Fragment,
	pub columns: Vec<PrimaryKeyColumn>,
}

// Create Procedure node
#[derive(Debug, Clone)]
pub struct CreateProcedureNode {
	pub namespace: Namespace,
	pub name: Fragment,
	pub params: Vec<ProcedureParam>,
	pub body_source: String,
	/// Ignored when `is_test = true` (test procedures have no trigger).
	pub trigger: RqlTrigger,
	pub is_test: bool,
}

/// Physical node for CREATE SERIES
#[derive(Debug, Clone)]
pub struct CreateSeriesNode {
	pub namespace: ResolvedNamespace,
	pub series: Fragment,
	pub columns: Vec<SeriesColumnToCreate>,
	pub tag: Option<SumTypeId>,
	pub key: SeriesKey,
	pub ttl: Option<RowTtl>,
}

/// Physical node for CREATE EVENT
#[derive(Debug, Clone)]
pub struct CreateEventNode {
	pub namespace: Namespace,
	pub name: Fragment,
	pub variants: Vec<CreateSumTypeVariant>,
}

/// Physical node for CREATE TAG
#[derive(Debug, Clone)]
pub struct CreateTagNode {
	pub namespace: Namespace,
	pub name: Fragment,
	pub variants: Vec<CreateSumTypeVariant>,
}

/// A resolved key-value config pair
#[derive(Debug, Clone)]
pub struct ConfigPair {
	pub key: Fragment,
	pub value: Fragment,
}

/// Physical node for CREATE SOURCE
#[derive(Debug, Clone)]
pub struct CreateSourceNode {
	pub namespace: Namespace,
	pub name: Fragment,
	pub connector: Fragment,
	pub config: Vec<ConfigPair>,
	pub target_namespace: Namespace,
	pub target_name: Fragment,
}

/// Physical node for CREATE SINK
#[derive(Debug, Clone)]
pub struct CreateSinkNode {
	pub namespace: Namespace,
	pub name: Fragment,
	pub source_namespace: Namespace,
	pub source_name: Fragment,
	pub connector: Fragment,
	pub config: Vec<ConfigPair>,
}

/// Physical node for DROP SOURCE
#[derive(Debug, Clone)]
pub struct DropSourceNode {
	pub if_exists: bool,
	pub namespace: Namespace,
	pub name: Fragment,
	pub cascade: bool,
}

/// Physical node for DROP SINK
#[derive(Debug, Clone)]
pub struct DropSinkNode {
	pub if_exists: bool,
	pub namespace: Namespace,
	pub name: Fragment,
	pub cascade: bool,
}

/// Physical node for CREATE BINDING
#[derive(Debug, Clone)]
pub struct CreateBindingNode {
	pub namespace: Namespace,
	pub name: Fragment,
	pub procedure_id: ProcedureId,
	pub protocol: BindingProtocol,
	pub format: BindingFormat,
}

/// Physical node for DROP BINDING
#[derive(Debug, Clone)]
pub struct DropBindingNode {
	pub namespace: Namespace,
	pub name: Fragment,
	pub if_exists: bool,
}

/// Physical node for DROP PROCEDURE
#[derive(Debug, Clone)]
pub struct DropProcedureNode {
	pub namespace_name: Fragment,
	pub procedure_name: Fragment,
	pub procedure_id: Option<ProcedureId>,
	pub if_exists: bool,
}

/// Physical node for DROP HANDLER
#[derive(Debug, Clone)]
pub struct DropHandlerNode {
	pub namespace_name: Fragment,
	pub handler_name: Fragment,
	pub procedure_id: Option<ProcedureId>,
	pub handler_id: Option<HandlerId>,
	pub if_exists: bool,
}

/// Physical node for DROP TEST
#[derive(Debug, Clone)]
pub struct DropTestNode {
	pub namespace_name: Fragment,
	pub test_name: Fragment,
	pub test_id: Option<TestId>,
	pub if_exists: bool,
}

// Assert Block node (multi-statement ASSERT or ASSERT ERROR)
#[derive(Debug, Clone)]
pub struct AssertBlockNode {
	pub rql: String,
	pub expect_error: bool,
	pub message: Option<String>,
}

// Create Test node
#[derive(Debug, Clone)]
pub struct CreateTestNode {
	pub namespace: Namespace,
	pub name: Fragment,
	pub cases: Option<String>,
	pub body_source: String,
}

// Run Tests node
#[derive(Debug, Clone)]
pub struct RunTestsNode {
	pub scope: RunTestsScope,
}

#[derive(Debug, Clone)]
pub enum RunTestsScope {
	All,
	Namespace(ResolvedNamespace),
	Single(ResolvedNamespace, String),
}

/// Physical node for CREATE MIGRATION
#[derive(Debug, Clone)]
pub struct CreateMigrationNode {
	pub name: String,
	pub body_source: String,
	pub rollback_body_source: Option<String>,
}

/// Physical node for MIGRATE
#[derive(Debug, Clone)]
pub struct MigrateNode {
	pub target: Option<String>,
}

/// Physical node for ROLLBACK MIGRATION
#[derive(Debug, Clone)]
pub struct RollbackMigrationNode {
	pub target: Option<String>,
}

/// Physical node for DISPATCH
#[derive(Debug, Clone)]
pub struct DispatchNode {
	pub namespace: Namespace,
	pub on_sumtype_id: SumTypeId,
	pub variant_name: String,
	pub fields: Vec<(String, Expression)>,
}

// Create Policy node
#[derive(Debug, Clone)]
pub struct CreateColumnPropertyNode {
	pub namespace: ResolvedNamespace,
	pub table: Fragment,
	pub column: Fragment,
	pub properties: Vec<ColumnPropertyKind>,
}

#[derive(Debug, Clone)]
pub enum LetValue {
	Expression(Expression),
	Statement(QueryPlan),
	EmptyFrame,
}

impl fmt::Display for LetValue {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			LetValue::Expression(expr) => write!(f, "{}", expr),
			LetValue::Statement(query) => write!(f, "Statement({:?})", query),
			LetValue::EmptyFrame => write!(f, "EmptyFrame"),
		}
	}
}

#[derive(Debug, Clone)]
pub struct DeclareNode {
	pub name: Fragment,
	pub value: LetValue,
}

#[derive(Debug, Clone)]
pub enum AssignValue {
	Expression(Expression),
	Statement(QueryPlan),
}

impl fmt::Display for AssignValue {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			AssignValue::Expression(expr) => write!(f, "{}", expr),
			AssignValue::Statement(query) => write!(f, "Statement({:?})", query),
		}
	}
}

#[derive(Debug, Clone)]
pub struct AssignNode {
	pub name: Fragment,
	pub value: AssignValue,
}

#[derive(Debug, Clone)]
pub struct VariableNode {
	pub variable_expr: VariableExpression,
}

#[derive(Debug, Clone)]
pub struct EnvironmentNode {}

/// A function parameter in the physical plan
#[derive(Debug, Clone)]
pub struct FunctionParameter {
	/// Parameter name (includes $)
	pub name: Fragment,
	/// Optional type constraint
	pub type_constraint: Option<TypeConstraint>,
}

#[derive(Debug, Clone)]
pub struct ScalarizeNode {
	pub input: Box<QueryPlan>,
	pub fragment: Fragment,
}

#[derive(Debug, Clone)]
pub struct AggregateNode {
	pub input: Box<QueryPlan>,
	pub by: Vec<Expression>,
	pub map: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct DistinctNode {
	pub input: Box<QueryPlan>,
	pub columns: Vec<ResolvedColumn>,
}

#[derive(Debug, Clone)]
pub struct AssertNode {
	pub input: Option<Box<QueryPlan>>,
	pub conditions: Vec<Expression>,
	pub message: Option<String>,
}

#[derive(Debug, Clone)]
pub struct FilterNode {
	pub input: Box<QueryPlan>,
	pub conditions: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct GateNode {
	pub input: Box<QueryPlan>,
	pub conditions: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct DeleteTableNode {
	pub input: Option<Box<QueryPlan>>,
	pub target: Option<ResolvedTable>,
	pub returning: Option<Vec<Expression>>,
}

#[derive(Debug, Clone)]
pub struct InsertTableNode {
	pub input: Box<QueryPlan>,
	pub target: ResolvedTable,
	pub returning: Option<Vec<Expression>>,
}

#[derive(Debug, Clone)]
pub struct InsertRingBufferNode {
	pub input: Box<QueryPlan>,
	pub target: ResolvedRingBuffer,
	pub returning: Option<Vec<Expression>>,
}

#[derive(Debug, Clone)]
pub struct InsertDictionaryNode {
	pub input: Box<QueryPlan>,
	pub target: ResolvedDictionary,
	pub returning: Option<Vec<Expression>>,
}

#[derive(Debug, Clone)]
pub struct UpdateTableNode {
	pub input: Box<QueryPlan>,
	pub target: Option<ResolvedTable>,
	pub returning: Option<Vec<Expression>>,
}

#[derive(Debug, Clone)]
pub struct DeleteRingBufferNode {
	pub input: Option<Box<QueryPlan>>,
	pub target: ResolvedRingBuffer,
	pub returning: Option<Vec<Expression>>,
}

#[derive(Debug, Clone)]
pub struct UpdateRingBufferNode {
	pub input: Box<QueryPlan>,
	pub target: ResolvedRingBuffer,
	pub returning: Option<Vec<Expression>>,
}

#[derive(Debug, Clone)]
pub struct UpdateSeriesNode {
	pub input: Box<QueryPlan>,
	pub target: ResolvedSeries,
	pub returning: Option<Vec<Expression>>,
}

#[derive(Debug, Clone)]
pub struct JoinInnerNode {
	pub left: Box<QueryPlan>,
	pub right: Box<QueryPlan>,
	pub on: Vec<Expression>,
	pub alias: Option<Fragment>,
}

#[derive(Debug, Clone)]
pub struct JoinLeftNode {
	pub left: Box<QueryPlan>,
	pub right: Box<QueryPlan>,
	pub on: Vec<Expression>,
	pub alias: Option<Fragment>,
}

#[derive(Debug, Clone)]
pub struct JoinNaturalNode {
	pub left: Box<QueryPlan>,
	pub right: Box<QueryPlan>,
	pub join_type: JoinType,
	pub alias: Option<Fragment>,
}

#[derive(Debug, Clone)]
pub struct AppendQueryNode {
	pub left: Box<QueryPlan>,
	pub right: Box<QueryPlan>,
}

#[derive(Debug, Clone)]
pub struct SortNode {
	pub input: Box<QueryPlan>,
	pub by: Vec<SortKey>,
}

#[derive(Debug, Clone)]
pub struct MapNode {
	pub input: Option<Box<QueryPlan>>,
	pub map: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct ExtendNode {
	pub input: Option<Box<QueryPlan>>,
	pub extend: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct PatchNode {
	pub input: Option<Box<QueryPlan>>,
	pub assignments: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct ApplyNode {
	pub input: Option<Box<QueryPlan>>,
	pub operator: Fragment, // FIXME becomes OperatorIdentifier
	pub expressions: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct InlineDataNode {
	pub rows: Vec<Vec<AliasExpression>>,
}

#[derive(Debug, Clone)]
pub struct IndexScanNode {
	pub source: ResolvedTable,
	pub index_name: String,
}

#[derive(Debug, Clone)]
pub struct RemoteScanNode {
	pub address: String,
	pub token: Option<String>,
	pub remote_rql: String,
	pub local_namespace: String,
	pub remote_name: String,
	pub variables: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct TableScanNode {
	pub source: ResolvedTable,
}

#[derive(Debug, Clone)]
pub struct ViewScanNode {
	pub source: ResolvedView,
}

#[derive(Debug, Clone)]
pub struct RingBufferScanNode {
	pub source: ResolvedRingBuffer,
}

#[derive(Debug, Clone)]
pub struct DictionaryScanNode {
	pub source: ResolvedDictionary,
}

#[derive(Debug, Clone)]
pub struct SeriesScanNode {
	pub source: ResolvedSeries,
	pub key_range_start: Option<u64>,
	pub key_range_end: Option<u64>,
	pub variant_tag: Option<u8>,
}

#[derive(Debug, Clone)]
pub struct InsertSeriesNode {
	pub input: Box<QueryPlan>,
	pub target: ResolvedSeries,
	pub returning: Option<Vec<Expression>>,
}

#[derive(Debug, Clone)]
pub struct DeleteSeriesNode {
	pub input: Option<Box<QueryPlan>>,
	pub target: ResolvedSeries,
	pub returning: Option<Vec<Expression>>,
}

#[derive(Debug, Clone)]
pub struct GeneratorNode {
	pub name: Fragment,
	pub expressions: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct TableVirtualScanNode {
	pub source: ResolvedTableVirtual,
	pub pushdown_context: Option<TableVirtualPushdownContext>,
}

#[derive(Debug, Clone)]
pub struct TableVirtualPushdownContext {
	pub filters: Vec<Expression>,
	pub projections: Vec<Expression>,
	pub order_by: Vec<SortKey>,
	pub limit: Option<usize>,
}

#[derive(Debug, Clone)]
pub enum TakeLimit {
	Literal(usize),
	Variable(String),
}

impl fmt::Display for TakeLimit {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			TakeLimit::Literal(n) => write!(f, "{}", n),
			TakeLimit::Variable(name) => write!(f, "${}", name),
		}
	}
}

#[derive(Debug, Clone)]
pub struct TakeNode {
	pub input: Box<QueryPlan>,
	pub take: TakeLimit,
}

#[derive(Debug, Clone)]
pub struct WindowNode {
	pub input: Option<Box<QueryPlan>>,
	pub kind: WindowKind,
	pub group_by: Vec<Expression>,
	pub aggregations: Vec<Expression>,
	pub ts: Option<String>,
}

/// O(1) point lookup by row number: `filter rownum == N`
#[derive(Debug, Clone)]
pub struct RowPointLookupNode {
	/// The source to look up in (table, ring buffer, etc.)
	pub source: ResolvedShape,
	/// The row number to fetch
	pub row_number: u64,
}

/// O(k) list lookup by row numbers: `filter rownum in [a, b, c]`
#[derive(Debug, Clone)]
pub struct RowListLookupNode {
	/// The source to look up in
	pub source: ResolvedShape,
	/// The row numbers to fetch
	pub row_numbers: Vec<u64>,
}

/// Range scan by row numbers: `filter rownum between X and Y`
#[derive(Debug, Clone)]
pub struct RowRangeScanNode {
	/// The source to scan
	pub source: ResolvedShape,
	/// Start of the range (inclusive)
	pub start: u64,
	/// End of the range (inclusive)
	pub end: u64,
}

/// APPEND statement physical plan node
#[derive(Debug, Clone)]
pub enum AppendPhysicalNode {
	IntoVariable {
		target: Fragment,
		source: AppendPhysicalSource,
	},
	Query {
		left: Box<QueryPlan>,
		right: Box<QueryPlan>,
	},
}

/// Source for an APPEND physical plan
#[derive(Debug, Clone)]
pub enum AppendPhysicalSource {
	Statement(Vec<PhysicalPlan>),
	Inline(InlineDataNode),
}

#[derive(Debug, Clone)]
pub struct ConditionalNode {
	pub condition: Expression,
	pub then_branch: Box<PhysicalPlan>,
	pub else_ifs: Vec<ElseIfBranch>,
	pub else_branch: Option<Box<PhysicalPlan>>,
}

#[derive(Debug, Clone)]
pub struct ElseIfBranch {
	pub condition: Expression,
	pub then_branch: Box<PhysicalPlan>,
}

#[derive(Debug, Clone)]
pub struct LoopPhysicalNode {
	pub body: Vec<PhysicalPlan>,
}

#[derive(Debug, Clone)]
pub struct WhilePhysicalNode {
	pub condition: Expression,
	pub body: Vec<PhysicalPlan>,
}

#[derive(Debug, Clone)]
pub struct ForPhysicalNode {
	pub variable_name: Fragment,
	pub iterable: Box<PhysicalPlan>,
	pub body: Vec<PhysicalPlan>,
}

#[derive(Debug, Clone)]
pub struct DefineFunctionNode {
	pub name: Fragment,
	pub parameters: Vec<FunctionParameter>,
	pub return_type: Option<TypeConstraint>,
	pub body: Vec<PhysicalPlan>,
}

#[derive(Debug, Clone)]
pub struct ReturnNode {
	pub value: Option<Expression>,
}

#[derive(Debug, Clone)]
pub struct CallFunctionNode {
	pub name: Fragment,
	pub arguments: Vec<Expression>,
	pub is_procedure_call: bool,
}

#[derive(Debug, Clone)]
pub struct DropNamespaceNode {
	pub namespace_name: Fragment,
	pub namespace_id: Option<NamespaceId>,
	pub if_exists: bool,
	pub cascade: bool,
}

#[derive(Debug, Clone)]
pub struct DropTableNode {
	pub namespace_name: Fragment,
	pub table_name: Fragment,
	pub table_id: Option<TableId>,
	pub if_exists: bool,
	pub cascade: bool,
}

#[derive(Debug, Clone)]
pub struct DropViewNode {
	pub namespace_name: Fragment,
	pub view_name: Fragment,
	pub view_id: Option<ViewId>,
	pub if_exists: bool,
	pub cascade: bool,
}

#[derive(Debug, Clone)]
pub struct DropRingBufferNode {
	pub namespace_name: Fragment,
	pub ringbuffer_name: Fragment,
	pub ringbuffer_id: Option<RingBufferId>,
	pub if_exists: bool,
	pub cascade: bool,
}

#[derive(Debug, Clone)]
pub struct DropDictionaryNode {
	pub namespace_name: Fragment,
	pub dictionary_name: Fragment,
	pub dictionary_id: Option<DictionaryId>,
	pub if_exists: bool,
	pub cascade: bool,
}

#[derive(Debug, Clone)]
pub struct DropSumTypeNode {
	pub namespace_name: Fragment,
	pub sumtype_name: Fragment,
	pub sumtype_id: Option<SumTypeId>,
	pub if_exists: bool,
	pub cascade: bool,
}

#[derive(Debug, Clone)]
pub struct DropSubscriptionNode {
	pub subscription_name: Fragment,
	pub if_exists: bool,
	pub cascade: bool,
}

#[derive(Debug, Clone)]
pub struct DropSeriesNode {
	pub namespace_name: Fragment,
	pub series_name: Fragment,
	pub series_id: Option<SeriesId>,
	pub if_exists: bool,
	pub cascade: bool,
}

#[derive(Debug, Clone)]
pub struct CreateIdentityNode {
	pub name: Fragment,
}

#[derive(Debug, Clone)]
pub struct CreateRoleNode {
	pub name: Fragment,
}

#[derive(Debug, Clone)]
pub struct GrantNode {
	pub role: Fragment,
	pub user: Fragment,
}

#[derive(Debug, Clone)]
pub struct RevokeNode {
	pub role: Fragment,
	pub user: Fragment,
}

#[derive(Debug, Clone)]
pub struct DropIdentityNode {
	pub name: Fragment,
	pub if_exists: bool,
}

#[derive(Debug, Clone)]
pub struct DropRoleNode {
	pub name: Fragment,
	pub if_exists: bool,
}

#[derive(Debug, Clone)]
pub struct CreateAuthenticationNode {
	pub user: Fragment,
	pub method: Fragment,
	pub config: collections::HashMap<String, String>,
}

#[derive(Debug, Clone)]
pub struct DropAuthenticationNode {
	pub user: Fragment,
	pub method: Fragment,
	pub if_exists: bool,
}

#[derive(Debug, Clone)]
pub struct CreatePolicyNode {
	pub name: Option<Fragment>,
	pub target_type: String,
	pub scope_namespace: Option<Fragment>,
	pub scope_shape: Option<Fragment>,
	pub operations: Vec<PolicyOperationNode>,
}

#[derive(Debug, Clone)]
pub struct PolicyOperationNode {
	pub operation: String,
	pub body_source: String,
}

#[derive(Debug, Clone)]
pub struct AlterPolicyNode {
	pub target_type: String,
	pub name: Fragment,
	pub enable: bool,
}

#[derive(Debug, Clone)]
pub struct DropPolicyNode {
	pub target_type: String,
	pub name: Fragment,
	pub if_exists: bool,
}