reinhardt-db 0.1.0

Django-style database layer for Reinhardt framework
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
/// Database schema editor module
///
/// This module provides the foundation for DDL (Data Definition Language) operations
/// across different database backends, inspired by Django's schema editor architecture.
///
/// # Example
///
/// ```rust
/// # use reinhardt_db::backends::schema::DDLStatement;
/// let create_table = DDLStatement::CreateTable {
///     table: "users".to_string(),
///     columns: vec![
///         ("id".to_string(), "INTEGER PRIMARY KEY".to_string()),
///         ("name".to_string(), "VARCHAR(100)".to_string()),
///     ],
/// };
/// assert_eq!(create_table.table_name(), "users");
/// ```
use std::fmt;

use reinhardt_query::prelude::{
	Alias, AlterTableStatement, ColumnDef, CreateIndexStatement, CreateTableStatement,
	DropIndexStatement, DropTableStatement, MySqlQueryBuilder, PostgresQueryBuilder, Query,
	QueryBuilder, SqliteQueryBuilder,
};

/// DDL reference objects for schema operations
pub mod ddl_references;

/// Schema editor factory for creating database-specific editors
pub mod factory;

/// Represents a DDL statement type
#[derive(Debug, Clone, PartialEq)]
pub enum DDLStatement {
	/// CREATE TABLE statement
	CreateTable {
		/// The table name.
		table: String,
		/// Column definitions as (name, type) pairs.
		columns: Vec<(String, String)>,
	},
	/// ALTER TABLE statement
	AlterTable {
		/// The table name.
		table: String,
		/// The list of changes to apply.
		changes: Vec<AlterTableChange>,
	},
	/// DROP TABLE statement
	DropTable {
		/// The table name.
		table: String,
		/// Whether to cascade the drop.
		cascade: bool,
	},
	/// CREATE INDEX statement
	CreateIndex {
		/// The index name.
		name: String,
		/// The table name.
		table: String,
		/// The columns to index.
		columns: Vec<String>,
		/// Whether the index is unique.
		unique: bool,
		/// Optional WHERE condition for partial indexes.
		condition: Option<String>,
	},
	/// DROP INDEX statement
	DropIndex {
		/// The index name.
		name: String,
	},
	/// CREATE SCHEMA statement
	CreateSchema {
		/// The schema name.
		name: String,
		/// Whether to use IF NOT EXISTS.
		if_not_exists: bool,
	},
	/// DROP SCHEMA statement
	DropSchema {
		/// The schema name.
		name: String,
		/// Whether to cascade the drop.
		cascade: bool,
		/// Whether to use IF EXISTS.
		if_exists: bool,
	},
	/// Raw SQL statement
	RawSQL(String),
}

impl DDLStatement {
	/// Get the table name associated with this DDL statement
	///
	/// # Example
	///
	/// ```rust
	/// # use reinhardt_db::backends::schema::DDLStatement;
	/// let stmt = DDLStatement::CreateTable {
	///     table: "users".to_string(),
	///     columns: vec![],
	/// };
	/// assert_eq!(stmt.table_name(), "users");
	/// ```
	pub fn table_name(&self) -> &str {
		match self {
			DDLStatement::CreateTable { table, .. } => table,
			DDLStatement::AlterTable { table, .. } => table,
			DDLStatement::DropTable { table, .. } => table,
			DDLStatement::CreateIndex { table, .. } => table,
			DDLStatement::DropIndex { .. } => "",
			DDLStatement::CreateSchema { .. } => "",
			DDLStatement::DropSchema { .. } => "",
			DDLStatement::RawSQL(_) => "",
		}
	}
}

/// ALTER TABLE change operations
#[derive(Debug, Clone, PartialEq)]
pub enum AlterTableChange {
	/// Add a column
	AddColumn {
		/// The column name.
		name: String,
		/// The column definition SQL.
		definition: String,
	},
	/// Drop a column
	DropColumn {
		/// The column name.
		name: String,
	},
	/// Rename a column
	RenameColumn {
		/// The old column name.
		old_name: String,
		/// The new column name.
		new_name: String,
	},
	/// Alter column type
	AlterColumnType {
		/// The column name.
		name: String,
		/// The new column type.
		new_type: String,
		/// Optional collation for the column.
		collation: Option<String>,
	},
	/// Set/drop column default
	AlterColumnDefault {
		/// The column name.
		name: String,
		/// The default value, or `None` to drop the default.
		default: Option<String>,
	},
	/// Set/drop NOT NULL constraint
	AlterColumnNullability {
		/// The column name.
		name: String,
		/// Whether the column is nullable.
		nullable: bool,
	},
	/// Add constraint
	AddConstraint {
		/// The constraint name.
		name: String,
		/// The constraint definition SQL.
		definition: String,
	},
	/// Drop constraint
	DropConstraint {
		/// The constraint name.
		name: String,
	},
}

/// Escapes a schema identifier by doubling double-quote characters.
///
/// This prevents SQL injection in schema names used within quoted identifiers.
/// For example, a schema name containing `"` will have it escaped to `""`.
fn escape_schema_identifier(name: &str) -> String {
	name.replace('"', "\"\"")
}

/// Base trait for database schema editors
///
/// This trait defines the interface that all database-specific schema editors must implement.
/// It provides methods for creating, altering, and dropping database schema objects.
///
/// # Example
///
/// ```rust,no_run
/// # use reinhardt_db::backends::schema::{BaseDatabaseSchemaEditor, SchemaEditorResult};
/// # use reinhardt_db::backends::DatabaseType;
/// # use async_trait::async_trait;
/// struct MySchemaEditor;
///
/// #[async_trait]
/// impl BaseDatabaseSchemaEditor for MySchemaEditor {
///     fn database_type(&self) -> DatabaseType {
///         DatabaseType::Postgres
///     }
///
///     async fn execute(&mut self, sql: &str) -> SchemaEditorResult<()> {
///         println!("Executing: {}", sql);
///         Ok(())
///     }
/// }
///
/// # async fn example() {
/// let mut editor = MySchemaEditor;
/// editor.execute("CREATE TABLE users (id INT)").await.unwrap();
/// # }
/// ```
#[async_trait::async_trait]
pub trait BaseDatabaseSchemaEditor: Send + Sync {
	/// Get the database type for this schema editor
	///
	/// Used to select the appropriate query builder when generating SQL
	fn database_type(&self) -> super::types::DatabaseType;

	/// Execute a SQL statement
	async fn execute(&mut self, sql: &str) -> SchemaEditorResult<()>;

	/// Generate CREATE TABLE statement using reinhardt-query
	///
	/// # Example
	///
	/// ```rust
	/// # use reinhardt_db::backends::schema::{BaseDatabaseSchemaEditor, SchemaEditorResult};
	/// # use reinhardt_db::backends::DatabaseType;
	/// # use async_trait::async_trait;
	/// # use reinhardt_query::prelude::{PostgresQueryBuilder, QueryBuilder};
	/// struct TestEditor;
	///
	/// #[async_trait]
	/// impl BaseDatabaseSchemaEditor for TestEditor {
	///     fn database_type(&self) -> DatabaseType {
	///         DatabaseType::Postgres
	///     }
	///
	///     async fn execute(&mut self, _sql: &str) -> SchemaEditorResult<()> {
	///         Ok(())
	///     }
	/// }
	///
	/// let editor = TestEditor;
	/// let stmt = editor.create_table_statement("users", &[
	///     ("id", "INTEGER PRIMARY KEY"),
	///     ("name", "VARCHAR(100)"),
	/// ]);
	/// let (sql, _) = PostgresQueryBuilder.build_create_table(&stmt);
	/// assert!(sql.contains("CREATE TABLE"));
	/// assert!(sql.contains("\"users\""));
	/// ```
	fn create_table_statement(
		&self,
		table: &str,
		columns: &[(&str, &str)],
	) -> CreateTableStatement {
		let mut binding = Query::create_table();
		let stmt = binding.table(Alias::new(table)).if_not_exists();

		for (name, definition) in columns {
			// Use custom() for raw type definitions since we receive them as strings
			stmt.col(ColumnDef::new(Alias::new(*name)).custom(*definition));
		}

		stmt.to_owned()
	}

	/// Generate DROP TABLE statement using reinhardt-query
	fn drop_table_statement(&self, table: &str, cascade: bool) -> DropTableStatement {
		let mut binding = Query::drop_table();
		let stmt = binding.table(Alias::new(table)).if_exists();

		if cascade {
			stmt.cascade();
		}

		stmt.to_owned()
	}

	/// Generate ALTER TABLE ADD COLUMN statement using reinhardt-query
	fn add_column_statement(
		&self,
		table: &str,
		column: &str,
		definition: &str,
	) -> AlterTableStatement {
		// Use custom() for raw type definitions
		Query::alter_table()
			.table(Alias::new(table))
			.add_column(ColumnDef::new(Alias::new(column)).custom(Alias::new(definition)))
			.to_owned()
	}

	/// Generate ALTER TABLE DROP COLUMN statement using reinhardt-query
	fn drop_column_statement(&self, table: &str, column: &str) -> AlterTableStatement {
		Query::alter_table()
			.table(Alias::new(table))
			.drop_column(Alias::new(column))
			.to_owned()
	}

	/// Generate ALTER TABLE RENAME COLUMN SQL
	///
	/// Always uses double quotes for PostgreSQL identifier safety.
	/// Note: reinhardt-query doesn't support RENAME COLUMN, so we use raw SQL.
	fn rename_column_statement(&self, table: &str, old_name: &str, new_name: &str) -> String {
		format!(
			"ALTER TABLE \"{}\" RENAME COLUMN \"{}\" TO \"{}\"",
			table, old_name, new_name
		)
	}

	/// Generate ALTER TABLE ALTER COLUMN TYPE SQL
	///
	/// Returns database-specific SQL for changing a column's type.
	/// Note: reinhardt-query doesn't support ALTER COLUMN TYPE, so we use raw SQL.
	///
	/// Default implementation uses PostgreSQL syntax:
	/// `ALTER TABLE table ALTER COLUMN column TYPE new_type`
	///
	/// Override this method in database-specific schema editors for:
	/// - MySQL: `ALTER TABLE table MODIFY COLUMN column new_type`
	/// - SQLite: Requires table recreation (complex multi-step process)
	/// - CockroachDB: Same as PostgreSQL
	fn alter_column_statement(&self, table: &str, column: &str, new_type: &str) -> String {
		format!(
			"ALTER TABLE \"{}\" ALTER COLUMN \"{}\" TYPE {}",
			table, column, new_type
		)
	}

	/// Generate CREATE INDEX statement using reinhardt-query (or raw SQL for partial indexes)
	///
	/// Note: reinhardt-query doesn't support partial indexes (WHERE clause), so we use raw SQL for those cases
	fn create_index_statement(
		&self,
		name: &str,
		table: &str,
		columns: &[&str],
		unique: bool,
		condition: Option<&str>,
	) -> Result<CreateIndexStatement, String> {
		if let Some(cond) = condition {
			// reinhardt-query doesn't support partial indexes, return error to indicate fallback needed
			// Always use double quotes for PostgreSQL identifier safety
			return Err(format!(
				"Partial indexes not supported by reinhardt-query. Use raw SQL: CREATE {}INDEX \"{}\" ON \"{}\" ({}) WHERE {}",
				if unique { "UNIQUE " } else { "" },
				name,
				table,
				columns
					.iter()
					.map(|c| format!("\"{}\"", c))
					.collect::<Vec<_>>()
					.join(", "),
				cond
			));
		}

		let mut binding = Query::create_index();
		let stmt = binding.name(Alias::new(name)).table(Alias::new(table));

		if unique {
			stmt.unique();
		}

		for col in columns {
			stmt.col(Alias::new(*col));
		}

		Ok(stmt.to_owned())
	}

	/// Generate DROP INDEX statement using reinhardt-query
	fn drop_index_statement(&self, name: &str) -> DropIndexStatement {
		let mut binding = Query::drop_index();
		binding.name(Alias::new(name)).if_exists().to_owned()
	}

	/// Generate CREATE SCHEMA statement
	///
	/// Note: reinhardt-query doesn't support CREATE SCHEMA, so we use raw SQL
	///
	/// # Arguments
	///
	/// * `name` - Schema name
	/// * `if_not_exists` - Whether to add IF NOT EXISTS clause
	///
	/// # Example
	///
	/// ```rust
	/// # use reinhardt_db::backends::schema::BaseDatabaseSchemaEditor;
	/// # use reinhardt_db::backends::DatabaseType;
	/// # use async_trait::async_trait;
	/// # use reinhardt_db::backends::schema::SchemaEditorResult;
	/// struct TestEditor;
	///
	/// #[async_trait]
	/// impl BaseDatabaseSchemaEditor for TestEditor {
	///     fn database_type(&self) -> DatabaseType {
	///         DatabaseType::Postgres
	///     }
	///
	///     async fn execute(&mut self, _sql: &str) -> SchemaEditorResult<()> {
	///         Ok(())
	///     }
	/// }
	///
	/// let editor = TestEditor;
	/// let sql = editor.create_schema_statement("my_schema", true);
	/// assert_eq!(sql, "CREATE SCHEMA IF NOT EXISTS \"my_schema\"");
	/// ```
	fn create_schema_statement(&self, name: &str, if_not_exists: bool) -> String {
		let escaped_name = escape_schema_identifier(name);
		if if_not_exists {
			format!("CREATE SCHEMA IF NOT EXISTS \"{}\"", escaped_name)
		} else {
			format!("CREATE SCHEMA \"{}\"", escaped_name)
		}
	}

	/// Generate DROP SCHEMA statement
	///
	/// Note: reinhardt-query doesn't support DROP SCHEMA, so we use raw SQL
	///
	/// # Arguments
	///
	/// * `name` - Schema name
	/// * `cascade` - Whether to add CASCADE clause
	/// * `if_exists` - Whether to add IF EXISTS clause
	///
	/// # Example
	///
	/// ```rust
	/// # use reinhardt_db::backends::schema::BaseDatabaseSchemaEditor;
	/// # use reinhardt_db::backends::DatabaseType;
	/// # use async_trait::async_trait;
	/// # use reinhardt_db::backends::schema::SchemaEditorResult;
	/// struct TestEditor;
	///
	/// #[async_trait]
	/// impl BaseDatabaseSchemaEditor for TestEditor {
	///     fn database_type(&self) -> DatabaseType {
	///         DatabaseType::Postgres
	///     }
	///
	///     async fn execute(&mut self, _sql: &str) -> SchemaEditorResult<()> {
	///         Ok(())
	///     }
	/// }
	///
	/// let editor = TestEditor;
	/// let sql = editor.drop_schema_statement("my_schema", true, true);
	/// assert_eq!(sql, "DROP SCHEMA IF EXISTS \"my_schema\" CASCADE");
	/// ```
	fn drop_schema_statement(&self, name: &str, cascade: bool, if_exists: bool) -> String {
		let if_exists_clause = if if_exists { " IF EXISTS" } else { "" };
		let cascade_clause = if cascade { " CASCADE" } else { "" };

		format!(
			"DROP SCHEMA{} \"{}\"{}",
			if_exists_clause,
			escape_schema_identifier(name),
			cascade_clause
		)
	}

	/// Build SQL string from `CreateTableStatement` using appropriate QueryBuilder
	fn build_create_table_sql(&self, stmt: &CreateTableStatement) -> String {
		use super::types::DatabaseType;

		let (sql, _values) = match self.database_type() {
			DatabaseType::Postgres => PostgresQueryBuilder.build_create_table(stmt),
			DatabaseType::Mysql => MySqlQueryBuilder.build_create_table(stmt),
			DatabaseType::Sqlite => SqliteQueryBuilder.build_create_table(stmt),
		};
		sql
	}

	/// Build SQL string from `DropTableStatement` using appropriate QueryBuilder
	fn build_drop_table_sql(&self, stmt: &DropTableStatement) -> String {
		use super::types::DatabaseType;

		let (sql, _values) = match self.database_type() {
			DatabaseType::Postgres => PostgresQueryBuilder.build_drop_table(stmt),
			DatabaseType::Mysql => MySqlQueryBuilder.build_drop_table(stmt),
			DatabaseType::Sqlite => SqliteQueryBuilder.build_drop_table(stmt),
		};
		sql
	}

	/// Build SQL string from `AlterTableStatement` using appropriate QueryBuilder
	fn build_alter_table_sql(&self, stmt: &AlterTableStatement) -> String {
		use super::types::DatabaseType;

		let (sql, _values) = match self.database_type() {
			DatabaseType::Postgres => PostgresQueryBuilder.build_alter_table(stmt),
			DatabaseType::Mysql => MySqlQueryBuilder.build_alter_table(stmt),
			DatabaseType::Sqlite => SqliteQueryBuilder.build_alter_table(stmt),
		};
		sql
	}

	/// Build SQL string from `CreateIndexStatement` using appropriate QueryBuilder
	fn build_create_index_sql(&self, stmt: &CreateIndexStatement) -> String {
		use super::types::DatabaseType;

		let (sql, _values) = match self.database_type() {
			DatabaseType::Postgres => PostgresQueryBuilder.build_create_index(stmt),
			DatabaseType::Mysql => MySqlQueryBuilder.build_create_index(stmt),
			DatabaseType::Sqlite => SqliteQueryBuilder.build_create_index(stmt),
		};
		sql
	}

	/// Build SQL string from `DropIndexStatement` using appropriate QueryBuilder
	fn build_drop_index_sql(&self, stmt: &DropIndexStatement) -> String {
		use super::types::DatabaseType;

		let (sql, _values) = match self.database_type() {
			DatabaseType::Postgres => PostgresQueryBuilder.build_drop_index(stmt),
			DatabaseType::Mysql => MySqlQueryBuilder.build_drop_index(stmt),
			DatabaseType::Sqlite => SqliteQueryBuilder.build_drop_index(stmt),
		};
		sql
	}
}

/// Result type for schema editor operations
pub type SchemaEditorResult<T> = Result<T, SchemaEditorError>;

/// Errors that can occur during schema editing operations
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum SchemaEditorError {
	/// SQL execution error
	ExecutionError(String),
	/// Invalid operation
	InvalidOperation(String),
	/// Database error
	DatabaseError(String),
}

impl fmt::Display for SchemaEditorError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			SchemaEditorError::ExecutionError(msg) => write!(f, "Execution error: {}", msg),
			SchemaEditorError::InvalidOperation(msg) => {
				write!(f, "Invalid operation: {}", msg)
			}
			SchemaEditorError::DatabaseError(msg) => write!(f, "Database error: {}", msg),
		}
	}
}

impl std::error::Error for SchemaEditorError {}

#[cfg(test)]
mod tests {
	use rstest::rstest;

	use super::*;

	struct TestSchemaEditor;

	#[async_trait::async_trait]
	impl BaseDatabaseSchemaEditor for TestSchemaEditor {
		async fn execute(&mut self, _sql: &str) -> SchemaEditorResult<()> {
			Ok(())
		}

		fn database_type(&self) -> crate::backends::types::DatabaseType {
			crate::backends::types::DatabaseType::Postgres
		}
	}

	#[test]
	fn test_create_table_statement() {
		use reinhardt_query::prelude::{PostgresQueryBuilder, QueryBuilder};

		let editor = TestSchemaEditor;
		let stmt = editor.create_table_statement(
			"users",
			&[("id", "INTEGER PRIMARY KEY"), ("name", "VARCHAR(100)")],
		);
		let (sql, _) = PostgresQueryBuilder.build_create_table(&stmt);

		assert!(sql.contains("CREATE TABLE"));
		assert!(sql.contains("\"users\""));
		assert!(sql.contains("\"id\""));
		assert!(sql.contains("\"name\""));
	}

	#[test]
	fn test_drop_table_statement() {
		use reinhardt_query::prelude::{PostgresQueryBuilder, QueryBuilder};

		let editor = TestSchemaEditor;

		let stmt_no_cascade = editor.drop_table_statement("users", false);
		let (sql_no_cascade, _) = PostgresQueryBuilder.build_drop_table(&stmt_no_cascade);
		assert!(sql_no_cascade.contains("DROP TABLE"));
		assert!(sql_no_cascade.contains("\"users\""));

		let stmt_cascade = editor.drop_table_statement("users", true);
		let (sql_cascade, _) = PostgresQueryBuilder.build_drop_table(&stmt_cascade);
		assert!(sql_cascade.contains("DROP TABLE"));
		assert!(sql_cascade.contains("\"users\""));
		assert!(sql_cascade.contains("CASCADE"));
	}

	#[test]
	fn test_add_column_statement() {
		use reinhardt_query::prelude::{PostgresQueryBuilder, QueryBuilder};

		let editor = TestSchemaEditor;
		let stmt = editor.add_column_statement("users", "email", "VARCHAR(255)");
		let (sql, _) = PostgresQueryBuilder.build_alter_table(&stmt);

		assert!(sql.contains("ALTER TABLE"));
		assert!(sql.contains("\"users\""));
		assert!(sql.contains("ADD COLUMN"));
		assert!(sql.contains("\"email\""));
		assert!(sql.contains("VARCHAR(255)"));
	}

	#[test]
	fn test_create_index_statement() {
		use reinhardt_query::prelude::{PostgresQueryBuilder, QueryBuilder};

		let editor = TestSchemaEditor;

		// Simple index
		let stmt = editor.create_index_statement("idx_email", "users", &["email"], false, None);
		let (sql, _) = PostgresQueryBuilder.build_create_index(&stmt.unwrap());
		assert!(sql.contains("CREATE INDEX"));
		assert!(sql.contains("idx_email"));
		assert!(sql.contains("\"users\""));

		// Unique index
		let unique_stmt =
			editor.create_index_statement("idx_email_uniq", "users", &["email"], true, None);
		let (unique_sql, _) = PostgresQueryBuilder.build_create_index(&unique_stmt.unwrap());
		assert!(unique_sql.contains("CREATE UNIQUE INDEX"));

		// Partial index (not supported by reinhardt-query, returns error with fallback SQL)
		let partial_result = editor.create_index_statement(
			"idx_active",
			"users",
			&["email"],
			false,
			Some("active = true"),
		);
		assert!(partial_result.is_err());
		let error_msg = partial_result.unwrap_err();
		assert!(error_msg.contains("Partial indexes not supported"));
		assert!(error_msg.contains("WHERE active = true"));
	}

	#[test]
	fn test_alter_column_statement() {
		let editor = TestSchemaEditor;

		// Test default PostgreSQL syntax
		let sql = editor.alter_column_statement("users", "email", "TEXT");
		assert_eq!(
			sql,
			"ALTER TABLE \"users\" ALTER COLUMN \"email\" TYPE TEXT"
		);

		// Verify identifier quoting
		assert!(sql.contains("\"users\""));
		assert!(sql.contains("\"email\""));
		assert!(sql.contains("TYPE TEXT"));
	}

	#[test]
	fn test_ddl_statement_table_name() {
		let stmt = DDLStatement::CreateTable {
			table: "users".to_string(),
			columns: vec![],
		};
		assert_eq!(stmt.table_name(), "users");

		let alter_stmt = DDLStatement::AlterTable {
			table: "posts".to_string(),
			changes: vec![],
		};
		assert_eq!(alter_stmt.table_name(), "posts");
	}

	#[rstest]
	#[case("my_schema", "CREATE SCHEMA IF NOT EXISTS \"my_schema\"")]
	#[case(
		"schema\"injection",
		"CREATE SCHEMA IF NOT EXISTS \"schema\"\"injection\""
	)]
	#[case(
		"special-chars_123",
		"CREATE SCHEMA IF NOT EXISTS \"special-chars_123\""
	)]
	fn test_create_schema_escapes_identifier(
		#[case] schema_name: &str,
		#[case] expected_sql: &str,
	) {
		// Arrange
		let editor = TestSchemaEditor;

		// Act
		let sql = editor.create_schema_statement(schema_name, true);

		// Assert
		assert_eq!(sql, expected_sql);
	}

	#[rstest]
	fn test_create_schema_without_if_not_exists() {
		// Arrange
		let editor = TestSchemaEditor;

		// Act
		let sql = editor.create_schema_statement("my_schema", false);

		// Assert
		assert_eq!(sql, "CREATE SCHEMA \"my_schema\"");
	}

	#[rstest]
	#[case("my_schema", "DROP SCHEMA IF EXISTS \"my_schema\" CASCADE")]
	#[case(
		"schema\"injection",
		"DROP SCHEMA IF EXISTS \"schema\"\"injection\" CASCADE"
	)]
	#[case(
		"special-chars_123",
		"DROP SCHEMA IF EXISTS \"special-chars_123\" CASCADE"
	)]
	fn test_drop_schema_escapes_identifier(#[case] schema_name: &str, #[case] expected_sql: &str) {
		// Arrange
		let editor = TestSchemaEditor;

		// Act
		let sql = editor.drop_schema_statement(schema_name, true, true);

		// Assert
		assert_eq!(sql, expected_sql);
	}

	#[rstest]
	fn test_drop_schema_without_cascade_and_if_exists() {
		// Arrange
		let editor = TestSchemaEditor;

		// Act
		let sql = editor.drop_schema_statement("my_schema", false, false);

		// Assert
		assert_eq!(sql, "DROP SCHEMA \"my_schema\"");
	}

	#[rstest]
	fn test_escape_schema_identifier_helper() {
		// Arrange / Act / Assert
		assert_eq!(escape_schema_identifier("simple"), "simple");
		assert_eq!(escape_schema_identifier("has\"quote"), "has\"\"quote");
		assert_eq!(
			escape_schema_identifier("multiple\"\"quotes"),
			"multiple\"\"\"\"quotes"
		);
		assert_eq!(escape_schema_identifier(""), "");
	}
}

#[cfg(test)]
pub mod test_utils;