Skip to main content

rullst_orm/
schema.rs

1use crate::Error;
2
3/// Allowlist of SQL comparison/join operators accepted in raw clause builders.
4const ALLOWED_OPERATORS: &[&str] = &["=", "!=", "<>", "<", ">", "<=", ">="];
5
6/// Validates a SQL identifier (column or table name) to prevent SQL injection.
7/// Allows alphanumeric characters, underscores, hyphens and a single dot
8/// for qualified names like `table.column`.
9pub fn validate_identifier(name: &str) -> Result<(), Error> {
10    if name.is_empty() {
11        return Err(Error::Internal(
12            "SQL identifier cannot be empty".to_string(),
13        ));
14    }
15    // At most one dot is allowed (for `table.column` notation),
16    // and it must not be the first or last character.
17    let dot_count = name.chars().filter(|&c| c == '.').count();
18    if dot_count > 1 {
19        return Err(Error::Internal(format!(
20            "Invalid SQL identifier '{}': at most one dot is allowed",
21            name
22        )));
23    }
24    if name.starts_with('.') || name.ends_with('.') {
25        return Err(Error::Internal(format!(
26            "Invalid SQL identifier '{}': must not start or end with a dot",
27            name
28        )));
29    }
30    if !name
31        .chars()
32        .all(|c| c.is_alphanumeric() || c == '_' || c == '-' || c == '.')
33    {
34        return Err(Error::Internal(format!(
35            "Invalid SQL identifier '{}': only alphanumeric characters, underscores, hyphens and dots are allowed",
36            name
37        )));
38    }
39    Ok(())
40}
41
42/// Validates a table name to prevent SQL injection.
43/// Wraps `validate_identifier` but disallows dots (table names have no qualifier).
44fn validate_table_name(table_name: &str) -> Result<(), Error> {
45    if table_name.contains('.') {
46        return Err(Error::Internal(format!(
47            "Invalid table name '{}': dots are not allowed in table names",
48            table_name
49        )));
50    }
51    validate_identifier(table_name)
52}
53
54/// Safe values allowed for a column DEFAULT clause.
55///
56/// Accepting a raw `&str` would allow DDL injection through the DEFAULT
57/// position. This enum restricts callers to known-safe literals.
58#[derive(Debug, Clone, PartialEq)]
59pub enum ColumnDefault {
60    /// `CURRENT_TIMESTAMP` — standard SQL timestamp literal.
61    CurrentTimestamp,
62    /// `NULL` — explicit SQL null default.
63    Null,
64    /// A non-negative integer literal (e.g. `0`, `1`).
65    Integer(i64),
66    /// A non-negative real literal (e.g. `0.0`).
67    Float(f64),
68    /// A string literal that will be single-quoted and escaped.
69    /// Only printable ASCII excluding `'` and `\` is accepted.
70    Text(String),
71}
72
73impl ColumnDefault {
74    /// Renders the default value as a safe SQL fragment.
75    pub fn to_sql(&self) -> String {
76        match self {
77            ColumnDefault::CurrentTimestamp => "CURRENT_TIMESTAMP".to_string(),
78            ColumnDefault::Null => "NULL".to_string(),
79            ColumnDefault::Integer(n) => n.to_string(),
80            ColumnDefault::Float(f) => format!("{f}"),
81            // Single-quote the string and escape any embedded single-quotes
82            // via SQL standard doubling (''), which is safe on every driver.
83            ColumnDefault::Text(s) => format!("'{}'", s.replace('\'', "''")),
84        }
85    }
86}
87
88pub struct Column {
89    pub name: String,
90    pub col_type: String,
91    pub is_nullable: bool,
92    pub is_primary_key: bool,
93    pub is_auto_increment: bool,
94    pub default_value: Option<ColumnDefault>,
95}
96
97impl Column {
98    /// Creates a new column, validating `name` against SQL identifier rules.
99    ///
100    /// # Panics
101    /// Panics if `name` fails identifier validation. Column names are always
102    /// developer-supplied compile-time literals — an invalid name is a bug,
103    /// not a runtime condition.
104    pub fn new(name: &str, col_type: &str) -> Self {
105        validate_identifier(name)
106            .unwrap_or_else(|e| panic!("Invalid column name {:?}: {}", name, e));
107        Self {
108            name: name.to_string(),
109            col_type: col_type.to_string(),
110            is_nullable: true,
111            is_primary_key: false,
112            is_auto_increment: false,
113            default_value: None,
114        }
115    }
116
117    pub fn not_null(&mut self) -> &mut Self {
118        self.is_nullable = false;
119        self
120    }
121
122    pub fn nullable(&mut self) -> &mut Self {
123        self.is_nullable = true;
124        self
125    }
126
127    /// Sets a safe DEFAULT value using the [`ColumnDefault`] enum.
128    ///
129    /// The old `&str` overload has been removed to prevent DDL injection
130    /// through unescaped DEFAULT clauses.
131    pub fn default(&mut self, val: ColumnDefault) -> &mut Self {
132        self.default_value = Some(val);
133        self
134    }
135
136    pub fn primary(&mut self) -> &mut Self {
137        self.is_primary_key = true;
138        self
139    }
140}
141
142pub struct Blueprint {
143    pub columns: Vec<Column>,
144}
145
146impl Default for Blueprint {
147    fn default() -> Self {
148        Self::new()
149    }
150}
151
152impl Blueprint {
153    pub fn new() -> Self {
154        Self { columns: vec![] }
155    }
156
157    pub fn id(&mut self) -> &mut Column {
158        self.columns.push(Column {
159            name: "id".to_string(),
160            col_type: "INTEGER".to_string(),
161            is_nullable: false,
162            is_primary_key: true,
163            is_auto_increment: true,
164            default_value: None,
165        });
166        self.columns
167            .last_mut()
168            .expect("BUG: columns is empty after push")
169    }
170
171    fn add_column(&mut self, name: &str, col_type: &str) -> &mut Column {
172        let col = Column::new(name, col_type);
173        self.columns.push(col);
174        self.columns
175            .last_mut()
176            .expect("BUG: columns is empty after push")
177    }
178
179    pub fn string(&mut self, name: &str) -> &mut Column {
180        self.add_column(name, "TEXT")
181    }
182
183    pub fn integer(&mut self, name: &str) -> &mut Column {
184        self.add_column(name, "INTEGER")
185    }
186
187    pub fn float(&mut self, name: &str) -> &mut Column {
188        self.add_column(name, "REAL")
189    }
190
191    pub fn boolean(&mut self, name: &str) -> &mut Column {
192        self.add_column(name, "INTEGER")
193    }
194
195    pub fn timestamps(&mut self) {
196        let mut created = Column::new("created_at", "TEXT");
197        created.default(ColumnDefault::CurrentTimestamp);
198        self.columns.push(created);
199
200        let mut updated = Column::new("updated_at", "TEXT");
201        updated.default(ColumnDefault::CurrentTimestamp);
202        self.columns.push(updated);
203    }
204
205    pub fn soft_deletes(&mut self) {
206        let col = Column::new("deleted_at", "TEXT");
207        self.columns.push(col);
208        self.columns
209            .last_mut()
210            .expect("BUG: columns is empty after push")
211            .nullable();
212    }
213
214    pub fn build(&self) -> Result<String, Error> {
215        let mut defs = vec![];
216        for col in &self.columns {
217            // Defensive re-validation: column names must always be safe
218            // identifiers regardless of how the Column was constructed.
219            validate_identifier(&col.name)?;
220            let mut def = format!("{} {}", col.name, col.col_type);
221            if col.is_primary_key {
222                def.push_str(" PRIMARY KEY");
223            }
224            if col.is_auto_increment {
225                def.push_str(" AUTOINCREMENT");
226            }
227            if !col.is_nullable && !col.is_primary_key {
228                def.push_str(" NOT NULL");
229            }
230            if let Some(default) = &col.default_value {
231                def.push_str(&format!(" DEFAULT {}", default.to_sql()));
232            }
233            defs.push(def);
234        }
235        Ok(defs.join(",\n    "))
236    }
237}
238
239pub struct Schema;
240
241impl Schema {
242    pub async fn create<F>(table_name: &str, callback: F) -> Result<(), Error>
243    where
244        F: FnOnce(&mut Blueprint),
245    {
246        validate_table_name(table_name)?;
247
248        let mut blueprint = Blueprint::new();
249        callback(&mut blueprint);
250
251        // build() now returns Result so any column-name or default issues
252        // surface as errors rather than producing malformed SQL.
253        let columns_sql = blueprint.build()?;
254        let sql = format!(
255            "CREATE TABLE IF NOT EXISTS {} (\n    {}\n);",
256            table_name, columns_sql
257        );
258
259        let pool = crate::Orm::pool();
260        let mut query_builder = sqlx::query_builder::QueryBuilder::new("");
261        query_builder.push(&sql);
262        query_builder.build().execute(pool).await?;
263
264        Ok(())
265    }
266
267    pub async fn drop_if_exists(table_name: &str) -> Result<(), Error> {
268        validate_table_name(table_name)?;
269
270        let sql = format!("DROP TABLE IF EXISTS {};", table_name);
271        let pool = crate::Orm::pool();
272        let mut query_builder = sqlx::query_builder::QueryBuilder::new("");
273        query_builder.push(&sql);
274        query_builder.build().execute(pool).await?;
275        Ok(())
276    }
277}
278
279#[async_trait::async_trait]
280pub trait Migration: Send + Sync {
281    fn name(&self) -> &'static str;
282    async fn up(&self) -> Result<(), Error>;
283    async fn down(&self) -> Result<(), Error>;
284}
285
286pub async fn run_artisan_with_args(
287    args: &[String],
288    migrations: Vec<Box<dyn Migration>>,
289    seeders: Vec<Box<dyn crate::Seeder>>,
290) -> Result<(), Error> {
291    if args.len() < 2 {
292        println!("Rullst ORM Artisan CLI");
293        println!("Usage:");
294        println!("  make:migration <name>   Generate a new migration");
295        println!("  migrate                  Run all pending migrations");
296        println!("  migrate:rollback         Rollback the last batch of migrations");
297        println!("  status                   Show migrations status");
298        println!("  db:seed                  Populate the database with seeders");
299        return Ok(());
300    }
301
302    let command = &args[1];
303    match command.as_str() {
304        "make:migration" => {
305            if args.len() < 3 {
306                println!("Error: migration name is required.");
307                return Ok(());
308            }
309            let name = &args[2];
310            create_migration_files(name)?;
311        }
312        "migrate" | "db:migrate" => {
313            run_migrations(migrations).await?;
314        }
315        "migrate:rollback" | "db:rollback" => {
316            rollback_migrations(migrations).await?;
317        }
318        "status" | "db:status" => {
319            status_migrations(migrations).await?;
320        }
321        "db:seed" => {
322            println!("Seeding database...");
323            crate::Orm::seed(seeders).await?;
324            println!("Database seeded successfully!");
325        }
326        _ => {
327            println!("Unknown command: {}", command);
328        }
329    }
330    Ok(())
331}
332
333pub async fn run_artisan(
334    migrations: Vec<Box<dyn Migration>>,
335    seeders: Vec<Box<dyn crate::Seeder>>,
336) -> Result<(), Error> {
337    let args: Vec<String> = std::env::args().collect();
338    run_artisan_with_args(&args, migrations, seeders).await
339}
340
341async fn status_migrations(migrations: Vec<Box<dyn Migration>>) -> Result<(), Error> {
342    let pool = crate::Orm::pool();
343    let driver = crate::Orm::driver();
344
345    let table_exists = match driver {
346        "postgres" | "mysql" => {
347            let query_str =
348                "SELECT COUNT(*) FROM information_schema.tables WHERE table_name = 'migrations'";
349            let row: (i64,) = sqlx::query_as(query_str).fetch_one(pool).await?;
350            row.0 > 0
351        }
352        _ => {
353            let query_str =
354                "SELECT COUNT(*) FROM sqlite_schema WHERE type='table' AND name='migrations'";
355            let row: (i64,) = sqlx::query_as(query_str).fetch_one(pool).await?;
356            row.0 > 0
357        }
358    };
359
360    let executed_set = if table_exists {
361        let executed: Vec<(String,)> = sqlx::query_as("SELECT migration FROM migrations")
362            .fetch_all(pool)
363            .await?;
364        executed
365            .into_iter()
366            .map(|(m,)| m)
367            .collect::<std::collections::HashSet<String>>()
368    } else {
369        std::collections::HashSet::new()
370    };
371
372    let name_header = "Migration Name";
373    let status_header = "Status";
374    println!("{name_header:<40} | {status_header}");
375    println!("{}", "-".repeat(55));
376    for m in migrations {
377        let name = m.name();
378        let status = if executed_set.contains(name) {
379            "Applied"
380        } else {
381            "Pending"
382        };
383        println!("{:<40} | {}", name, status);
384    }
385
386    Ok(())
387}
388
389fn create_migration_files(name: &str) -> Result<(), Error> {
390    validate_table_name(name)?;
391    use std::fs;
392
393    let now = std::time::SystemTime::now()
394        .duration_since(std::time::UNIX_EPOCH)
395        .expect("System time went backwards")
396        .as_secs()
397        .to_string();
398    let snake_name = name.to_lowercase().replace("-", "_");
399    let file_name = format!("m{}_{}", now, snake_name);
400
401    fs::create_dir_all("src/migrations")
402        .map_err(|e| Error::Internal(format!("Failed to create migrations directory: {}", e)))?;
403
404    let new_file_path = format!("src/migrations/{}.rs", file_name);
405    let migration_code = format!(
406        r#"use rullst_orm::schema::{{Schema, Blueprint, Migration}};
407use rullst_orm::async_trait;
408
409pub struct MigrationImpl;
410
411#[async_trait]
412impl Migration for MigrationImpl {{
413    fn name(&self) -> &'static str {{
414        "m{timestamp}_{name}"
415    }}
416
417    async fn up(&self) -> Result<(), crate::Error> {{
418        Schema::create("{name}", |table| {{
419            table.id();
420            table.timestamps();
421        }}).await
422    }}
423
424    async fn down(&self) -> Result<(), crate::Error> {{
425        Schema::drop_if_exists("{name}").await
426    }}
427}}
428"#,
429        timestamp = now,
430        name = snake_name
431    );
432
433    fs::write(&new_file_path, migration_code)
434        .map_err(|e| Error::Internal(format!("Failed to write migration file: {}", e)))?;
435    println!("Created migration file: {}", new_file_path);
436
437    regenerate_migrations_mod()?;
438
439    Ok(())
440}
441
442fn regenerate_migrations_mod() -> Result<(), Error> {
443    use std::fs;
444    let paths = fs::read_dir("src/migrations")
445        .map_err(|e| Error::Internal(format!("Failed to read migrations dir: {}", e)))?;
446
447    let mut modules = vec![];
448    for path in paths {
449        let path = path.map_err(|e| Error::Internal(e.to_string()))?.path();
450        if let Some(ext) = path.extension()
451            && ext == "rs"
452            && let Some(stem) = path.file_stem()
453        {
454            let stem_str = stem.to_string_lossy().to_string();
455            if stem_str != "mod" && stem_str.starts_with('m') {
456                modules.push(stem_str);
457            }
458        }
459    }
460    modules.sort();
461
462    let mut mod_content = String::new();
463    mod_content.push_str("// Generated by Rullst ORM Artisan. Do not edit manually.\n\n");
464    for m in &modules {
465        mod_content.push_str(&format!("pub mod {};\n", m));
466    }
467    mod_content
468        .push_str("\npub fn get_migrations() -> Vec<Box<dyn rullst_orm::schema::Migration>> {\n");
469    mod_content.push_str("    vec![\n");
470    for m in &modules {
471        mod_content.push_str(&format!("        Box::new({}::MigrationImpl),\n", m));
472    }
473    mod_content.push_str("    ]\n");
474    mod_content.push_str("}\n");
475
476    fs::write("src/migrations/mod.rs", mod_content)
477        .map_err(|e| Error::Internal(format!("Failed to write mod.rs: {}", e)))?;
478    println!("Regenerated src/migrations/mod.rs");
479
480    Ok(())
481}
482
483async fn run_migrations(migrations: Vec<Box<dyn Migration>>) -> Result<(), Error> {
484    let pool = crate::Orm::pool();
485    let driver = crate::Orm::driver();
486
487    let query_str = match driver {
488        "postgres" => {
489            "CREATE TABLE IF NOT EXISTS migrations (
490                id SERIAL PRIMARY KEY,
491                migration VARCHAR(255) NOT NULL,
492                batch INTEGER NOT NULL
493            )"
494        }
495        "mysql" => {
496            "CREATE TABLE IF NOT EXISTS migrations (
497                id INT AUTO_INCREMENT PRIMARY KEY,
498                migration VARCHAR(255) NOT NULL,
499                batch INT NOT NULL
500            )"
501        }
502        _ => {
503            "CREATE TABLE IF NOT EXISTS migrations (
504                id INTEGER PRIMARY KEY AUTOINCREMENT,
505                migration TEXT NOT NULL,
506                batch INTEGER NOT NULL
507            )"
508        }
509    };
510
511    sqlx::query(query_str).execute(pool).await?;
512
513    let executed: Vec<(String,)> = sqlx::query_as("SELECT migration FROM migrations")
514        .fetch_all(pool)
515        .await?;
516    let executed_set: std::collections::HashSet<String> =
517        executed.into_iter().map(|(m,)| m).collect();
518
519    let batch_row: (Option<i32>,) = sqlx::query_as("SELECT MAX(batch) FROM migrations")
520        .fetch_one(pool)
521        .await?;
522    let next_batch = batch_row.0.unwrap_or(0) + 1;
523
524    let mut count = 0;
525    let mut successful_migrations = vec![];
526    for m in migrations {
527        let name = m.name();
528        if !executed_set.contains(name) {
529            println!("Migrating: {}", name);
530            m.up().await?;
531            successful_migrations.push(name);
532            println!("Migrated:  {}", name);
533            count += 1;
534        }
535    }
536
537    if count > 0 {
538        let mut query_builder =
539            sqlx::query_builder::QueryBuilder::new("INSERT INTO migrations (migration, batch) ");
540        query_builder.push_values(successful_migrations, |mut b, name| {
541            b.push_bind(name).push_bind(next_batch);
542        });
543        query_builder.build().execute(pool).await?;
544    } else {
545        println!("Nothing to migrate.");
546    }
547
548    Ok(())
549}
550
551async fn rollback_migrations(migrations: Vec<Box<dyn Migration>>) -> Result<(), Error> {
552    let pool = crate::Orm::pool();
553    let driver = crate::Orm::driver();
554
555    let table_exists = match driver {
556        "postgres" | "mysql" => {
557            let query_str =
558                "SELECT COUNT(*) FROM information_schema.tables WHERE table_name = 'migrations'";
559            let row: (i64,) = sqlx::query_as(query_str).fetch_one(pool).await?;
560            row.0 > 0
561        }
562        _ => {
563            let query_str =
564                "SELECT COUNT(*) FROM sqlite_schema WHERE type='table' AND name='migrations'";
565            let row: (i64,) = sqlx::query_as(query_str).fetch_one(pool).await?;
566            row.0 > 0
567        }
568    };
569
570    if !table_exists {
571        println!("Nothing to rollback.");
572        return Ok(());
573    }
574
575    let batch_row: (Option<i32>,) = sqlx::query_as("SELECT MAX(batch) FROM migrations")
576        .fetch_one(pool)
577        .await?;
578
579    let last_batch = match batch_row.0 {
580        Some(b) if b > 0 => b,
581        _ => {
582            println!("Nothing to rollback.");
583            return Ok(());
584        }
585    };
586
587    let to_rollback: Vec<(String,)> =
588        sqlx::query_as("SELECT migration FROM migrations WHERE batch = ? ORDER BY id DESC")
589            .bind(last_batch)
590            .fetch_all(pool)
591            .await?;
592
593    let mut rollback_map = std::collections::HashMap::new();
594    for m in migrations {
595        rollback_map.insert(m.name().to_string(), m);
596    }
597
598    for (name,) in to_rollback {
599        if let Some(m) = rollback_map.get(&name) {
600            println!("Rolling back: {}", name);
601            m.down().await?;
602            sqlx::query("DELETE FROM migrations WHERE migration = ?")
603                .bind(&name)
604                .execute(pool)
605                .await?;
606            println!("Rolled back:  {}", name);
607        } else {
608            println!(
609                "Warning: migration {} found in database but not in compiled binary.",
610                name
611            );
612        }
613    }
614
615    Ok(())
616}
617
618pub struct JoinClause {
619    pub table: String,
620    pub conditions: Vec<String>,
621    pub bindings: Vec<crate::RullstValue>,
622    pub errors: Vec<crate::Error>,
623}
624
625impl JoinClause {
626    pub fn new(table: &str) -> Self {
627        Self {
628            table: table.to_string(),
629            conditions: vec![],
630            bindings: vec![],
631            errors: vec![],
632        }
633    }
634
635    /// Adds a column-to-column JOIN condition.
636    ///
637    /// This prevents SQL injection — column names should always be hardcoded, never
638    /// derived from user input. Returns errors internally rather than panicking.
639    pub fn on(&mut self, first: &str, operator: &str, second: &str) -> &mut Self {
640        if let Err(e) = validate_identifier(first) {
641            self.errors.push(crate::Error::Validation(format!(
642                "JoinClause::on — invalid identifier for `first`: {:?}",
643                e
644            )));
645        }
646        if let Err(e) = validate_identifier(second) {
647            self.errors.push(crate::Error::Validation(format!(
648                "JoinClause::on — invalid identifier for `second`: {:?}",
649                e
650            )));
651        }
652        if !ALLOWED_OPERATORS.contains(&operator) {
653            self.errors.push(crate::Error::Validation(format!(
654                "JoinClause::on — invalid operator '{}'. Allowed: {:?}",
655                operator, ALLOWED_OPERATORS
656            )));
657        }
658        self.conditions
659            .push(format!("{} {} {}", first, operator, second));
660        self
661    }
662
663    pub fn on_eq<T: Into<crate::RullstValue>>(&mut self, column: &str, value: T) -> &mut Self {
664        if let Err(e) = validate_identifier(column) {
665            self.errors.push(crate::Error::Validation(format!(
666                "JoinClause::on_eq — invalid identifier for `column`: {:?}",
667                e
668            )));
669        }
670        self.conditions.push(format!("{} = ?", column));
671        self.bindings.push(value.into());
672        self
673    }
674
675    pub fn to_sql(&self) -> String {
676        self.conditions.join(" AND ")
677    }
678}
679
680pub trait SubqueryBuilder {
681    fn to_sql(&self) -> String;
682    fn bindings(&self) -> &Vec<crate::RullstValue>;
683}
684
685pub static QUERY_LOGGING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
686
687pub fn enable_query_log() {
688    QUERY_LOGGING.store(true, std::sync::atomic::Ordering::SeqCst);
689}
690
691pub fn disable_query_log() {
692    QUERY_LOGGING.store(false, std::sync::atomic::Ordering::SeqCst);
693}
694
695pub fn is_query_log_enabled() -> bool {
696    QUERY_LOGGING.load(std::sync::atomic::Ordering::SeqCst)
697}
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702
703    #[test]
704    fn test_enable_disable_query_log() {
705        disable_query_log();
706        assert!(!is_query_log_enabled());
707        enable_query_log();
708        assert!(is_query_log_enabled());
709        disable_query_log();
710        assert!(!is_query_log_enabled());
711    }
712
713    #[test]
714    fn test_join_clause() {
715        let mut jc = JoinClause::new("users");
716        jc.on("users.id", "=", "posts.user_id");
717        assert_eq!(jc.to_sql(), "users.id = posts.user_id");
718    }
719
720    #[test]
721    fn test_validate_table_name() {
722        assert!(validate_table_name("users").is_ok());
723        assert!(validate_table_name("user_posts").is_ok());
724        assert!(validate_table_name("DROP TABLE users").is_err());
725        assert!(validate_table_name("../../../etc/shadow").is_err());
726        // dots not allowed in table names
727        assert!(validate_table_name("users.id").is_err());
728    }
729
730    #[test]
731    fn test_validate_identifier() {
732        assert!(validate_identifier("users").is_ok());
733        assert!(validate_identifier("users.id").is_ok());
734        assert!(validate_identifier("user_posts").is_ok());
735        assert!(validate_identifier("").is_err());
736        assert!(validate_identifier("users.posts.id").is_err()); // two dots
737        assert!(validate_identifier("DROP TABLE users").is_err());
738        assert!(validate_identifier("id; DROP TABLE users--").is_err());
739        // Leading/trailing dot edge cases — all now rejected
740        assert!(validate_identifier(".").is_err()); // bare dot: starts AND ends with dot
741        assert!(validate_identifier(".users").is_err()); // leading dot
742        assert!(validate_identifier("users.").is_err()); // trailing dot
743        assert!(validate_identifier("user name").is_err()); // Spaces not allowed
744        assert!(validate_identifier("admin'--").is_err()); // Quotes not allowed
745        assert!(validate_identifier("users()").is_err()); // Parentheses not allowed
746        assert!(validate_identifier("a*b").is_err()); // Asterisk not allowed
747    }
748
749    #[test]
750    fn test_join_clause_on_invalid_operator() {
751        let mut jc = JoinClause::new("posts");
752        jc.on("posts.user_id", "OR 1=1 --", "users.id");
753        assert!(!jc.errors.is_empty());
754        assert!(jc.errors[0].to_string().contains("invalid operator"));
755    }
756
757    #[test]
758    fn test_join_clause_on_invalid_column() {
759        let mut jc = JoinClause::new("posts");
760        jc.on("users.id; DROP TABLE users--", "=", "posts.user_id");
761        assert!(!jc.errors.is_empty());
762        assert!(jc.errors[0].to_string().contains("invalid identifier"));
763    }
764
765    #[test]
766    fn test_timestamps_adds_columns() {
767        let mut bp = Blueprint::new();
768        bp.timestamps();
769        assert_eq!(bp.columns.len(), 2);
770        assert_eq!(bp.columns[0].name, "created_at");
771        assert_eq!(bp.columns[1].name, "updated_at");
772        assert_eq!(
773            bp.columns[0].default_value,
774            Some(ColumnDefault::CurrentTimestamp)
775        );
776        assert_eq!(
777            bp.columns[1].default_value,
778            Some(ColumnDefault::CurrentTimestamp)
779        );
780    }
781
782    #[test]
783    fn test_soft_deletes_adds_nullable_column() {
784        let mut bp = Blueprint::new();
785        bp.soft_deletes();
786        assert_eq!(bp.columns.len(), 1);
787        assert_eq!(bp.columns[0].name, "deleted_at");
788        assert!(bp.columns[0].is_nullable);
789    }
790
791    #[test]
792    fn test_blueprint_build_produces_valid_sql() {
793        let mut bp = Blueprint::new();
794        bp.id();
795        bp.string("name").not_null();
796        bp.integer("age");
797        let sql = bp.build().expect("build should succeed for valid columns");
798        assert!(sql.contains("id INTEGER PRIMARY KEY"));
799        assert!(sql.contains("name TEXT NOT NULL"));
800        assert!(sql.contains("age INTEGER"));
801    }
802
803    #[test]
804    fn test_column_default_to_sql_escaping() {
805        let default_text = ColumnDefault::Text("O'Reilly".to_string());
806        assert_eq!(default_text.to_sql(), "'O''Reilly'");
807    }
808
809    #[test]
810    fn test_validate_identifier_multiple_dots() {
811        assert!(validate_identifier("table.column").is_ok()); // one dot
812        assert!(validate_identifier("schema.table.column").is_err()); // multiple dots
813    }
814
815    #[test]
816    fn test_column_default_sql_rendering() {
817        assert_eq!(
818            ColumnDefault::CurrentTimestamp.to_sql(),
819            "CURRENT_TIMESTAMP"
820        );
821        assert_eq!(ColumnDefault::Null.to_sql(), "NULL");
822        assert_eq!(ColumnDefault::Integer(42).to_sql(), "42");
823        assert_eq!(ColumnDefault::Float(1.23).to_sql(), "1.23");
824        assert_eq!(ColumnDefault::Text("hello".to_string()).to_sql(), "'hello'");
825        // SQL injection via embedded quote must be escaped
826        assert_eq!(ColumnDefault::Text("it's".to_string()).to_sql(), "'it''s'");
827    }
828
829    #[test]
830    fn test_join_clause_on_eq_binds_value() {
831        let mut jc = JoinClause::new("orders");
832        jc.on_eq("orders.user_id", 42i32);
833        assert_eq!(jc.to_sql(), "orders.user_id = ?");
834        assert_eq!(jc.bindings.len(), 1);
835    }
836
837    #[test]
838    fn test_join_clause_multiple_conditions() {
839        let mut jc = JoinClause::new("posts");
840        jc.on("posts.user_id", "=", "users.id");
841        jc.on("posts.status", ">", "users.min_status");
842        assert_eq!(
843            jc.to_sql(),
844            "posts.user_id = users.id AND posts.status > users.min_status"
845        );
846    }
847
848    #[test]
849    fn test_column_builder_methods() {
850        let mut col = Column::new("age", "INTEGER");
851        assert_eq!(col.name, "age");
852        assert_eq!(col.col_type, "INTEGER");
853        assert!(col.is_nullable); // default is true
854        assert!(!col.is_primary_key);
855        assert!(!col.is_auto_increment);
856        assert_eq!(col.default_value, None);
857
858        col.not_null();
859        assert!(!col.is_nullable);
860
861        col.nullable();
862        assert!(col.is_nullable);
863
864        col.primary();
865        assert!(col.is_primary_key);
866
867        col.default(ColumnDefault::Integer(18));
868        assert_eq!(col.default_value, Some(ColumnDefault::Integer(18)));
869    }
870
871    #[tokio::test]
872    async fn test_db_migration_error_state_invalid_blueprint() {
873        let result = Schema::create("invalid; DROP TABLE users", |bp| {
874            bp.id();
875        })
876        .await;
877
878        assert!(result.is_err());
879    }
880
881    #[tokio::test]
882    async fn test_drop_if_exists_invalid_table() {
883        let result = Schema::drop_if_exists("invalid; name").await;
884        assert!(result.is_err());
885        assert!(matches!(result, Err(crate::Error::Internal(_))));
886    }
887}