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
#![deny(unused_crate_dependencies)]

use crate::directives::IndexMethod;
use serde::{Deserialize, Serialize};
use std::{
    collections::{HashMap, HashSet},
    fmt,
    fmt::Write,
    string::ToString,
    time::{SystemTime, UNIX_EPOCH},
};
use strum::{AsRefStr, EnumString};

pub mod directives;

#[derive(Debug)]
pub struct RootColumns {
    pub id: i64,
    pub root_id: i64,
    pub column_name: String,
    pub graphql_type: String,
}

#[derive(Debug)]
pub struct NewRootColumns {
    pub root_id: i64,
    pub column_name: String,
    pub graphql_type: String,
}

#[derive(Debug)]
pub struct GraphRoot {
    pub id: i64,
    pub version: String,
    pub schema_name: String,
    pub schema_identifier: String,
    pub query: String,
    pub schema: String,
}

#[derive(Debug)]
pub struct NewGraphRoot {
    pub version: String,
    pub schema_name: String,
    pub schema_identifier: String,
    pub query: String,
    pub schema: String,
}

#[derive(Debug)]
pub struct TypeId {
    pub id: i64,
    pub schema_version: String,
    pub schema_name: String,
    pub schema_identifier: String,
    pub graphql_name: String,
    pub table_name: String,
}

#[derive(Debug)]
pub struct IdLatest {
    pub schema_version: String,
}

#[derive(Debug)]
pub struct NumVersions {
    pub num: Option<i64>,
}

#[derive(Clone, Debug)]
pub struct NewColumn {
    pub type_id: i64,
    pub column_position: i32,
    pub column_name: String,
    pub column_type: String,
    pub nullable: bool,
    pub graphql_type: String,
    pub unique: bool,
}

#[derive(Debug)]
pub struct Columns {
    pub id: i64,
    pub type_id: i64,
    pub column_position: i32,
    pub column_name: String,
    pub column_type: String,
    pub nullable: bool,
    pub graphql_type: String,
}

impl NewColumn {
    pub fn sql_fragment(&self) -> String {
        let null_frag = if self.nullable { "" } else { "not null" };
        let unique_frag = if self.unique { "unique" } else { "" };
        format!(
            "{} {} {} {}",
            self.column_name,
            self.sql_type(),
            null_frag,
            unique_frag
        )
        .trim()
        .to_string()
    }

    fn sql_type(&self) -> &str {
        match ColumnType::from(self.column_type.as_str()) {
            ColumnType::ID => "bigint primary key",
            ColumnType::Address => "varchar(64)",
            ColumnType::Bytes4 => "varchar(8)",
            ColumnType::Bytes8 => "varchar(16)",
            ColumnType::Bytes32 => "varchar(64)",
            ColumnType::AssetId => "varchar(64)",
            ColumnType::ContractId => "varchar(64)",
            ColumnType::Salt => "varchar(64)",
            ColumnType::Int4 => "integer",
            ColumnType::Int8 => "bigint",
            ColumnType::Int16 => "numeric",
            ColumnType::UInt4 => "integer",
            ColumnType::UInt8 => "bigint",
            ColumnType::UInt16 => "numeric",
            ColumnType::Timestamp => "timestamp",
            ColumnType::Object => "bytea",
            ColumnType::Blob => "varchar(10485760)",
            ColumnType::ForeignKey => {
                panic!("ForeignKey ColumnType is a reference type only.")
            }
            ColumnType::Json => "Json",
            ColumnType::MessageId => "varchar(64)",
            ColumnType::Charfield => "varchar(255)",
            ColumnType::Identity => "varchar(66)",
            ColumnType::Boolean => "boolean",
        }
    }
}

#[derive(Debug)]
pub struct ColumnInfo {
    pub type_id: i64,
    pub table_name: String,
    pub column_position: i32,
    pub column_name: String,
    pub column_type: String,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ColumnType {
    ID = 0,
    Address = 1,
    AssetId = 2,
    Bytes4 = 3,
    Bytes8 = 4,
    Bytes32 = 5,
    ContractId = 6,
    Salt = 7,
    Int4 = 8,
    Int8 = 9,
    UInt4 = 10,
    UInt8 = 11,
    Timestamp = 12,
    Blob = 13,
    ForeignKey = 14,
    Json = 15,
    MessageId = 16,
    Charfield = 17,
    Identity = 18,
    Boolean = 19,
    Object = 20,
    UInt16 = 21,
    Int16 = 22,
}

impl From<ColumnType> for i32 {
    fn from(typ: ColumnType) -> i32 {
        match typ {
            ColumnType::ID => 0,
            ColumnType::Address => 1,
            ColumnType::AssetId => 2,
            ColumnType::Bytes4 => 3,
            ColumnType::Bytes8 => 4,
            ColumnType::Bytes32 => 5,
            ColumnType::ContractId => 6,
            ColumnType::Salt => 7,
            ColumnType::Int4 => 8,
            ColumnType::Int8 => 9,
            ColumnType::UInt4 => 10,
            ColumnType::UInt8 => 11,
            ColumnType::Timestamp => 12,
            ColumnType::Blob => 13,
            ColumnType::ForeignKey => 14,
            ColumnType::Json => 15,
            ColumnType::MessageId => 16,
            ColumnType::Charfield => 17,
            ColumnType::Identity => 18,
            ColumnType::Boolean => 19,
            ColumnType::Object => 20,
            ColumnType::UInt16 => 21,
            ColumnType::Int16 => 22,
        }
    }
}

impl fmt::Display for ColumnType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

impl From<i32> for ColumnType {
    fn from(num: i32) -> ColumnType {
        match num {
            0 => ColumnType::ID,
            1 => ColumnType::Address,
            2 => ColumnType::AssetId,
            3 => ColumnType::Bytes4,
            4 => ColumnType::Bytes8,
            5 => ColumnType::Bytes32,
            6 => ColumnType::ContractId,
            7 => ColumnType::Salt,
            8 => ColumnType::Int4,
            9 => ColumnType::Int8,
            10 => ColumnType::UInt4,
            11 => ColumnType::UInt8,
            12 => ColumnType::Timestamp,
            13 => ColumnType::Blob,
            14 => ColumnType::ForeignKey,
            15 => ColumnType::Json,
            16 => ColumnType::MessageId,
            17 => ColumnType::Charfield,
            18 => ColumnType::Identity,
            19 => ColumnType::Boolean,
            20 => ColumnType::Object,
            21 => ColumnType::Int16,
            22 => ColumnType::UInt16,
            _ => panic!("Invalid column type."),
        }
    }
}

impl From<&str> for ColumnType {
    fn from(name: &str) -> ColumnType {
        match name {
            "ID" => ColumnType::ID,
            "Address" => ColumnType::Address,
            "AssetId" => ColumnType::AssetId,
            "Bytes4" => ColumnType::Bytes4,
            "Bytes8" => ColumnType::Bytes8,
            "Bytes32" => ColumnType::Bytes32,
            "ContractId" => ColumnType::ContractId,
            "Salt" => ColumnType::Salt,
            "Int4" => ColumnType::Int4,
            "Int8" => ColumnType::Int8,
            "UInt4" => ColumnType::UInt4,
            "UInt8" => ColumnType::UInt8,
            "Timestamp" => ColumnType::Timestamp,
            "Blob" => ColumnType::Blob,
            "ForeignKey" => ColumnType::ForeignKey,
            "Json" => ColumnType::Json,
            "MessageId" => ColumnType::MessageId,
            "Charfield" => ColumnType::Charfield,
            "Identity" => ColumnType::Identity,
            "Boolean" => ColumnType::Boolean,
            "Object" => ColumnType::Object,
            "UInt16" => ColumnType::UInt16,
            "Int16" => ColumnType::Int16,
            _ => panic!("Invalid column type: '{name}'"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct IndexAsset {
    pub id: i64,
    pub index_id: i64,
    pub version: i32,
    pub digest: String,
    #[serde(skip_serializing)]
    pub bytes: Vec<u8>,
}

#[derive(Debug)]
pub struct IndexAssetBundle {
    pub schema: IndexAsset,
    pub manifest: IndexAsset,
    pub wasm: IndexAsset,
}

#[derive(Debug, Eq, PartialEq, Hash, Clone, EnumString, AsRefStr)]
pub enum IndexAssetType {
    #[strum(serialize = "wasm")]
    Wasm,
    #[strum(serialize = "manifest")]
    Manifest,
    #[strum(serialize = "schema")]
    Schema,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RegisteredIndex {
    pub id: i64,
    pub namespace: String,
    pub identifier: String,
    pub pubkey: Option<String>,
}

impl RegisteredIndex {
    pub fn uid(&self) -> String {
        format!("{}.{}", self.namespace, self.identifier)
    }
}

#[derive(Eq, PartialEq, Debug, Clone, Default)]
pub enum DbType {
    #[default]
    Postgres,
}

impl DbType {
    pub fn table_name(&self, namespace: &str, table_name: &str) -> String {
        match self {
            DbType::Postgres => format!("{namespace}.{table_name}"),
        }
    }
}

pub trait CreateStatement {
    fn create_statement(&self) -> String;
}

#[derive(Debug)]
pub struct ColumnIndex {
    pub db_type: DbType,
    pub table_name: String,
    pub namespace: String,
    pub method: IndexMethod,
    pub unique: bool,
    pub column_name: String,
}

impl ColumnIndex {
    pub fn name(&self) -> String {
        format!("{}_{}_idx", &self.table_name, &self.column_name)
    }
}

impl CreateStatement for ColumnIndex {
    fn create_statement(&self) -> String {
        let mut frag = "CREATE ".to_string();
        if self.unique {
            frag += "UNIQUE ";
        }

        match self.db_type {
            DbType::Postgres => {
                let _ = write!(
                    frag,
                    "INDEX {} ON {}.{} USING {} ({});",
                    self.name(),
                    self.namespace,
                    self.table_name,
                    self.method.as_ref(),
                    self.column_name
                );
            }
        }

        frag
    }
}

#[derive(Debug, Clone, Copy, Default, EnumString, AsRefStr)]
pub enum OnDelete {
    #[default]
    #[strum(serialize = "NO ACTION")]
    NoAction,
    #[strum(serialize = "CASCADE")]
    Cascade,
    #[strum(serialize = "SET NULL")]
    SetNull,
}

#[derive(Debug, Clone, Copy, Default, EnumString, AsRefStr)]
pub enum OnUpdate {
    #[default]
    #[strum(serialize = "NO ACTION")]
    NoAction,
}

#[derive(Debug, Clone, Default)]
pub struct ForeignKey {
    pub db_type: DbType,
    pub namespace: String,
    pub table_name: String,
    pub column_name: String,
    pub reference_table_name: String,
    pub reference_column_name: String,
    pub reference_column_type: String,
    pub on_delete: OnDelete,
    pub on_update: OnUpdate,
}

impl ForeignKey {
    pub fn new(
        db_type: DbType,
        namespace: String,
        table_name: String,
        column_name: String,
        reference_table_name: String,
        ref_column_name: String,
        reference_column_type: String,
    ) -> Self {
        Self {
            db_type,
            namespace,
            table_name,
            column_name,
            reference_column_name: ref_column_name,
            reference_table_name,
            reference_column_type,
            ..Default::default()
        }
    }

    pub fn name(&self) -> String {
        format!(
            "fk_{}_{}__{}_{}",
            self.table_name,
            self.column_name,
            self.reference_table_name,
            self.reference_column_name
        )
    }
}

impl CreateStatement for ForeignKey {
    fn create_statement(&self) -> String {
        match self.db_type {
            DbType::Postgres => {
                format!(
                    "ALTER TABLE {}.{} ADD CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {}.{}({}) ON DELETE {} ON UPDATE {} INITIALLY DEFERRED;",
                    self.namespace,
                    self.table_name,
                    self.name(),
                    self.column_name,
                    self.namespace,
                    self.reference_table_name,
                    self.reference_column_name,
                    self.on_delete.as_ref(),
                    self.on_update.as_ref()
                )
            }
        }
    }
}

//
pub struct IdCol {}
impl IdCol {
    pub fn to_lowercase_string() -> String {
        "id".to_string()
    }

    pub fn to_uppercase_string() -> String {
        "ID".to_string()
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum QueryElement {
    Field { key: String, value: String },
    ObjectOpeningBoundary { key: String },
    ObjectClosingBoundary,
}

// TODO: Adjust filter to allow for more complex filtering
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct QueryFilter {
    pub key: String,
    pub relation: String,
    pub value: String,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct JoinCondition {
    pub referencing_key_table: String,
    pub referencing_key_col: String,
    pub primary_key_table: String,
    pub primary_key_col: String,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct QueryJoinNode {
    pub dependencies: HashMap<String, JoinCondition>,
    pub dependents: HashMap<String, JoinCondition>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct UserQuery {
    pub elements: Vec<QueryElement>,
    pub joins: HashMap<String, QueryJoinNode>,
    pub namespace_identifier: String,
    pub entity_name: String,
    pub filters: Vec<QueryFilter>,
}

impl UserQuery {
    // TODO: Add proper parsing for filtering
    pub fn to_sql(&mut self, db_type: &DbType) -> String {
        // Different database solutions have unique ways of
        // constructing JSON-formatted queries and results.
        match db_type {
            DbType::Postgres => {
                let elements = self.parse_query_elements(db_type);

                let _filters: Vec<String> = self
                    .filters
                    .iter()
                    .map(|f| format!("{} {} {}", f.key, f.relation, f.value))
                    .collect();

                let elements_string = elements.join("");

                let sorted_joins = self.get_topologically_sorted_joins();

                let mut last_seen_primary_key_table = "".to_string();
                let mut joins: Vec<String> = Vec::new();

                for sj in sorted_joins {
                    if sj.primary_key_table == last_seen_primary_key_table {
                        if let Some(elem) = joins.last_mut() {
                            let join_condition = format!(
                                "{}.{} = {}.{}",
                                sj.referencing_key_table,
                                sj.referencing_key_col,
                                sj.primary_key_table,
                                sj.primary_key_col
                            );
                            *elem = format!("{elem} AND {join_condition}")
                        }
                    } else {
                        joins.push(format!(
                            "INNER JOIN {} ON {}.{} = {}.{}",
                            sj.primary_key_table,
                            sj.referencing_key_table,
                            sj.referencing_key_col,
                            sj.primary_key_table,
                            sj.primary_key_col
                        ));
                        last_seen_primary_key_table = sj.primary_key_table;
                    }
                }

                format!(
                    "SELECT json_build_object({}) FROM {}.{} {}",
                    elements_string,
                    self.namespace_identifier,
                    self.entity_name,
                    joins.join(" ")
                )
            }
        }
    }

    fn parse_query_elements(&self, db_type: &DbType) -> Vec<String> {
        let mut peekable_elements = self.elements.iter().peekable();

        let mut elements = Vec::new();

        match db_type {
            DbType::Postgres => {
                while let Some(e) = peekable_elements.next() {
                    match e {
                        // Set the key for this JSON element to the name of the entity field
                        // and the value to the corresponding database table so that it can
                        // be successfully retrieved.
                        QueryElement::Field { key, value } => {
                            elements.push(format!("'{key}', {value}"));

                            // If the next element is not a closing boundary, then a comma should
                            // be added so that the resultant SQL query can be properly constructed.
                            if let Some(next_element) = peekable_elements.peek() {
                                match next_element {
                                    QueryElement::Field { .. }
                                    | QueryElement::ObjectOpeningBoundary { .. } => {
                                        elements.push(", ".to_string());
                                    }
                                    _ => {}
                                }
                            }
                        }

                        // Set a nested JSON object as the value for this entity field.
                        QueryElement::ObjectOpeningBoundary { key } => {
                            elements.push(format!("'{key}', json_build_object("))
                        }

                        QueryElement::ObjectClosingBoundary => {
                            elements.push(")".to_string());

                            if let Some(next_element) = peekable_elements.peek() {
                                match next_element {
                                    QueryElement::Field { .. }
                                    | QueryElement::ObjectOpeningBoundary { .. } => {
                                        elements.push(", ".to_string());
                                    }
                                    _ => {}
                                }
                            }
                        }
                    }
                }
            }
        }

        elements
    }

    fn get_topologically_sorted_joins(&mut self) -> Vec<JoinCondition> {
        let mut yet_to_process =
            self.joins.clone().into_keys().collect::<HashSet<String>>();
        let mut start_nodes: Vec<String> = self
            .joins
            .iter()
            .filter(|(_k, v)| v.dependencies.is_empty())
            .map(|(k, _v)| k.clone())
            .collect();

        let mut sorted_joins: Vec<JoinCondition> = Vec::new();

        while let Some(current_node) = start_nodes.pop() {
            if let Some(node) = self.joins.get_mut(&current_node) {
                for (dependent_node, _) in node.clone().dependents.iter() {
                    if let Some(or) = self.joins.get_mut(dependent_node) {
                        if let Some(dependency) = or.dependencies.remove(&current_node) {
                            sorted_joins.push(dependency);
                            if or.dependencies.is_empty() {
                                start_nodes.push(dependent_node.clone());
                            }
                        }
                    }
                }
            }

            yet_to_process.remove(&current_node);
        }

        sorted_joins.into_iter().rev().collect()
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Nonce {
    pub uid: String,
    pub expiry: i64,
}

impl Nonce {
    pub fn is_expired(&self) -> bool {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;

        now >= self.expiry
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_user_query_parse_query_elements() {
        let elements = vec![
            QueryElement::Field {
                key: "flat_field_key".to_string(),
                value: "flat_value".to_string(),
            },
            QueryElement::ObjectOpeningBoundary {
                key: "nested_object_key".to_string(),
            },
            QueryElement::Field {
                key: "nested_field_key".to_string(),
                value: "nested_field_value".to_string(),
            },
            QueryElement::ObjectClosingBoundary,
        ];
        let uq = UserQuery {
            elements,
            joins: HashMap::new(),
            namespace_identifier: "".to_string(),
            entity_name: "".to_string(),
            filters: Vec::new(),
        };

        let expected = vec![
            "'flat_field_key', flat_value".to_string(),
            ", ".to_string(),
            "'nested_object_key', json_build_object(".to_string(),
            "'nested_field_key', nested_field_value".to_string(),
            ")".to_string(),
        ];

        assert_eq!(expected, uq.parse_query_elements(&DbType::Postgres));
    }

    #[test]
    fn test_user_query_to_sql() {
        let elements = vec![
            QueryElement::Field {
                key: "hash".to_string(),
                value: "name_ident.block.hash".to_string(),
            },
            QueryElement::ObjectOpeningBoundary {
                key: "tx".to_string(),
            },
            QueryElement::Field {
                key: "hash".to_string(),
                value: "name_ident.tx.hash".to_string(),
            },
            QueryElement::ObjectClosingBoundary,
            QueryElement::Field {
                key: "height".to_string(),
                value: "name_ident.block.height".to_string(),
            },
        ];

        let mut uq = UserQuery {
            elements,
            joins: HashMap::from([
                (
                    "name_ident.block".to_string(),
                    QueryJoinNode {
                        dependencies: HashMap::new(),
                        dependents: HashMap::from([(
                            "name_ident.tx".to_string(),
                            JoinCondition {
                                referencing_key_table: "name_ident.tx".to_string(),
                                referencing_key_col: "block".to_string(),
                                primary_key_table: "name_ident.block".to_string(),
                                primary_key_col: "id".to_string(),
                            },
                        )]),
                    },
                ),
                (
                    "name_ident.tx".to_string(),
                    QueryJoinNode {
                        dependents: HashMap::new(),
                        dependencies: HashMap::from([(
                            "name_ident.block".to_string(),
                            JoinCondition {
                                referencing_key_table: "name_ident.tx".to_string(),
                                referencing_key_col: "block".to_string(),
                                primary_key_table: "name_ident.block".to_string(),
                                primary_key_col: "id".to_string(),
                            },
                        )]),
                    },
                ),
            ]),
            namespace_identifier: "name_ident".to_string(),
            entity_name: "entity_name".to_string(),
            filters: vec![QueryFilter {
                key: "a".to_string(),
                relation: "=".to_string(),
                value: "123".to_string(),
            }],
        };

        let expected = "SELECT json_build_object('hash', name_ident.block.hash, 'tx', json_build_object('hash', name_ident.tx.hash), 'height', name_ident.block.height) FROM name_ident.entity_name INNER JOIN name_ident.block ON name_ident.tx.block = name_ident.block.id"
            .to_string();
        assert_eq!(expected, uq.to_sql(&DbType::Postgres));
    }
}