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
use rorm_db::sql::aggregation::SelectAggregator;
use rorm_db::sql::join_table::JoinType;
use rorm_db::sql::limit_clause::LimitClause;
use rorm_db::sql::ordering::Ordering;
use rorm_db::sql::value::NullType;
use rorm_db::{DatabaseConfiguration, DatabaseDriver};

use crate::utils::FFIOption;
use crate::{Error, FFIDate, FFIDateTime, FFISlice, FFIString, FFITime};

/**
Representation of the database backend.

This is used to determine the correct driver and the correct dialect to use.
 */
#[repr(i32)]
pub enum DBBackend {
    /// This exists to forbid default initializations with 0 on C side.
    /// Using this type will result in an [Error::ConfigurationError]
    Invalid,
    /// SQLite backend
    SQLite,
    /// MySQL / MariaDB backend
    MySQL,
    /// Postgres backend
    Postgres,
}

/**
Configuration operation to connect to a database.

Will be converted into [DatabaseConfiguration].

`min_connections` and `max_connections` must not be 0.
 */
#[repr(C)]
pub struct DBConnectOptions<'a> {
    backend: DBBackend,
    name: FFIString<'a>,
    host: FFIString<'a>,
    port: u16,
    user: FFIString<'a>,
    password: FFIString<'a>,
    min_connections: u32,
    max_connections: u32,
}

impl From<DBConnectOptions<'_>> for Result<DatabaseConfiguration, Error<'_>> {
    fn from(config: DBConnectOptions) -> Self {
        if config.min_connections == 0 || config.max_connections == 0 {
            return Err(Error::ConfigurationError(FFIString::from(
                "DBConnectOptions.min_connections and DBConnectOptions.max_connections must not be 0",
            )));
        }

        let d = match config.backend {
            DBBackend::Invalid => {
                return Err(Error::ConfigurationError(FFIString::from(
                    "Invalid database backend selected",
                )))
            }
            DBBackend::SQLite => DatabaseDriver::SQLite {
                filename: <&str>::try_from(config.name).unwrap().to_owned(),
            },
            DBBackend::MySQL => DatabaseDriver::MySQL {
                name: <&str>::try_from(config.name).unwrap().to_owned(),
                host: <&str>::try_from(config.host).unwrap().to_owned(),
                port: config.port,
                user: <&str>::try_from(config.user).unwrap().to_owned(),
                password: <&str>::try_from(config.password).unwrap().to_owned(),
            },
            DBBackend::Postgres => DatabaseDriver::Postgres {
                name: <&str>::try_from(config.name).unwrap().to_owned(),
                host: <&str>::try_from(config.host).unwrap().to_owned(),
                port: config.port,
                user: <&str>::try_from(config.user).unwrap().to_owned(),
                password: <&str>::try_from(config.password).unwrap().to_owned(),
            },
        };

        #[cfg(feature = "logging")]
        return Ok(DatabaseConfiguration {
            driver: d,
            min_connections: config.min_connections,
            max_connections: config.max_connections,
            disable_logging: None,
            statement_log_level: None,
            slow_statement_log_level: None,
        });

        #[cfg(not(feature = "logging"))]
        Ok(DatabaseConfiguration {
            driver: d,
            min_connections: config.min_connections,
            max_connections: config.max_connections,
            disable_logging: Some(true),
            statement_log_level: None,
            slow_statement_log_level: None,
        })
    }
}

/**
Representation of a [NullType]
*/
#[repr(C)]
#[derive(Copy, Clone)]
pub enum FFINullType {
    /// String representation
    String,
    /// i64 representation
    I64,
    /// i32 representation
    I32,
    /// i16 representation
    I16,
    /// Bool representation
    Bool,
    /// f64 representation
    F64,
    /// f32 representation
    F32,
    /// binary representation
    Binary,
    /// Naive Time representation
    NaiveTime,
    /// Naive Date representation
    NaiveDate,
    /// Naive DateTime representation
    NaiveDateTime,
    /// NULL choice type representation
    Choice,
}

impl From<NullType> for FFINullType {
    fn from(value: NullType) -> Self {
        match value {
            NullType::String => Self::String,
            NullType::I64 => Self::I64,
            NullType::I32 => Self::I32,
            NullType::I16 => Self::I16,
            NullType::Bool => Self::Bool,
            NullType::F64 => Self::F64,
            NullType::F32 => Self::F32,
            NullType::Binary => Self::Binary,
            NullType::NaiveTime => Self::NaiveTime,
            NullType::NaiveDate => Self::NaiveDate,
            NullType::NaiveDateTime => Self::NaiveDateTime,
            NullType::Choice => Self::Choice,
        }
    }
}

impl From<FFINullType> for NullType {
    fn from(value: FFINullType) -> Self {
        match value {
            FFINullType::String => Self::String,
            FFINullType::I64 => Self::I64,
            FFINullType::I32 => Self::I32,
            FFINullType::I16 => Self::I16,
            FFINullType::Bool => Self::Bool,
            FFINullType::F64 => Self::F64,
            FFINullType::F32 => Self::F32,
            FFINullType::Binary => Self::Binary,
            FFINullType::NaiveTime => Self::NaiveTime,
            FFINullType::NaiveDate => Self::NaiveDate,
            FFINullType::NaiveDateTime => Self::NaiveDateTime,
            FFINullType::Choice => Self::Choice,
        }
    }
}

/**
This enum represents a value
 */
#[repr(C)]
#[derive(Copy, Clone)]
pub enum FFIValue<'a> {
    /// null representation
    Null(FFINullType),
    /// Representation of an identifier.
    /// This variant will not be escaped, so do not
    /// pass unchecked data to it.
    Ident(FFIString<'a>),
    /// Representation of a column.
    Column {
        /// Optional table name
        table_name: FFIOption<FFIString<'a>>,
        /// Name of the column
        column_name: FFIString<'a>,
    },
    /// String representation
    String(FFIString<'a>),
    /// i64 representation
    I64(i64),
    /// i32 representation
    I32(i32),
    /// i16 representation
    I16(i16),
    /// Bool representation
    Bool(bool),
    /// f64 representation
    F64(f64),
    /// f32 representation
    F32(f32),
    /// Binary representation
    Binary(FFISlice<'a, u8>),
    /// Representation of time without timezones
    NaiveTime(FFITime),
    /// Representation of dates without timezones
    NaiveDate(FFIDate),
    /// Representation of datetimes without timezones
    NaiveDateTime(FFIDateTime),
    /// Representation of enum
    Choice(FFIString<'a>),
}

impl<'a> TryFrom<&'a FFIValue<'a>> for rorm_db::sql::value::Value<'a> {
    type Error = Error<'a>;

    fn try_from(value: &'a FFIValue<'a>) -> Result<Self, Self::Error> {
        match value {
            FFIValue::Null(t) => Ok(rorm_db::sql::value::Value::Null((*t).into())),
            FFIValue::Ident(x) => Ok(rorm_db::sql::value::Value::Ident(
                x.try_into().map_err(|_| Error::InvalidStringError)?,
            )),
            FFIValue::Column {
                table_name,
                column_name,
            } => {
                let table_name = match table_name {
                    FFIOption::None => None,
                    FFIOption::Some(v) => {
                        Some(v.try_into().map_err(|_| Error::InvalidStringError)?)
                    }
                };
                Ok(rorm_db::sql::value::Value::Column {
                    table_name,
                    column_name: column_name
                        .try_into()
                        .map_err(|_| Error::InvalidStringError)?,
                })
            }
            FFIValue::String(x) => Ok(rorm_db::sql::value::Value::String(
                x.try_into().map_err(|_| Error::InvalidStringError)?,
            )),
            FFIValue::I64(x) => Ok(rorm_db::sql::value::Value::I64(*x)),
            FFIValue::I32(x) => Ok(rorm_db::sql::value::Value::I32(*x)),
            FFIValue::I16(x) => Ok(rorm_db::sql::value::Value::I16(*x)),
            FFIValue::Bool(x) => Ok(rorm_db::sql::value::Value::Bool(*x)),
            FFIValue::F64(x) => Ok(rorm_db::sql::value::Value::F64(*x)),
            FFIValue::F32(x) => Ok(rorm_db::sql::value::Value::F32(*x)),
            FFIValue::Binary(x) => Ok(rorm_db::sql::value::Value::Binary(x.into())),
            FFIValue::NaiveTime(x) => Ok(rorm_db::sql::value::Value::NaiveTime(x.try_into()?)),
            FFIValue::NaiveDate(x) => Ok(rorm_db::sql::value::Value::NaiveDate(x.try_into()?)),
            FFIValue::NaiveDateTime(x) => {
                Ok(rorm_db::sql::value::Value::NaiveDateTime(x.try_into()?))
            }
            FFIValue::Choice(x) => Ok(rorm_db::sql::value::Value::Choice(
                x.try_into().map_err(|_| Error::InvalidStringError)?,
            )),
        }
    }
}

/**
This enum represents all available ternary expression.
 */
#[repr(C)]
pub enum FFITernaryCondition<'a> {
    /// Between represents "{} BETWEEN {} AND {}" from SQL
    Between([&'a FFICondition<'a>; 3]),
    /// Between represents "{} NOT BETWEEN {} AND {}" from SQL
    NotBetween([&'a FFICondition<'a>; 3]),
}

impl<'a> TryFrom<&FFITernaryCondition<'a>> for rorm_db::sql::conditional::TernaryCondition<'a> {
    type Error = Error<'a>;

    fn try_from(value: &FFITernaryCondition<'a>) -> Result<Self, Self::Error> {
        match value {
            FFITernaryCondition::Between(x) => {
                let [a, b, c] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?, (*c).try_into()?];
                Ok(rorm_db::sql::conditional::TernaryCondition::Between(
                    Box::new(x_conv),
                ))
            }
            FFITernaryCondition::NotBetween(x) => {
                let [a, b, c] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?, (*c).try_into()?];
                Ok(rorm_db::sql::conditional::TernaryCondition::NotBetween(
                    Box::new(x_conv),
                ))
            }
        }
    }
}

/**
This enum represents a binary expression.
 */
#[repr(C)]
pub enum FFIBinaryCondition<'a> {
    /// Representation of "{} = {}" in SQL
    Equals([&'a FFICondition<'a>; 2]),
    /// Representation of "{} <> {}" in SQL
    NotEquals([&'a FFICondition<'a>; 2]),
    /// Representation of "{} > {}" in SQL
    Greater([&'a FFICondition<'a>; 2]),
    /// Representation of "{} >= {}" in SQL
    GreaterOrEquals([&'a FFICondition<'a>; 2]),
    /// Representation of "{} < {}" in SQL
    Less([&'a FFICondition<'a>; 2]),
    /// Representation of "{} <= {}" in SQL
    LessOrEquals([&'a FFICondition<'a>; 2]),
    /// Representation of "{} LIKE {}" in SQL
    Like([&'a FFICondition<'a>; 2]),
    /// Representation of "{} NOT LIKE {}" in SQL
    NotLike([&'a FFICondition<'a>; 2]),
    /// Representation of "{} REGEXP {}" in SQL
    Regexp([&'a FFICondition<'a>; 2]),
    /// Representation of "{} NOT REGEXP {}" in SQL
    NotRegexp([&'a FFICondition<'a>; 2]),
    /// Representation of "{} IN {}" in SQL
    In([&'a FFICondition<'a>; 2]),
    /// Representation of "{} NOT IN {}" in SQL
    NotIn([&'a FFICondition<'a>; 2]),
}

impl<'a> TryFrom<&FFIBinaryCondition<'a>> for rorm_db::sql::conditional::BinaryCondition<'a> {
    type Error = Error<'a>;

    fn try_from(value: &FFIBinaryCondition<'a>) -> Result<Self, Self::Error> {
        match value {
            FFIBinaryCondition::Equals(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::Equals(
                    Box::new(x_conv),
                ))
            }
            FFIBinaryCondition::NotEquals(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::NotEquals(
                    Box::new(x_conv),
                ))
            }
            FFIBinaryCondition::Greater(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::Greater(
                    Box::new(x_conv),
                ))
            }
            FFIBinaryCondition::GreaterOrEquals(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::GreaterOrEquals(
                    Box::new(x_conv),
                ))
            }
            FFIBinaryCondition::Less(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::Less(Box::new(
                    x_conv,
                )))
            }
            FFIBinaryCondition::LessOrEquals(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::LessOrEquals(
                    Box::new(x_conv),
                ))
            }
            FFIBinaryCondition::Like(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::Like(Box::new(
                    x_conv,
                )))
            }
            FFIBinaryCondition::NotLike(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::NotLike(
                    Box::new(x_conv),
                ))
            }
            FFIBinaryCondition::Regexp(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::Regexp(
                    Box::new(x_conv),
                ))
            }
            FFIBinaryCondition::NotRegexp(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::NotRegexp(
                    Box::new(x_conv),
                ))
            }
            FFIBinaryCondition::In(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::In(Box::new(
                    x_conv,
                )))
            }
            FFIBinaryCondition::NotIn(x) => {
                let [a, b] = x;
                let x_conv = [(*a).try_into()?, (*b).try_into()?];
                Ok(rorm_db::sql::conditional::BinaryCondition::NotIn(Box::new(
                    x_conv,
                )))
            }
        }
    }
}

/**
This enum represents all available unary conditions.
 */
#[repr(C)]
pub enum FFIUnaryCondition<'a> {
    /// Representation of SQL's "{} IS NULL"
    IsNull(&'a FFICondition<'a>),
    /// Representation of SQL's "{} IS NOT NULL"
    IsNotNull(&'a FFICondition<'a>),
    /// Representation of SQL's "EXISTS {}"
    Exists(&'a FFICondition<'a>),
    /// Representation of SQL's "NOT EXISTS {}"
    NotExists(&'a FFICondition<'a>),
    /// Representation of SQL's "NOT {}"
    Not(&'a FFICondition<'a>),
}

impl<'a> TryFrom<&FFIUnaryCondition<'a>> for rorm_db::sql::conditional::UnaryCondition<'a> {
    type Error = Error<'a>;

    fn try_from(value: &FFIUnaryCondition<'a>) -> Result<Self, Self::Error> {
        match value {
            FFIUnaryCondition::IsNull(x) => Ok(rorm_db::sql::conditional::UnaryCondition::IsNull(
                Box::new((*x).try_into()?),
            )),
            FFIUnaryCondition::IsNotNull(x) => Ok(
                rorm_db::sql::conditional::UnaryCondition::IsNotNull(Box::new((*x).try_into()?)),
            ),
            FFIUnaryCondition::Exists(x) => Ok(rorm_db::sql::conditional::UnaryCondition::Exists(
                Box::new((*x).try_into()?),
            )),
            FFIUnaryCondition::NotExists(x) => Ok(
                rorm_db::sql::conditional::UnaryCondition::NotExists(Box::new((*x).try_into()?)),
            ),
            FFIUnaryCondition::Not(x) => Ok(rorm_db::sql::conditional::UnaryCondition::Not(
                Box::new((*x).try_into()?),
            )),
        }
    }
}

/**
This enum represents a condition tree.
 */
#[repr(C)]
pub enum FFICondition<'a> {
    /// A list of [Condition]s, that get expanded to "{} AND {} ..."
    Conjunction(FFISlice<'a, FFICondition<'a>>),
    /// A list of [Condition]s, that get expanded to "{} OR {} ..."
    Disjunction(FFISlice<'a, FFICondition<'a>>),
    /// Representation of a unary condition.
    UnaryCondition(FFIUnaryCondition<'a>),
    /// Representation of a binary condition.
    BinaryCondition(FFIBinaryCondition<'a>),
    /// Representation of a ternary condition.
    TernaryCondition(FFITernaryCondition<'a>),
    /// Representation of a value.
    Value(FFIValue<'a>),
}

impl<'a> TryFrom<&'a FFICondition<'a>> for rorm_db::sql::conditional::Condition<'a> {
    type Error = Error<'a>;

    fn try_from(value: &'a FFICondition<'a>) -> Result<Self, Self::Error> {
        match value {
            FFICondition::Conjunction(x) => {
                let x_conv: &[FFICondition] = x.into();
                let mut x_vec = vec![];
                for cond in x_conv {
                    x_vec.push(cond.try_into()?);
                }
                Ok(rorm_db::sql::conditional::Condition::Conjunction(x_vec))
            }
            FFICondition::Disjunction(x) => {
                let x_conv: &[FFICondition] = x.into();
                let mut x_vec = vec![];
                for cond in x_conv {
                    x_vec.push(cond.try_into()?);
                }
                Ok(rorm_db::sql::conditional::Condition::Disjunction(x_vec))
            }
            FFICondition::UnaryCondition(x) => Ok(
                rorm_db::sql::conditional::Condition::UnaryCondition(x.try_into()?),
            ),
            FFICondition::BinaryCondition(x) => Ok(
                rorm_db::sql::conditional::Condition::BinaryCondition(x.try_into()?),
            ),
            FFICondition::TernaryCondition(x) => Ok(
                rorm_db::sql::conditional::Condition::TernaryCondition(x.try_into()?),
            ),
            FFICondition::Value(x) => {
                Ok(rorm_db::sql::conditional::Condition::Value(x.try_into()?))
            }
        }
    }
}

/**
Representation of an update.

Consists of a column and the value to set to this column.
*/
#[repr(C)]
pub struct FFIUpdate<'a> {
    pub(crate) column: FFIString<'a>,
    pub(crate) value: FFIValue<'a>,
}

/**
Representation of a join type.
*/
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub enum FFIJoinType {
    /// Normal join operation.
    ///
    /// Equivalent to INNER JOIN
    Join,
    /// Cartesian product of the tables
    CrossJoin,
    /// Given:
    /// T1 LEFT JOIN T2 ON ..
    ///
    /// First, an inner join is performed.
    /// Then, for each row in T1 that does not satisfy the join condition with any row in T2,
    /// a joined row is added with null values in columns of T2.
    LeftJoin,
    /// Given:
    /// T1 RIGHT JOIN T2 ON ..
    ///
    /// First, an inner join is performed.
    /// Then, for each row in T2 that does not satisfy the join condition with any row in T1,
    /// a joined row is added with null values in columns of T1.
    RightJoin,
    /// Given:
    /// T1 FULL JOIN T2 ON ..
    ///
    /// First, an inner join is performed.
    /// Then, for each row in T2 that does not satisfy the join condition with any row in T1,
    /// a joined row is added with null values in columns of T1.
    /// Also, for each row in T1 that does not satisfy the join condition with any row in T2,
    /// a joined row is added with null values in columns of T2.
    FullJoin,
}

impl From<FFIJoinType> for JoinType {
    fn from(v: FFIJoinType) -> Self {
        match v {
            FFIJoinType::Join => JoinType::Join,
            FFIJoinType::CrossJoin => JoinType::CrossJoin,
            FFIJoinType::LeftJoin => JoinType::LeftJoin,
            FFIJoinType::RightJoin => JoinType::RightJoin,
            FFIJoinType::FullJoin => JoinType::FullJoin,
        }
    }
}

/**
FFI representation of a Join expression.
*/
#[repr(C)]
pub struct FFIJoin<'a> {
    /// Type of the join operation
    pub(crate) join_type: FFIJoinType,
    /// Name of the join table
    pub(crate) table_name: FFIString<'a>,
    /// Alias for the join table
    pub(crate) join_alias: FFIString<'a>,
    /// Condition to apply the join on
    pub(crate) join_condition: &'a FFICondition<'a>,
}

/**
FFI representation of a Limit clause.
*/
#[repr(C)]
pub struct FFILimitClause {
    pub(crate) limit: u64,
    pub(crate) offset: FFIOption<u64>,
}

impl From<FFILimitClause> for LimitClause {
    fn from(v: FFILimitClause) -> Self {
        Self {
            limit: v.limit,
            offset: v.offset.into(),
        }
    }
}

/**
FFI representation of a [SelectColumnImpl]
*/
#[repr(C)]
pub struct FFIColumnSelector<'a> {
    pub(crate) table_name: FFIOption<FFIString<'a>>,
    pub(crate) column_name: FFIString<'a>,
    pub(crate) select_alias: FFIOption<FFIString<'a>>,
    pub(crate) aggregation: FFIOption<FFIAggregation>,
}

/**
Representation of the [Ordering]
*/
#[repr(C)]
#[derive(Copy, Clone)]
pub enum FFIOrdering {
    /// Ascending
    Asc,
    /// Descending
    Desc,
}

impl From<FFIOrdering> for Ordering {
    fn from(v: FFIOrdering) -> Self {
        match v {
            FFIOrdering::Asc => Self::Asc,
            FFIOrdering::Desc => Self::Desc,
        }
    }
}

/**
Representation of an aggregator function
*/
#[repr(C)]
#[derive(Copy, Clone)]
pub enum FFIAggregation {
    /// Returns the average value of all non-null values.
    /// The result of avg is a floating point value, except all input values are null, than the
    /// result will also be null.
    Avg,
    /// Returns the count of the number of times that the column is not null.
    Count,
    /// Returns the summary off all non-null values in the group.
    /// If there are only null values in the group, this function will return null.
    Sum,
    /// Returns the maximum value of all values in the group.
    /// If there are only null values in the group, this function will return null.
    Max,
    /// Returns the minimum value of all values in the group.
    /// If there are only null values in the group, this function will return null.
    Min,
}

impl From<FFIAggregation> for SelectAggregator {
    fn from(v: FFIAggregation) -> Self {
        match v {
            FFIAggregation::Avg => SelectAggregator::Avg,
            FFIAggregation::Count => SelectAggregator::Count,
            FFIAggregation::Sum => SelectAggregator::Sum,
            FFIAggregation::Max => SelectAggregator::Max,
            FFIAggregation::Min => SelectAggregator::Min,
        }
    }
}

/**
Representation of a [OrderByEntry]
*/
#[repr(C)]
#[derive(Copy, Clone)]
pub struct FFIOrderByEntry<'a> {
    pub(crate) ordering: FFIOrdering,
    pub(crate) table_name: FFIOption<FFIString<'a>>,
    pub(crate) column_name: FFIString<'a>,
}