akita_core 0.7.0

Akita - Mini orm for rust.
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
/*
 *
 *  *
 *  *      Copyright (c) 2018-2025, SnackCloud All rights reserved.
 *  *
 *  *   Redistribution and use in source and binary forms, with or without
 *  *   modification, are permitted provided that the following conditions are met:
 *  *
 *  *   Redistributions of source code must retain the above copyright notice,
 *  *   this list of conditions and the following disclaimer.
 *  *   Redistributions in binary form must reproduce the above copyright
 *  *   notice, this list of conditions and the following disclaimer in the
 *  *   documentation and/or other materials provided with the distribution.
 *  *   Neither the name of the www.snackcloud.cn developer nor the names of its
 *  *   contributors may be used to endorse or promote products derived from
 *  *   this software without specific prior written permission.
 *  *   Author: SnackCloud
 *  *
 *
 */
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use uuid::Uuid;

use crate::{types::SqlType, AkitaValue};

/// Table

pub trait GetTableName {
    /// extract the table name from a struct
    fn table_name() -> TableName;
}

pub trait GetFields {
    /// extract the columns from struct
    fn fields() -> Vec<FieldName>;
}

pub trait Table {
    /// extract the table name from a struct
    fn table_name() -> TableName;

    /// extract the columns from struct
    fn fields() -> Vec<FieldName>;
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TableName {
    /// table name
    pub name: String,
    /// table of schema
    pub schema: Option<String>,
    /// table alias
    pub alias: Option<String>,
    pub ignore_interceptors: HashSet<String>,
}

impl Default for TableName {
    fn default() -> Self {
        Self {
            name: "".to_string(),
            schema: None,
            alias: None,
            ignore_interceptors: Default::default(),
        }
    }
}

impl Hash for TableName {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.schema.hash(state);
        self.name.hash(state);
    }
}

impl TableName {
    /// create table with name
    pub fn from(name: &str) -> Self {
        let name = name.trim();

        // Separate aliases (if any)
        let (table_part, alias) = Self::split_table_and_alias(name);

        // Separate schema and table names
        let (schema, name) = Self::split_schema_and_table(&table_part);

        TableName {
            name,
            schema,
            alias,
            ignore_interceptors: HashSet::new(),
        }
    }

    pub fn parse_table_name(sql: &str) -> TableName {
        let tables = TableName::parse_from_sql(sql);
        // Store the first table
        if let Some(first_table) = tables.first() {
            first_table.clone()
        } else {
            TableName::default()
        }
    }

    pub fn name(&self) -> String {
        self.name.to_string()
    }

    pub fn parse_from_sql(sql: &str) -> Vec<TableName> {
        let normalized_sql = Self::normalize_sql(sql);

        // Try parsing different types of SQL statements
        if let Some(tables) = Self::parse_insert_update_delete(&normalized_sql) {
            return tables;
        }

        if let Some(tables) = Self::parse_select(&normalized_sql) {
            return tables;
        }

        if let Some(tables) = Self::parse_ddl(&normalized_sql) {
            return tables;
        }

        vec![]
    }

    /// return the long name of the table using schema.table_name
    pub fn complete_name(&self) -> String {
        match self.schema {
            Some(ref schema) => format!("{}.{}", schema, self.name),
            None => self.name.to_owned(),
        }
    }

    pub fn sql_reference(&self) -> String {
        let full_name = self.complete_name();

        if let Some(alias) = &self.alias {
            format!("{} AS {}", full_name, alias)
        } else {
            full_name
        }
    }

    pub fn equals_ignore_alias(&self, other: &TableName) -> bool {
        self.name == other.name && self.schema == other.schema
    }

    fn normalize_sql(sql: &str) -> String {
        let sql = sql.trim();

        // Remove a one-line comment
        let re_comment = Regex::new(r"--.*$|/\*.*?\*/").unwrap();
        let sql = re_comment.replace_all(sql, "");

        // Replace multiple whitespace characters with a single space
        let re_whitespace = Regex::new(r"\s+").unwrap();
        re_whitespace.replace_all(&sql, " ").to_string()
    }

    fn parse_insert_update_delete(sql: &str) -> Option<Vec<TableName>> {
        let patterns = [
            // INSERT INTO/INSERT
            (r"(?i)^\s*INSERT\s+(?:INTO\s+)?(\S+)", "INSERT"),
            // UPDATE
            (r"(?i)^\s*UPDATE\s+(\S+)", "UPDATE"),
            // DELETE FROM/DELETE
            (r"(?i)^\s*DELETE\s+(?:FROM\s+)?(\S+)", "DELETE"),
        ];

        for (pattern, _) in patterns {
            if let Some(caps) = Regex::new(pattern).unwrap().captures(sql) {
                let table_expr = &caps[1];
                // Remove possible semicolons
                let table_expr = table_expr.split(';').next().unwrap_or(table_expr);
                return Some(vec![TableName::from(table_expr)]);
            }
        }

        None
    }

    fn parse_select(sql: &str) -> Option<Vec<TableName>> {
        let re_from = Regex::new(
            r"(?i)FROM\s+([^;]+?)(?:\s+(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET))?(?:;|$)",
        )
        .unwrap();

        if let Some(caps) = re_from.captures(sql) {
            let from_clause = &caps[1];

            let tables = Self::split_table_list(from_clause);

            if !tables.is_empty() {
                return Some(
                    tables
                        .into_iter()
                        .map(|v| TableName::from(v.as_str()))
                        .collect(),
                );
            }
        }

        None
    }

    /// Parse DDL statements(CREATE/DROP/ALTER TABLE)
    fn parse_ddl(sql: &str) -> Option<Vec<TableName>> {
        let pattern = r"(?i)^\s*(?:CREATE|DROP|ALTER|TRUNCATE|RENAME)\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(\S+)";

        if let Some(caps) = Regex::new(pattern).unwrap().captures(sql) {
            let table_expr = &caps[1];
            let table_expr = table_expr.split(';').next().unwrap_or(table_expr);
            return Some(vec![TableName::from(table_expr)]);
        }

        None
    }

    /// Split table list (handles commas and joins)
    fn split_table_list(from_clause: &str) -> Vec<String> {
        let mut tables = Vec::new();
        let mut current = String::new();
        let mut paren_depth = 0;

        for ch in from_clause.chars() {
            match ch {
                '(' => paren_depth += 1,
                ')' => paren_depth -= 1,
                ',' if paren_depth == 0 => {
                    if !current.trim().is_empty() {
                        tables.push(current.trim().to_string());
                    }
                    current.clear();
                    continue;
                }
                _ => {}
            }
            current.push(ch);
        }

        if !current.trim().is_empty() {
            tables.push(current.trim().to_string());
        }

        tables
    }

    /// Separation table and aliases
    fn split_table_and_alias(s: &str) -> (String, Option<String>) {
        let parts: Vec<&str> = s.split_whitespace().collect();

        if parts.len() >= 3 && parts[1].to_uppercase() == "AS" {
            // Format: table AS alias
            (parts[0].to_string(), Some(parts[2].to_string()))
        } else if parts.len() >= 2 {
            // Format: table alias(Implicit aliases)
            (parts[0].to_string(), Some(parts[1].to_string()))
        } else {
            // There are no aliases
            (s.to_string(), None)
        }
    }

    /// Separate schema and table names
    fn split_schema_and_table(s: &str) -> (Option<String>, String) {
        let parts: Vec<&str> = s.split('.').collect();

        match parts.len() {
            1 => (None, parts[0].to_string()),                       // table
            2 => (Some(parts[0].to_string()), parts[1].to_string()), // schema.table
            _ => {
                // For situations like db.schema.table, take the last two parts
                let len = parts.len();
                (Some(parts[len - 2].to_string()), parts[len - 1].to_string())
            }
        }
    }
}

/// Field

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct FieldName {
    pub name: String,
    pub table: Option<String>,
    pub alias: Option<String>,
    /// exist in actual table
    pub exist: bool,
    pub select: bool,
    pub fill: Option<Fill>,
    pub field_type: FieldType,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Fill {
    pub mode: String,
    pub value: Option<AkitaValue>,
    pub strategy: FillStrategy,
}

/// Fill strategy for automatic field population.
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum FillStrategy {
    /// Fixed value - use the value in `Fill.value`
    Fixed,
    /// Current timestamp (UTC)
    Timestamp,
    /// UUID v4
    Uuid,
    /// Snowflake ID
    Snowflake,
    /// Custom function name (resolved at runtime)
    Custom(String),
}

impl Default for FillStrategy {
    fn default() -> Self {
        FillStrategy::Fixed
    }
}

impl FillStrategy {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "timestamp" | "now" | "current_time" => FillStrategy::Timestamp,
            "uuid" | "uuid_v4" => FillStrategy::Uuid,
            "snowflake" | "snowflake_id" => FillStrategy::Snowflake,
            "fixed" | "default" => FillStrategy::Fixed,
            custom => FillStrategy::Custom(custom.to_string()),
        }
    }
}

impl Fill {
    /// Create a new Fill with fixed value
    pub fn fixed(mode: &str, value: AkitaValue) -> Self {
        Self {
            mode: mode.to_string(),
            value: Some(value),
            strategy: FillStrategy::Fixed,
        }
    }

    /// Create a new Fill with timestamp strategy
    pub fn timestamp(mode: &str) -> Self {
        Self {
            mode: mode.to_string(),
            value: None,
            strategy: FillStrategy::Timestamp,
        }
    }

    /// Create a new Fill with UUID strategy
    pub fn uuid(mode: &str) -> Self {
        Self {
            mode: mode.to_string(),
            value: None,
            strategy: FillStrategy::Uuid,
        }
    }

    /// Create a new Fill with snowflake strategy
    pub fn snowflake(mode: &str) -> Self {
        Self {
            mode: mode.to_string(),
            value: None,
            strategy: FillStrategy::Snowflake,
        }
    }

    /// Check if this fill should be applied for the given operation
    pub fn should_apply(&self, operation: &str) -> bool {
        match self.mode.as_str() {
            "default" => true,
            "insert" => operation == "insert",
            "update" => operation == "update",
            "insert_update" => operation == "insert" || operation == "update",
            _ => false,
        }
    }

    /// Get the fill value, resolving strategy if needed
    pub fn resolve_value(&self) -> Option<AkitaValue> {
        match &self.strategy {
            FillStrategy::Fixed => self.value.clone(),
            FillStrategy::Timestamp => Some(AkitaValue::Timestamp(chrono::Utc::now())),
            FillStrategy::Uuid => Some(AkitaValue::Text(uuid::Uuid::new_v4().to_string())),
            FillStrategy::Snowflake => {
                // Snowflake ID generation - use a simple timestamp-based ID
                // In production, this should use a proper snowflake generator
                let now = chrono::Utc::now().timestamp_millis();
                Some(AkitaValue::Bigint(now))
            }
            FillStrategy::Custom(_name) => {
                // Custom functions are resolved at runtime via interceptor
                self.value.clone()
            }
        }
    }
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum IdentifierType {
    Auto,
    Input,
    AssignId,
    AssignUuid,
}

impl IdentifierType {
    pub fn from_str(ident: &str) -> Self {
        let ident = ident.to_lowercase();
        match ident.as_str() {
            "auto" => Self::Auto,
            "input" => Self::Input,
            "assign_id" => Self::AssignId,
            "assign_uuid" => Self::AssignUuid,
            _ => Self::Auto,
        }
    }
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum FieldType {
    TableId(IdentifierType),
    TableField,
}

impl FieldName {
    /// create table with name
    pub fn from(arg: &str) -> Self {
        if arg.contains('.') {
            let splinters = arg.split('.').collect::<Vec<&str>>();
            assert!(
                splinters.len() == 2,
                "There should only be 2 parts, trying to split `.` {}",
                arg
            );
            let table = splinters[0].to_owned();
            let name = splinters[1].to_owned();
            FieldName {
                name,
                table: Some(table),
                alias: None,
                exist: true,
                select: true,
                fill: None,
                field_type: FieldType::TableField,
            }
        } else {
            FieldName {
                name: arg.to_owned(),
                table: None,
                alias: None,
                exist: true,
                select: true,
                fill: None,
                field_type: FieldType::TableField,
            }
        }
    }

    /// return the long name of the table using schema.table_name
    pub fn complete_name(&self) -> String {
        match self.table {
            Some(ref table) => format!("{}.{}", table, self.name),
            None => self.name.to_owned(),
        }
    }

    pub fn name(&self) -> String {
        self.name.to_owned()
    }

    /// 判断是否主键
    pub fn is_table_id(&self) -> bool {
        match self.field_type {
            FieldType::TableId(_) => true,
            FieldType::TableField => false,
        }
    }

    pub fn is_auto_increment(&self) -> bool {
        match &self.field_type {
            FieldType::TableId(id_type) => match id_type {
                IdentifierType::Auto => true,
                _ => false,
            },
            FieldType::TableField => false,
        }
    }

    /// 获取主键类型
    pub fn get_table_id_type(&self) -> Option<&IdentifierType> {
        match &self.field_type {
            FieldType::TableId(id_type) => Some(id_type),
            FieldType::TableField => None,
        }
    }
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct TableInfo {
    pub name: TableName,

    /// comment of this table
    pub comment: Option<String>,

    /// columns of this table
    pub columns: Vec<ColumnInfo>,

    /// views can also be generated
    pub is_view: bool,

    pub table_key: Vec<TableKey>,
}

impl TableInfo {
    pub fn name(&self) -> String {
        self.name.name()
    }
    pub fn comment(&self) -> Option<String> {
        self.comment.to_owned()
    }
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct ColumnInfo {
    pub table: TableName,
    pub name: FieldName,
    pub comment: Option<String>,
    pub specification: ColumnSpecification,
    pub stat: Option<ColumnStat>,
}

impl ColumnInfo {
    pub fn name(&self) -> String {
        self.name.name()
    }
    pub fn comment(&self) -> Option<String> {
        self.comment.to_owned()
    }
    pub fn data_type(&self) -> String {
        self.specification.sql_type.as_string()
    }
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct ColumnSpecification {
    pub sql_type: SqlType,
    pub capacity: Option<Capacity>,
    pub constraints: Vec<ColumnConstraint>,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum Capacity {
    Limit(i32),
    Range(i32, i32),
}

impl Capacity {
    fn get_limit(&self) -> Option<i32> {
        match *self {
            Capacity::Limit(limit) => Some(limit),
            Capacity::Range(_whole, _decimal) => None,
        }
    }

    pub fn sql_format(&self) -> String {
        match *self {
            Capacity::Limit(limit) => format!("({})", limit),
            Capacity::Range(_whole, _decimal) => format!("({}, {})", _whole, _decimal),
        }
    }
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum ColumnConstraint {
    NotNull,
    DefaultValue(Literal),
    /// the string contains the sequence name of this serial column
    AutoIncrement(Option<String>),
}

impl ColumnConstraint {
    pub fn sql_format(&self) -> String {
        match self {
            ColumnConstraint::NotNull => "not null".into(),
            ColumnConstraint::DefaultValue(v) => v.sql_format(),
            ColumnConstraint::AutoIncrement(_) => "auto_increment".into(),
        }
    }
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum Literal {
    Bool(bool),
    Null,
    Integer(i64),
    Double(f64),
    UuidGenerateV4, // pg: uuid_generate_v4();
    Uuid(Uuid),
    String(String),
    Blob(Vec<u8>),
    CurrentTime,      // pg: now()
    CurrentDate,      //pg: today()
    CurrentTimestamp, // pg: now()
    ArrayInt(Vec<i64>),
    ArrayFloat(Vec<f64>),
    ArrayString(Vec<String>),
}

impl Literal {
    pub fn sql_format(&self) -> String {
        match self {
            Literal::Bool(v) => v.to_string(),
            Literal::Integer(v) => v.to_string(),
            Literal::Double(v) => v.to_string(),
            Literal::Uuid(v) => v.to_string(),
            Literal::String(v) => v.to_owned(),
            Literal::Blob(v) => String::from_utf8(v.to_owned()).unwrap_or_default(),
            Literal::CurrentTime => "now()".to_string(),
            Literal::CurrentDate => "now()".to_string(),
            _ => String::default(),
        }
    }
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct ColumnStat {
    pub avg_width: i32, /* average width of the column, (the number of characters) */
    //most_common_AkitaValues: AkitaValue,//top 5 most common AkitaValues
    pub n_distinct: f32, // the number of distinct AkitaValues of these column
}

impl From<i64> for Literal {
    fn from(i: i64) -> Self {
        Literal::Integer(i)
    }
}

impl From<String> for Literal {
    fn from(s: String) -> Self {
        Literal::String(s)
    }
}

impl<'a> From<&'a str> for Literal {
    fn from(s: &'a str) -> Self {
        Literal::String(String::from(s))
    }
}

impl ColumnSpecification {
    pub fn get_limit(&self) -> Option<i32> {
        match self.capacity {
            Some(ref capacity) => capacity.get_limit(),
            None => None,
        }
    }
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Key {
    pub name: Option<String>,
    pub columns: Vec<FieldName>,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct ForeignKey {
    pub name: Option<String>,
    // the local columns of this table local column = foreign_column
    pub columns: Vec<FieldName>,
    // referred foreign table
    pub foreign_table: TableName,
    // referred column of the foreign table
    // this is most likely the primary key of the table in context
    pub referred_columns: Vec<FieldName>,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum TableKey {
    PrimaryKey(Key),
    UniqueKey(Key),
    Key(Key),
    ForeignKey(ForeignKey),
}

impl TableKey {
    pub fn is_pri(&self) -> bool {
        match self {
            TableKey::PrimaryKey(_) => true,
            _ => false,
        }
    }
}

#[derive(Debug)]
pub struct SchemaContent {
    pub schema: String,
    pub tablenames: Vec<TableName>,
    pub views: Vec<TableName>,
}

#[allow(unused)]
pub struct DatabaseName {
    pub name: String,
    pub description: Option<String>,
}