Source file gen_migration.ml
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
let template_mariadb =
{|let create_{{name}}s_table =
Sihl.Database.Migration.create_step
~label:"create {{name}}s table"
{sql|
CREATE TABLE IF NOT EXISTS {{name}}s (
id BIGINT UNSIGNED AUTO_INCREMENT,
uuid BINARY(16) NOT NULL,
{{schema}},
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
CONSTRAINT unique_uuid UNIQUE KEY (uuid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|sql}
;;
let migration =
Sihl.Database.Migration.(
empty "{{name}}"
|> add_step create_{{name}}s_table
)
;;
|}
;;
let template_postgresql =
{|let create_{{name}}s_table =
Sihl.Database.Migration.create_step
~label:"create {{name}}s table"
{sql|
CREATE TABLE IF NOT EXISTS {{name}}s (
id serial,
uuid UUID NOT NULL,
{{schema}},
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE (uuid)
);
|sql}
;;
let migration =
Sihl.Database.Migration.(
empty "{{name}}"
|> add_step create_{{name}}s_table
)
;;
|}
;;
let type_of_gen_type_postgresql (t : Gen_core.gen_type) : string =
let open Gen_core in
match t with
| Float -> "DECIMAL NOT NULL"
| Int -> "INTEGER NOT NULL"
| Bool -> "BOOLEAN NOT NULL"
| String -> "VARCHAR(128) NOT NULL"
| Datetime -> "TIMESTAMP"
;;
let type_of_gen_type_mariadb (t : Gen_core.gen_type) : string =
let open Gen_core in
match t with
| Float -> "FLOAT NOT NULL"
| Int -> "INT NOT NULL"
| Bool -> "BOOLEAN NOT NULL"
| String -> "VARCHAR(128) NOT NULL"
| Datetime -> "TIMESTAMP"
;;
let migration_schema_postgresql (schema : Gen_core.schema) =
schema
|> List.map (fun (name, type_) ->
Format.sprintf "%s %s" name (type_of_gen_type_postgresql type_))
|> String.concat ",\n "
;;
let migration_schema_mariadb (schema : Gen_core.schema) =
schema
|> List.map (fun (name, type_) ->
Format.sprintf "%s %s" name (type_of_gen_type_mariadb type_))
|> String.concat ",\n "
;;
let write_migration_file
(database : Gen_core.database)
(name : string)
(schema : Gen_core.schema)
=
let open Gen_core in
let file =
match database with
| PostgreSql ->
{ name = Format.sprintf "%s.ml" name
; template = template_postgresql
; params = [ "name", name; "schema", migration_schema_postgresql schema ]
}
| MariaDb ->
{ name = Format.sprintf "%s.ml" name
; template = template_mariadb
; params = [ "name", name; "schema", migration_schema_mariadb schema ]
}
in
write_in_database file
;;