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