pywatt_sdk 0.5.3

Standardized SDK for building PyWatt modules in 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
use crate::model_manager::{
    Error, Result,
    adapters::DatabaseAdapter,
    definitions::{
        ColumnDescriptor, Constraint, DataType, IndexDescriptor, IndexType, ModelDescriptor,
        ReferentialAction,
    },
    errors::{adapter_error, unsupported_feature_error},
};

/// SQLite database adapter for model management
#[derive(Debug, Default)]
pub struct SqliteAdapter;

impl SqliteAdapter {
    /// Create a new SQLite adapter
    pub fn new() -> Self {
        Self
    }

    /// Helper to format the schema-qualified table name
    fn format_table_name(&self, table_name: &str, schema_name: Option<&str>) -> String {
        // SQLite doesn't traditionally use schemas in the same way as PostgreSQL
        // If a schema is specified, we'll use it as a table prefix
        if let Some(schema) = schema_name {
            format!("{}_{}", schema, table_name)
        } else {
            table_name.to_string()
        }
    }

    /// Helper to handle referential actions
    fn get_referential_action_sql(&self, action: Option<&ReferentialAction>) -> &'static str {
        match action {
            Some(ReferentialAction::NoAction) => "NO ACTION",
            Some(ReferentialAction::Restrict) => "RESTRICT",
            Some(ReferentialAction::Cascade) => "CASCADE",
            Some(ReferentialAction::SetNull) => "SET NULL",
            Some(ReferentialAction::SetDefault) => "SET DEFAULT",
            None => "NO ACTION", // Default
        }
    }
}

impl DatabaseAdapter for SqliteAdapter {
    type Error = Error;

    fn get_db_type_name(&self) -> &'static str {
        "sqlite"
    }

    fn map_common_data_type(&self, common_type: &DataType) -> Result<String> {
        match common_type {
            // SQLite has a flexible type system with only a few storage classes
            DataType::Text(_) | DataType::Varchar(_) | DataType::Char(_) => Ok("TEXT".to_string()),
            DataType::Integer(_) | DataType::SmallInt | DataType::BigInt => {
                Ok("INTEGER".to_string())
            }
            DataType::Boolean => Ok("INTEGER".to_string()), // SQLite uses 0/1 for booleans
            DataType::Float | DataType::Double => Ok("REAL".to_string()),
            DataType::Decimal(_, _) => Ok("NUMERIC".to_string()),
            DataType::Date
            | DataType::Time
            | DataType::DateTime
            | DataType::Timestamp
            | DataType::TimestampTz => {
                // SQLite doesn't have dedicated date/time types
                // Options are TEXT (ISO8601 strings), REAL (Julian day numbers), or INTEGER (Unix timestamp)
                Ok("TEXT".to_string())
            }
            DataType::Blob => Ok("BLOB".to_string()),
            DataType::Json | DataType::JsonB => Ok("TEXT".to_string()), // Store JSON as TEXT
            DataType::Uuid => Ok("TEXT".to_string()),                   // Store UUID as TEXT
            DataType::Enum(_, _) => {
                // SQLite doesn't have a dedicated enum type - we'd use a CHECK constraint
                // but for type mapping only, we'll use TEXT
                Ok("TEXT".to_string())
            }
            DataType::Custom(custom_type) => Ok(custom_type.clone()), // Use as-is
        }
    }

    fn generate_column_definition_sql(&self, column: &ColumnDescriptor) -> Result<String> {
        let quoted_name = self.quote_identifier(&column.name);
        let data_type = self.map_common_data_type(&column.data_type)?;

        let mut parts = vec![quoted_name, data_type];

        // Handle primary key - use rowid alias form for auto-increment
        if column.is_primary_key {
            if column.auto_increment {
                // SQLite special case for auto-increment primary key
                if matches!(
                    column.data_type,
                    DataType::Integer(_) | DataType::SmallInt | DataType::BigInt
                ) {
                    parts.push("PRIMARY KEY AUTOINCREMENT".to_string());
                } else {
                    return Err(adapter_error(
                        "SQLite AUTOINCREMENT can only be used with INTEGER PRIMARY KEY",
                    ));
                }
            } else {
                parts.push("PRIMARY KEY".to_string());
            }
        }

        // NOT NULL constraint
        if !column.is_nullable {
            parts.push("NOT NULL".to_string());
        }

        // Unique constraint (for the column only)
        if column.is_unique {
            parts.push("UNIQUE".to_string());
        }

        // Default value
        if let Some(default_value) = &column.default_value {
            parts.push(format!("DEFAULT {}", default_value));
        }

        // SQLite supports inline CHECK constraints
        for constraint in &column.constraints {
            if let Constraint::Check { expression, .. } = constraint {
                parts.push(format!("CHECK ({})", expression));
            }
        }

        Ok(parts.join(" "))
    }

    fn generate_constraint_sql(
        &self,
        constraint: &Constraint,
        table_name: &str,
    ) -> Result<Option<String>> {
        match constraint {
            Constraint::PrimaryKey { name, columns } => {
                let constraint_name = name.as_deref().unwrap_or("pk");
                let sql =
                    self.generate_primary_key_sql(columns, table_name, Some(constraint_name))?;
                Ok(Some(sql))
            }
            Constraint::Unique { name, columns } => {
                let constraint_name = name.as_deref().unwrap_or("unique");
                let quoted_name =
                    self.quote_identifier(&format!("{}_{}", table_name, constraint_name));
                let quoted_columns: Vec<String> = columns
                    .iter()
                    .map(|col| self.quote_identifier(col))
                    .collect();

                Ok(Some(format!(
                    "CONSTRAINT {} UNIQUE ({})",
                    quoted_name,
                    quoted_columns.join(", ")
                )))
            }
            Constraint::ForeignKey {
                name,
                columns,
                references_table,
                references_columns,
                on_delete,
                on_update,
            } => {
                let constraint_name = name.as_deref().unwrap_or("fk");
                let quoted_name =
                    self.quote_identifier(&format!("{}_{}", table_name, constraint_name));
                let quoted_columns: Vec<String> = columns
                    .iter()
                    .map(|col| self.quote_identifier(col))
                    .collect();
                let quoted_ref_table = self.quote_identifier(references_table);
                let quoted_ref_columns: Vec<String> = references_columns
                    .iter()
                    .map(|col| self.quote_identifier(col))
                    .collect();

                let on_delete_sql = self.get_referential_action_sql(on_delete.as_ref());
                let on_update_sql = self.get_referential_action_sql(on_update.as_ref());

                Ok(Some(format!(
                    "CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {} ({}) ON DELETE {} ON UPDATE {}",
                    quoted_name,
                    quoted_columns.join(", "),
                    quoted_ref_table,
                    quoted_ref_columns.join(", "),
                    on_delete_sql,
                    on_update_sql
                )))
            }
            Constraint::Check { name, expression } => {
                let constraint_name = name.as_deref().unwrap_or("check");
                let quoted_name =
                    self.quote_identifier(&format!("{}_{}", table_name, constraint_name));

                Ok(Some(format!(
                    "CONSTRAINT {} CHECK ({})",
                    quoted_name, expression
                )))
            }
            // These are typically handled inline at the column level
            Constraint::NotNull | Constraint::DefaultValue(_) | Constraint::AutoIncrement => {
                Ok(None)
            }
        }
    }

    fn generate_primary_key_sql(
        &self,
        pk_columns: &[String],
        table_name: &str,
        constraint_name: Option<&str>,
    ) -> Result<String> {
        let quoted_columns: Vec<String> = pk_columns
            .iter()
            .map(|col| self.quote_identifier(col))
            .collect();

        let name_part = constraint_name
            .map(|name| {
                format!(
                    "CONSTRAINT {} ",
                    self.quote_identifier(&format!("{}_{}", table_name, name))
                )
            })
            .unwrap_or_default();

        Ok(format!(
            "{}PRIMARY KEY ({})",
            name_part,
            quoted_columns.join(", ")
        ))
    }

    fn generate_foreign_key_sql(&self, fk: &Constraint, table_name: &str) -> Result<String> {
        match fk {
            Constraint::ForeignKey {
                name,
                columns,
                references_table,
                references_columns,
                on_delete,
                on_update,
            } => {
                let constraint_name = name.as_deref().unwrap_or("fk");
                let quoted_name =
                    self.quote_identifier(&format!("{}_{}", table_name, constraint_name));

                let quoted_columns: Vec<String> = columns
                    .iter()
                    .map(|col| self.quote_identifier(col))
                    .collect();

                let quoted_ref_table = self.quote_identifier(references_table);
                let quoted_ref_columns: Vec<String> = references_columns
                    .iter()
                    .map(|col| self.quote_identifier(col))
                    .collect();

                let on_delete_sql = self.get_referential_action_sql(on_delete.as_ref());
                let on_update_sql = self.get_referential_action_sql(on_update.as_ref());

                // SQLite doesn't support ALTER TABLE ADD CONSTRAINT FOREIGN KEY
                // We'll define this as the SQL to be used at table creation time
                Ok(format!(
                    "CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {} ({}) ON DELETE {} ON UPDATE {}",
                    quoted_name,
                    quoted_columns.join(", "),
                    quoted_ref_table,
                    quoted_ref_columns.join(", "),
                    on_delete_sql,
                    on_update_sql
                ))
            }
            _ => Err(adapter_error("Not a foreign key constraint")),
        }
    }

    fn generate_index_sql(&self, index: &IndexDescriptor, table_name: &str) -> Result<String> {
        let index_name = match &index.name {
            Some(name) => name.clone(),
            None => format!("{}_{}_idx", table_name, index.columns.join("_")),
        };

        let quoted_name = self.quote_identifier(&index_name);
        let quoted_table = self.quote_identifier(table_name);

        let quoted_columns: Vec<String> = index
            .columns
            .iter()
            .map(|col| self.quote_identifier(col))
            .collect();

        let unique = if index.is_unique { "UNIQUE " } else { "" };

        // SQLite doesn't support most index types - it only has the default btree index
        if let Some(idx_type) = &index.index_type {
            if !matches!(idx_type, IndexType::BTree) {
                return Err(unsupported_feature_error(format!(
                    "SQLite only supports BTree indexes, not {:?}",
                    idx_type
                )));
            }
        }

        let where_clause = index
            .condition
            .as_ref()
            .map(|cond| format!(" WHERE {}", cond))
            .unwrap_or_default();

        Ok(format!(
            "CREATE {}INDEX {} ON {} ({}){}",
            unique,
            quoted_name,
            quoted_table,
            quoted_columns.join(", "),
            where_clause
        ))
    }

    fn generate_create_table_sql(&self, model: &ModelDescriptor) -> Result<String> {
        let table_name = self.format_table_name(&model.name, model.schema.as_deref());
        let quoted_table = self.quote_identifier(&table_name);

        // Generate column definitions
        let mut column_defs = Vec::new();
        for column in &model.columns {
            let column_sql = self.generate_column_definition_sql(column)?;
            column_defs.push(column_sql);
        }

        // Add table-level constraints
        let mut table_constraints = Vec::new();

        // Add primary key if specified at table level
        if let Some(pk_columns) = &model.primary_key {
            let pk_sql = self.generate_primary_key_sql(pk_columns, &table_name, None)?;
            table_constraints.push(pk_sql);
        }

        // Add other table constraints
        for constraint in &model.constraints {
            if let Some(constraint_sql) = self.generate_constraint_sql(constraint, &table_name)? {
                table_constraints.push(constraint_sql);
            }
        }

        // Combine column defs and table constraints
        let mut all_parts = column_defs;
        all_parts.extend(table_constraints);

        // Generate the full CREATE TABLE statement
        let create_table_sql = format!(
            "CREATE TABLE {} (\n  {}\n)",
            quoted_table,
            all_parts.join(",\n  ")
        );

        Ok(create_table_sql)
    }

    fn generate_drop_table_sql(
        &self,
        table_name: &str,
        schema_name: Option<&str>,
    ) -> Result<String> {
        let name = self.format_table_name(table_name, schema_name);
        let quoted_table = self.quote_identifier(&name);

        Ok(format!("DROP TABLE IF EXISTS {}", quoted_table))
    }

    fn generate_add_column_sql(
        &self,
        table_name: &str,
        column: &ColumnDescriptor,
        schema_name: Option<&str>,
    ) -> Result<String> {
        let name = self.format_table_name(table_name, schema_name);
        let quoted_table = self.quote_identifier(&name);
        let column_sql = self.generate_column_definition_sql(column)?;

        // SQLite has limited ALTER TABLE support
        // It can add a column, but with restrictions:
        // - Cannot have PRIMARY KEY or UNIQUE constraints
        // - Cannot have foreign keys
        // - Can have NOT NULL only with a DEFAULT value

        if column.is_primary_key {
            return Err(unsupported_feature_error(
                "SQLite cannot add a PRIMARY KEY column to an existing table",
            ));
        }

        if column.is_unique {
            return Err(unsupported_feature_error(
                "SQLite cannot add a UNIQUE column to an existing table",
            ));
        }

        if !column.is_nullable && column.default_value.is_none() {
            return Err(unsupported_feature_error(
                "SQLite cannot add a NOT NULL column without a DEFAULT value to an existing table",
            ));
        }

        // Check for foreign key constraints
        for constraint in &column.constraints {
            if matches!(constraint, Constraint::ForeignKey { .. }) {
                return Err(unsupported_feature_error(
                    "SQLite cannot add a FOREIGN KEY column to an existing table",
                ));
            }
        }

        Ok(format!(
            "ALTER TABLE {} ADD COLUMN {}",
            quoted_table, column_sql
        ))
    }

    fn generate_drop_column_sql(
        &self,
        _table_name: &str,
        _column_name: &str,
        _schema_name: Option<&str>,
    ) -> Result<String> {
        Err(unsupported_feature_error(
            "SQLite doesn't support DROP COLUMN in versions before 3.35.0. \
            For older versions, you must recreate the table without the column.",
        ))
    }

    fn generate_rename_table_sql(
        &self,
        old_table_name: &str,
        new_table_name: &str,
        schema_name: Option<&str>,
    ) -> Result<String> {
        let old_name = self.format_table_name(old_table_name, schema_name);
        let new_name = self.format_table_name(new_table_name, schema_name);

        let quoted_old_table = self.quote_identifier(&old_name);
        let quoted_new_table = self.quote_identifier(&new_name);

        Ok(format!(
            "ALTER TABLE {} RENAME TO {}",
            quoted_old_table, quoted_new_table
        ))
    }

    fn identifier_quote_char_start(&self) -> char {
        '"'
    }

    fn identifier_quote_char_end(&self) -> char {
        '"'
    }

    fn escape_string_literal(&self, value: &str) -> String {
        // For SQLite, escape ' as ''
        value.replace('\'', "''")
    }

    /// Generate SQL to drop a constraint from a table
    fn generate_drop_constraint_sql(
        &self,
        _table_name: &str,
        _constraint_name: &str,
        _schema_name: Option<&str>,
    ) -> Result<String> {
        // SQLite does not support ALTER TABLE DROP CONSTRAINT.
        // Constraints must be dropped by recreating the table without the constraint.
        Err(unsupported_feature_error(
            "SQLite does not support DROP CONSTRAINT. Table must be recreated.",
        ))
    }

    /// Generate SQL to drop an index
    fn generate_drop_index_sql(
        &self,
        _table_name: &str,
        index_name: &str,
        _schema_name: Option<&str>,
    ) -> Result<String> {
        let quoted_index = self.quote_identifier(index_name);
        Ok(format!("DROP INDEX {}", quoted_index))
    }
}

/// Test module for SQLite adapter
#[cfg(test)]
mod tests {
    use super::*;
    use crate::model_manager::definitions::{IntegerSize, ModelDescriptor};

    #[test]
    fn test_map_data_types() {
        let adapter = SqliteAdapter::new();
        assert_eq!(
            adapter.map_common_data_type(&DataType::Text(None)).unwrap(),
            "TEXT"
        );
        assert_eq!(
            adapter
                .map_common_data_type(&DataType::Varchar(255))
                .unwrap(),
            "TEXT"
        );
        assert_eq!(
            adapter
                .map_common_data_type(&DataType::Integer(IntegerSize::I32))
                .unwrap(),
            "INTEGER"
        );
        assert_eq!(
            adapter.map_common_data_type(&DataType::Boolean).unwrap(),
            "INTEGER"
        );
        assert_eq!(
            adapter.map_common_data_type(&DataType::Float).unwrap(),
            "REAL"
        );
        assert_eq!(
            adapter
                .map_common_data_type(&DataType::Decimal(10, 2))
                .unwrap(),
            "NUMERIC"
        );
        assert_eq!(
            adapter.map_common_data_type(&DataType::Blob).unwrap(),
            "BLOB"
        );
        assert_eq!(
            adapter.map_common_data_type(&DataType::Json).unwrap(),
            "TEXT"
        );
        assert_eq!(
            adapter.map_common_data_type(&DataType::Uuid).unwrap(),
            "TEXT"
        );
    }

    #[test]
    fn test_generate_column_definition() {
        let adapter = SqliteAdapter::new();
        let basic_column = ColumnDescriptor {
            name: "username".to_string(),
            data_type: DataType::Varchar(100),
            is_nullable: false,
            is_primary_key: false,
            is_unique: false,
            default_value: None,
            auto_increment: false,
            comment: None,
            constraints: vec![],
        };
        assert_eq!(
            adapter
                .generate_column_definition_sql(&basic_column)
                .unwrap(),
            "\"username\" TEXT NOT NULL"
        );
        let pk_column = ColumnDescriptor {
            name: "id".to_string(),
            data_type: DataType::Integer(IntegerSize::I64),
            is_nullable: false,
            is_primary_key: true,
            is_unique: false,
            default_value: None,
            auto_increment: true,
            comment: None,
            constraints: vec![],
        };
        assert_eq!(
            adapter.generate_column_definition_sql(&pk_column).unwrap(),
            "\"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL"
        );
    }

    #[test]
    fn test_generate_create_table() {
        let adapter = SqliteAdapter::new();
        let user_model = ModelDescriptor {
            name: "users".to_string(),
            schema: None,
            columns: vec![
                ColumnDescriptor {
                    name: "id".to_string(),
                    data_type: DataType::Integer(IntegerSize::I64),
                    is_nullable: false,
                    is_primary_key: true,
                    is_unique: false,
                    default_value: None,
                    auto_increment: true,
                    comment: None,
                    constraints: vec![],
                },
                ColumnDescriptor {
                    name: "username".to_string(),
                    data_type: DataType::Varchar(100),
                    is_nullable: false,
                    is_primary_key: false,
                    is_unique: true,
                    default_value: None,
                    auto_increment: false,
                    comment: None,
                    constraints: vec![],
                },
                ColumnDescriptor {
                    name: "email".to_string(),
                    data_type: DataType::Varchar(255),
                    is_nullable: false,
                    is_primary_key: false,
                    is_unique: true,
                    default_value: None,
                    auto_increment: false,
                    comment: None,
                    constraints: vec![],
                },
            ],
            primary_key: None,
            indexes: vec![],
            constraints: vec![],
            comment: None,
            engine: None,
            charset: None,
            collation: None,
            options: Default::default(),
        };
        let create_table_sql = adapter.generate_create_table_sql(&user_model).unwrap();
        assert!(create_table_sql.contains("CREATE TABLE \"users\""));
        assert!(create_table_sql.contains("\"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL"));
        assert!(create_table_sql.contains("\"username\" TEXT NOT NULL UNIQUE"));
        assert!(create_table_sql.contains("\"email\" TEXT NOT NULL UNIQUE"));
    }
}