Skip to main content

schema_installer/
tracking.rs

1use schema_sql_generator::common::generator_type::GeneratorType;
2
3pub struct SchemaMigrationDdl;
4
5impl SchemaMigrationDdl {
6    pub fn schema_migration_ddl(database_type: &GeneratorType) -> String {
7        match database_type {
8            GeneratorType::Postgresql => {
9                r#"CREATE TABLE IF NOT EXISTS schema_migration (
10    id BIGSERIAL PRIMARY KEY,
11    version TEXT NOT NULL,
12    script_path TEXT NOT NULL,
13    checksum TEXT NOT NULL,
14    execution_time_ms INT NOT NULL,
15    installed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
16    status TEXT NOT NULL,
17    tool_version TEXT NOT NULL
18);"#
19                    .to_string()
20            }
21            GeneratorType::SqlServer => {
22                r#"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='dbo' AND TABLE_NAME='schema_migration')
23BEGIN
24  CREATE TABLE dbo.schema_migration (
25    id BIGINT IDENTITY(1,1) PRIMARY KEY,
26    version NVARCHAR(MAX) NOT NULL,
27    script_path NVARCHAR(MAX) NOT NULL,
28    checksum NVARCHAR(MAX) NOT NULL,
29    execution_time_ms INT NOT NULL,
30    installed_at DATETIME2 NOT NULL DEFAULT GETDATE(),
31    status NVARCHAR(MAX) NOT NULL,
32    tool_version NVARCHAR(MAX) NOT NULL
33  );
34END"#
35                    .to_string()
36            }
37            GeneratorType::Sqlite => {
38                r#"CREATE TABLE IF NOT EXISTS schema_migration (
39    id INTEGER PRIMARY KEY AUTOINCREMENT,
40    version TEXT NOT NULL,
41    script_path TEXT NOT NULL,
42    checksum TEXT NOT NULL,
43    execution_time_ms INTEGER NOT NULL,
44    installed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
45    status TEXT NOT NULL,
46    tool_version TEXT NOT NULL
47);"#
48                    .to_string()
49            }
50        }
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn test_postgres_schema_migration_ddl() {
60        let ddl = SchemaMigrationDdl::schema_migration_ddl(&GeneratorType::Postgresql);
61        assert!(ddl.contains("CREATE TABLE IF NOT EXISTS schema_migration"));
62        assert!(ddl.contains("BIGSERIAL PRIMARY KEY"));
63    }
64
65    #[test]
66    fn test_sqlserver_schema_migration_ddl() {
67        let ddl = SchemaMigrationDdl::schema_migration_ddl(&GeneratorType::SqlServer);
68        assert!(ddl.contains("dbo.schema_migration"));
69        assert!(ddl.contains("BIGINT IDENTITY(1,1)"));
70    }
71
72    #[test]
73    fn test_sqlite_schema_migration_ddl() {
74        let ddl = SchemaMigrationDdl::schema_migration_ddl(&GeneratorType::Sqlite);
75        assert!(ddl.contains("CREATE TABLE IF NOT EXISTS schema_migration"));
76        assert!(ddl.contains("INTEGER PRIMARY KEY AUTOINCREMENT"));
77    }
78}