athena_rs 3.0.1

Database gateway API
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
//! Public gateway-facing SDK request types and route constants.
use crate::client::backend::QueryResult;
use crate::client::query_builder::{Condition, ConditionOperator, OrderDirection};
use serde_json::Value;

/// Structured gateway namespace with canonical paths and endpoint builders.
#[derive(Debug, Clone, Copy, Default)]
pub struct Gateway;

impl Gateway {
    /// Canonical gateway route for fetch/select operations.
    pub const FETCH_PATH: &str = "/gateway/fetch";
    /// Canonical gateway route for insert operations.
    pub const INSERT_PATH: &str = "/gateway/insert";
    /// Canonical gateway route for update operations.
    pub const UPDATE_PATH: &str = "/gateway/update";
    /// Canonical gateway route for delete operations.
    pub const DELETE_PATH: &str = "/gateway/delete";
    /// Canonical gateway route for raw query fallback.
    pub const QUERY_PATH: &str = "/gateway/query";
    /// Canonical gateway route for SQL execution.
    pub const SQL_PATH: &str = "/gateway/sql";
    /// Backward-compatible SQL route still used by older servers.
    pub const LEGACY_SQL_PATH: &str = "/query/sql";

    /// Build fully-qualified gateway endpoints from a base URL.
    pub fn routes(base_url: &str) -> GatewayRoutes {
        GatewayRoutes::for_base_url(base_url)
    }

    /// Join base URL and route path into a stable endpoint URL.
    pub fn endpoint(base_url: &str, path: &str) -> String {
        format!(
            "{}/{}",
            base_url.trim_end_matches('/'),
            path.trim_start_matches('/')
        )
    }

    /// Resolve the canonical route path for an operation.
    pub fn path_for(operation: GatewayOperation) -> &'static str {
        operation.gateway_path()
    }

    /// Namespaced request factory.
    pub fn request() -> GatewayRequestFactory {
        GatewayRequestFactory
    }

    /// Const request namespace (`Gateway::REQUEST.delete(...)`).
    pub const REQUEST: GatewayRequestFactory = GatewayRequestFactory;
}

/// Canonical gateway route for fetch/select operations.
pub const GATEWAY_FETCH_PATH: &str = Gateway::FETCH_PATH;
/// Canonical gateway route for insert operations.
pub const GATEWAY_INSERT_PATH: &str = Gateway::INSERT_PATH;
/// Canonical gateway route for update operations.
pub const GATEWAY_UPDATE_PATH: &str = Gateway::UPDATE_PATH;
/// Canonical gateway route for delete operations.
pub const GATEWAY_DELETE_PATH: &str = Gateway::DELETE_PATH;
/// Canonical gateway route for raw query fallback.
pub const GATEWAY_QUERY_PATH: &str = Gateway::QUERY_PATH;
/// Canonical gateway route for SQL execution.
pub const GATEWAY_SQL_PATH: &str = Gateway::SQL_PATH;
/// Backward-compatible SQL route still used by older servers.
pub const LEGACY_SQL_PATH: &str = Gateway::LEGACY_SQL_PATH;

/// Materialized full gateway endpoints for a given base URL.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GatewayRoutes {
    pub fetch: String,
    pub insert: String,
    pub update: String,
    pub delete: String,
    pub query: String,
    pub sql: String,
}

impl GatewayRoutes {
    /// Build fully-qualified gateway endpoints from a base URL.
    pub fn for_base_url(base_url: &str) -> Self {
        Self {
            fetch: Gateway::endpoint(base_url, Gateway::FETCH_PATH),
            insert: Gateway::endpoint(base_url, Gateway::INSERT_PATH),
            update: Gateway::endpoint(base_url, Gateway::UPDATE_PATH),
            delete: Gateway::endpoint(base_url, Gateway::DELETE_PATH),
            query: Gateway::endpoint(base_url, Gateway::QUERY_PATH),
            sql: Gateway::endpoint(base_url, Gateway::SQL_PATH),
        }
    }
}

/// Join base URL and route path into a stable endpoint URL.
pub fn build_gateway_endpoint(base_url: &str, path: &str) -> String {
    Gateway::endpoint(base_url, path)
}

/// Supported SDK gateway operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GatewayOperation {
    Fetch,
    Insert,
    Update,
    Delete,
    Sql,
}

/// Path resolver trait for gateway operations and requests.
pub trait GatewayPath {
    /// Return the canonical HTTP path for this operation/request.
    fn gateway_path(&self) -> &'static str;
}

/// Canonical request contract implemented by all typed gateway requests.
pub trait GatewayDriverRequest: GatewayPath + Clone + Into<GatewayRequest> {
    /// Canonical operation represented by this request type.
    const OPERATION: GatewayOperation;

    /// Return the operation represented by this concrete request value.
    fn operation(&self) -> GatewayOperation {
        Self::OPERATION
    }

    /// Return the canonical HTTP path for this request type.
    fn path() -> &'static str {
        Gateway::path_for(Self::OPERATION)
    }
}

impl GatewayPath for GatewayOperation {
    fn gateway_path(&self) -> &'static str {
        match self {
            GatewayOperation::Fetch => Gateway::FETCH_PATH,
            GatewayOperation::Insert => Gateway::INSERT_PATH,
            GatewayOperation::Update => Gateway::UPDATE_PATH,
            GatewayOperation::Delete => Gateway::DELETE_PATH,
            GatewayOperation::Sql => Gateway::SQL_PATH,
        }
    }
}

/// Canonical query result type returned by gateway SDK methods.
pub type GatewayQueryResult = QueryResult;

/// Typed payload variants for gateway request dispatch.
#[derive(Debug, Clone)]
pub enum GatewayRequestPayload {
    Fetch(GatewayFetchRequest),
    Insert(GatewayInsertRequest),
    Update(GatewayUpdateRequest),
    Delete(GatewayDeleteRequest),
    Sql(GatewaySqlRequest),
}

/// Unified request wrapper for SDK gateway operations.
#[derive(Debug, Clone)]
pub struct GatewayRequest {
    payload: GatewayRequestPayload,
}

impl GatewayRequest {
    /// Create a typed fetch request wrapper.
    pub fn fetch(table: impl Into<String>) -> Self {
        GatewayFetchRequest::new(table).into()
    }

    /// Create a typed insert request wrapper.
    pub fn insert(table: impl Into<String>, payload: Value) -> Self {
        GatewayInsertRequest::new(table, payload).into()
    }

    /// Create a typed update request wrapper.
    pub fn update(table: impl Into<String>, payload: Value) -> Self {
        GatewayUpdateRequest::new(table, payload).into()
    }

    /// Create a typed delete request wrapper.
    pub fn delete(table: impl Into<String>) -> Self {
        GatewayDeleteRequest::new(table).into()
    }

    /// Create a typed SQL request wrapper.
    pub fn sql(query: impl Into<String>) -> Self {
        GatewaySqlRequest::new(query).into()
    }

    /// Return the operation represented by this request.
    pub fn operation(&self) -> GatewayOperation {
        match &self.payload {
            GatewayRequestPayload::Fetch(_) => GatewayOperation::Fetch,
            GatewayRequestPayload::Insert(_) => GatewayOperation::Insert,
            GatewayRequestPayload::Update(_) => GatewayOperation::Update,
            GatewayRequestPayload::Delete(_) => GatewayOperation::Delete,
            GatewayRequestPayload::Sql(_) => GatewayOperation::Sql,
        }
    }

    /// Resolve the canonical route path for this request.
    pub fn path(&self) -> &'static str {
        self.operation().gateway_path()
    }

    /// Borrow the typed payload.
    pub fn payload(&self) -> &GatewayRequestPayload {
        &self.payload
    }

    /// Consume into the typed payload.
    pub fn into_payload(self) -> GatewayRequestPayload {
        self.payload
    }
}

/// Canonical request namespace types (`Fetch`, `Insert`, `Update`, `Delete`, `Sql`).
pub mod request {
    pub type Fetch = super::GatewayFetchRequest;
    pub type Insert = super::GatewayInsertRequest;
    pub type Update = super::GatewayUpdateRequest;
    pub type Delete = super::GatewayDeleteRequest;
    pub type Sql = super::GatewaySqlRequest;
}

/// Namespaced request constructor API for `Gateway::request()`.
#[derive(Debug, Clone, Copy, Default)]
pub struct GatewayRequestFactory;

impl GatewayRequestFactory {
    /// Build a typed fetch request for `/gateway/fetch`.
    pub fn fetch(&self, table: impl Into<String>) -> request::Fetch {
        GatewayFetchRequest::new(table)
    }

    /// Build a typed insert request for `/gateway/insert`.
    pub fn insert(&self, table: impl Into<String>, payload: Value) -> request::Insert {
        GatewayInsertRequest::new(table, payload)
    }

    /// Build a typed update request for `/gateway/update`.
    pub fn update(&self, table: impl Into<String>, payload: Value) -> request::Update {
        GatewayUpdateRequest::new(table, payload)
    }

    /// Build a typed delete request for `/gateway/delete`.
    pub fn delete(&self, table: impl Into<String>) -> request::Delete {
        GatewayDeleteRequest::new(table)
    }

    /// Build a typed SQL request for `/gateway/sql`.
    pub fn sql(&self, query: impl Into<String>) -> request::Sql {
        GatewaySqlRequest::new(query)
    }
}

impl From<GatewayRequestPayload> for GatewayRequest {
    fn from(payload: GatewayRequestPayload) -> Self {
        Self { payload }
    }
}

impl From<GatewayFetchRequest> for GatewayRequest {
    fn from(request: GatewayFetchRequest) -> Self {
        GatewayRequestPayload::Fetch(request).into()
    }
}

impl From<GatewayInsertRequest> for GatewayRequest {
    fn from(request: GatewayInsertRequest) -> Self {
        GatewayRequestPayload::Insert(request).into()
    }
}

impl From<GatewayUpdateRequest> for GatewayRequest {
    fn from(request: GatewayUpdateRequest) -> Self {
        GatewayRequestPayload::Update(request).into()
    }
}

impl From<GatewayDeleteRequest> for GatewayRequest {
    fn from(request: GatewayDeleteRequest) -> Self {
        GatewayRequestPayload::Delete(request).into()
    }
}

impl From<GatewaySqlRequest> for GatewayRequest {
    fn from(request: GatewaySqlRequest) -> Self {
        GatewayRequestPayload::Sql(request).into()
    }
}

/// Typed fetch request for `/gateway/fetch`.
#[derive(Debug, Clone)]
pub struct GatewayFetchRequest {
    pub table: String,
    pub columns: Vec<String>,
    pub raw_select: Option<String>,
    pub conditions: Vec<Condition>,
    pub order_by: Vec<(String, OrderDirection)>,
    pub limit: Option<usize>,
    pub offset: Option<usize>,
}

impl GatewayFetchRequest {
    /// Create a new fetch request.
    pub fn new(table: impl Into<String>) -> Self {
        Self {
            table: table.into(),
            columns: Vec::new(),
            raw_select: None,
            conditions: Vec::new(),
            order_by: Vec::new(),
            limit: None,
            offset: None,
        }
    }

    /// Alias for `new`.
    pub fn fetch(table: impl Into<String>) -> Self {
        Self::new(table)
    }

    /// Set requested columns.
    pub fn columns(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.columns = columns.into_iter().map(Into::into).collect();
        self
    }

    /// Set raw PostgREST select projection.
    pub fn raw_select(mut self, select: impl Into<String>) -> Self {
        self.raw_select = Some(select.into());
        self
    }

    fn add_condition(
        mut self,
        column: impl Into<String>,
        operator: ConditionOperator,
        values: Vec<Value>,
    ) -> Self {
        self.conditions
            .push(Condition::new(column.into(), operator, values));
        self
    }

    /// Add one condition.
    pub fn where_condition(mut self, condition: Condition) -> Self {
        self.conditions.push(condition);
        self
    }

    /// Add multiple conditions.
    pub fn where_conditions(mut self, conditions: impl IntoIterator<Item = Condition>) -> Self {
        self.conditions.extend(conditions);
        self
    }

    /// Add an equality condition.
    pub fn where_eq(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Eq, vec![value.into()])
    }

    /// Add a not-equal condition.
    pub fn where_neq(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Neq, vec![value.into()])
    }

    /// Add a greater-than condition.
    pub fn where_gt(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Gt, vec![value.into()])
    }

    /// Add a less-than condition.
    pub fn where_lt(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Lt, vec![value.into()])
    }

    /// Add an IN condition.
    pub fn where_in(self, column: impl Into<String>, values: Vec<Value>) -> Self {
        self.add_condition(column, ConditionOperator::In, values)
    }

    /// Add an ORDER BY clause.
    pub fn order_by(mut self, column: impl Into<String>, direction: OrderDirection) -> Self {
        self.order_by.push((column.into(), direction));
        self
    }

    /// Set result limit.
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Set result offset.
    pub fn offset(mut self, offset: usize) -> Self {
        self.offset = Some(offset);
        self
    }
}

impl GatewayPath for GatewayFetchRequest {
    fn gateway_path(&self) -> &'static str {
        Gateway::FETCH_PATH
    }
}

impl GatewayDriverRequest for GatewayFetchRequest {
    const OPERATION: GatewayOperation = GatewayOperation::Fetch;
}

/// Marker scope for insert mutations (no filter scope fields).
#[derive(Debug, Clone, Default)]
pub struct GatewayInsertScope;

/// Scope fields for update mutations.
#[derive(Debug, Clone, Default)]
pub struct GatewayUpdateScope {
    pub row_id: Option<String>,
    pub conditions: Vec<Condition>,
    pub allow_unfiltered: bool,
}

/// Shared mutation request implementation used by both insert and update operations.
#[derive(Debug, Clone)]
pub struct GatewayMutationRequest<S> {
    pub table: String,
    pub payload: Value,
    pub scope: S,
}

impl<S: Default> GatewayMutationRequest<S> {
    /// Create a new mutation request.
    pub fn new(table: impl Into<String>, payload: Value) -> Self {
        Self {
            table: table.into(),
            payload,
            scope: S::default(),
        }
    }

    /// Replace payload.
    pub fn payload(mut self, payload: Value) -> Self {
        self.payload = payload;
        self
    }
}

/// Typed insert request for `/gateway/insert`.
pub type GatewayInsertRequest = GatewayMutationRequest<GatewayInsertScope>;

impl GatewayInsertRequest {
    /// Alias for `new`.
    pub fn insert(table: impl Into<String>, payload: Value) -> Self {
        Self::new(table, payload)
    }
}

impl GatewayPath for GatewayInsertRequest {
    fn gateway_path(&self) -> &'static str {
        Gateway::INSERT_PATH
    }
}

impl GatewayDriverRequest for GatewayInsertRequest {
    const OPERATION: GatewayOperation = GatewayOperation::Insert;
}

/// Typed update request for `/gateway/update`.
pub type GatewayUpdateRequest = GatewayMutationRequest<GatewayUpdateScope>;

impl GatewayUpdateRequest {
    /// Alias for `new`.
    pub fn update(table: impl Into<String>, payload: Value) -> Self {
        Self::new(table, payload)
    }

    /// Target a specific row id (`id = <row_id>`).
    pub fn row_id(mut self, row_id: impl Into<String>) -> Self {
        self.scope.row_id = Some(row_id.into());
        self
    }

    fn add_condition(
        mut self,
        column: impl Into<String>,
        operator: ConditionOperator,
        values: Vec<Value>,
    ) -> Self {
        self.scope
            .conditions
            .push(Condition::new(column.into(), operator, values));
        self
    }

    /// Add one condition.
    pub fn where_condition(mut self, condition: Condition) -> Self {
        self.scope.conditions.push(condition);
        self
    }

    /// Add multiple conditions.
    pub fn where_conditions(mut self, conditions: impl IntoIterator<Item = Condition>) -> Self {
        self.scope.conditions.extend(conditions);
        self
    }

    /// Add an equality condition.
    pub fn where_eq(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Eq, vec![value.into()])
    }

    /// Add a not-equal condition.
    pub fn where_neq(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Neq, vec![value.into()])
    }

    /// Add a greater-than condition.
    pub fn where_gt(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Gt, vec![value.into()])
    }

    /// Add a less-than condition.
    pub fn where_lt(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Lt, vec![value.into()])
    }

    /// Add an IN condition.
    pub fn where_in(self, column: impl Into<String>, values: Vec<Value>) -> Self {
        self.add_condition(column, ConditionOperator::In, values)
    }

    /// Explicitly allow unfiltered updates.
    pub fn unsafe_unfiltered(mut self) -> Self {
        self.scope.allow_unfiltered = true;
        self
    }
}

impl GatewayPath for GatewayUpdateRequest {
    fn gateway_path(&self) -> &'static str {
        Gateway::UPDATE_PATH
    }
}

impl GatewayDriverRequest for GatewayUpdateRequest {
    const OPERATION: GatewayOperation = GatewayOperation::Update;
}

/// Typed delete request for `/gateway/delete`.
#[derive(Debug, Clone)]
pub struct GatewayDeleteRequest {
    pub table: String,
    pub row_id: Option<String>,
    pub conditions: Vec<Condition>,
    pub allow_unfiltered: bool,
}

impl GatewayDeleteRequest {
    /// Create a new delete request.
    pub fn new(table: impl Into<String>) -> Self {
        Self {
            table: table.into(),
            row_id: None,
            conditions: Vec::new(),
            allow_unfiltered: false,
        }
    }

    /// Alias for `new`.
    pub fn delete(table: impl Into<String>) -> Self {
        Self::new(table)
    }

    /// Target a specific row id (`id = <row_id>`).
    pub fn row_id(mut self, row_id: impl Into<String>) -> Self {
        self.row_id = Some(row_id.into());
        self
    }

    fn add_condition(
        mut self,
        column: impl Into<String>,
        operator: ConditionOperator,
        values: Vec<Value>,
    ) -> Self {
        self.conditions
            .push(Condition::new(column.into(), operator, values));
        self
    }

    /// Add one condition.
    pub fn where_condition(mut self, condition: Condition) -> Self {
        self.conditions.push(condition);
        self
    }

    /// Add multiple conditions.
    pub fn where_conditions(mut self, conditions: impl IntoIterator<Item = Condition>) -> Self {
        self.conditions.extend(conditions);
        self
    }

    /// Add an equality condition.
    pub fn where_eq(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Eq, vec![value.into()])
    }

    /// Add a not-equal condition.
    pub fn where_neq(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Neq, vec![value.into()])
    }

    /// Add a greater-than condition.
    pub fn where_gt(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Gt, vec![value.into()])
    }

    /// Add a less-than condition.
    pub fn where_lt(self, column: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_condition(column, ConditionOperator::Lt, vec![value.into()])
    }

    /// Add an IN condition.
    pub fn where_in(self, column: impl Into<String>, values: Vec<Value>) -> Self {
        self.add_condition(column, ConditionOperator::In, values)
    }

    /// Explicitly allow unfiltered deletes.
    pub fn unsafe_unfiltered(mut self) -> Self {
        self.allow_unfiltered = true;
        self
    }
}

impl GatewayPath for GatewayDeleteRequest {
    fn gateway_path(&self) -> &'static str {
        Gateway::DELETE_PATH
    }
}

impl GatewayDriverRequest for GatewayDeleteRequest {
    const OPERATION: GatewayOperation = GatewayOperation::Delete;
}

/// Typed SQL request for `/gateway/sql`.
#[derive(Debug, Clone)]
pub struct GatewaySqlRequest {
    pub query: String,
}

impl GatewaySqlRequest {
    /// Create a new SQL request.
    pub fn new(query: impl Into<String>) -> Self {
        Self {
            query: query.into(),
        }
    }

    /// Alias for `new`.
    pub fn sql(query: impl Into<String>) -> Self {
        Self::new(query)
    }
}

impl GatewayPath for GatewaySqlRequest {
    fn gateway_path(&self) -> &'static str {
        Gateway::SQL_PATH
    }
}

impl GatewayDriverRequest for GatewaySqlRequest {
    const OPERATION: GatewayOperation = GatewayOperation::Sql;
}

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

    #[test]
    fn gateway_request_fetch_sets_fetch_shape() {
        let request = GatewayRequest::fetch("users");
        assert_eq!(request.operation(), GatewayOperation::Fetch);
        let GatewayRequestPayload::Fetch(fetch) = request.payload() else {
            panic!("expected fetch payload");
        };
        assert_eq!(fetch.table, "users");
        assert!(fetch.columns.is_empty());
    }

    #[test]
    fn gateway_request_insert_sets_insert_shape() {
        let request = GatewayRequest::insert("users", json!({ "email": "a@example.com" }));
        assert_eq!(request.operation(), GatewayOperation::Insert);
        let GatewayRequestPayload::Insert(insert) = request.payload() else {
            panic!("expected insert payload");
        };
        assert_eq!(insert.table, "users");
        assert_eq!(insert.payload["email"], json!("a@example.com"));
    }

    #[test]
    fn gateway_request_update_sets_update_shape() {
        let request = GatewayRequest::update("users", json!({ "status": "active" }));
        assert_eq!(request.operation(), GatewayOperation::Update);
        let GatewayRequestPayload::Update(update) = request.payload() else {
            panic!("expected update payload");
        };
        assert_eq!(update.table, "users");
        assert_eq!(update.payload["status"], json!("active"));
    }

    #[test]
    fn gateway_request_delete_sets_delete_shape() {
        let request = GatewayRequest::delete("users");
        assert_eq!(request.operation(), GatewayOperation::Delete);
        let GatewayRequestPayload::Delete(delete) = request.payload() else {
            panic!("expected delete payload");
        };
        assert_eq!(delete.table, "users");
        assert!(delete.conditions.is_empty());
    }

    #[test]
    fn gateway_request_sql_sets_sql_shape() {
        let request = GatewayRequest::sql("select 1");
        assert_eq!(request.operation(), GatewayOperation::Sql);
        let GatewayRequestPayload::Sql(sql) = request.payload() else {
            panic!("expected sql payload");
        };
        assert_eq!(sql.query, "select 1");
    }

    #[test]
    fn gateway_fetch_request_builder_sets_expected_shape() {
        let request = GatewayFetchRequest::new("users")
            .columns(["id", "email"])
            .where_eq("status", json!("active"))
            .order_by("id", OrderDirection::Desc)
            .limit(10)
            .offset(5);

        assert_eq!(request.table, "users");
        assert_eq!(request.columns, vec!["id".to_string(), "email".to_string()]);
        assert_eq!(request.conditions.len(), 1);
        assert_eq!(request.limit, Some(10));
        assert_eq!(request.offset, Some(5));
    }

    #[test]
    fn gateway_operation_resolves_canonical_paths() {
        assert_eq!(GatewayOperation::Fetch.gateway_path(), Gateway::FETCH_PATH);
        assert_eq!(
            GatewayOperation::Insert.gateway_path(),
            Gateway::INSERT_PATH
        );
        assert_eq!(
            GatewayOperation::Update.gateway_path(),
            Gateway::UPDATE_PATH
        );
        assert_eq!(
            GatewayOperation::Delete.gateway_path(),
            Gateway::DELETE_PATH
        );
        assert_eq!(GatewayOperation::Sql.gateway_path(), Gateway::SQL_PATH);
    }

    #[test]
    fn gateway_request_path_matches_operation_path() {
        let request = GatewayRequest::delete("users");
        assert_eq!(request.path(), Gateway::DELETE_PATH);
    }

    #[test]
    fn gateway_request_factory_builds_typed_requests() {
        let update = Gateway::request().update("users", json!({ "status": "active" }));
        assert_eq!(update.table, "users");
        assert_eq!(update.payload["status"], json!("active"));

        let delete = Gateway::request().delete("users");
        assert_eq!(delete.table, "users");

        let delete_via_const = Gateway::REQUEST.delete("users");
        assert_eq!(delete_via_const.table, "users");
    }

    #[test]
    fn typed_request_trait_resolves_static_paths() {
        assert_eq!(
            <request::Fetch as GatewayDriverRequest>::path(),
            Gateway::FETCH_PATH
        );
        assert_eq!(
            <request::Insert as GatewayDriverRequest>::path(),
            Gateway::INSERT_PATH
        );
        assert_eq!(
            <request::Update as GatewayDriverRequest>::path(),
            Gateway::UPDATE_PATH
        );
        assert_eq!(
            <request::Delete as GatewayDriverRequest>::path(),
            Gateway::DELETE_PATH
        );
        assert_eq!(
            <request::Sql as GatewayDriverRequest>::path(),
            Gateway::SQL_PATH
        );
    }
}