forked from fsprojects/Rezoom.SQL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModelOps.fs
More file actions
488 lines (457 loc) · 22.7 KB
/
ModelOps.fs
File metadata and controls
488 lines (457 loc) · 22.7 KB
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
/// Fundamental operations on the model.
/// The model should only be modified (it's immutable, so by modified I mean creation of altered copies)
/// via these primitives. This will ensure invariants like that every foreign key constraint has a reverse foreign
/// key tracking it in the referenced table.
module Rezoom.SQL.Compiler.ModelOps
let getSchema (name : Name) =
stateful {
let! model = State.get
return model.Schemas |> Map.tryFind name
}
let getObject (name : QualifiedObjectName) =
stateful {
let! schema = getSchema name.SchemaName
match schema with
| None -> return None
| Some schema ->
return schema.Objects |> Map.tryFind name.ObjectName
}
let private requireNoObject (name : QualifiedObjectName WithSource) =
stateful {
let! obj = getObject name.Value
match obj with
| Some _ -> failAt name.Source <| Error.objectAlreadyExists name.Value
| None -> ()
}
let getRequiredSchema (schemaName: Name option WithSource) =
stateful {
let! model = State.get
let source = schemaName.Source
let schemaName =
match schemaName.Value with
| None -> model.DefaultSchema
| Some name -> name
let! schema = getSchema schemaName
return
match schema with
| Some obj -> obj
| None ->
schemaName
|> Error.noSuchSchema model.Schemas
|> failAt source
}
let getRequiredObject objectTypeName (name : QualifiedObjectName WithSource) =
stateful {
let! model = State.get
let! schema = name.Map(fun n -> Some n.SchemaName) |> getRequiredSchema
return
match schema.Objects |> Map.tryFind name.Value.ObjectName with
| None -> failAt name.Source <| Error.noSuchObject objectTypeName name.Value.ObjectName
| Some obj -> obj
}
let getRequiredTable name =
getRequiredObject "table" name
|> State.map (function
| SchemaTable t -> t
| _ -> failAt name.Source <| Error.objectIsNotA "table" name.Value)
let getRequiredView name =
getRequiredObject "view" name
|> State.map (function
| SchemaView v -> v
| _ -> failAt name.Source <| Error.objectIsNotA "view" name.Value)
let getRequiredIndex name =
getRequiredObject "index" name
|> State.map (function
| SchemaIndex i -> i
| _ -> failAt name.Source <| Error.objectIsNotA "index" name.Value)
let getRequiredColumn tableName (columnName : Name WithSource) =
getRequiredTable tableName
|> State.map (fun tbl ->
match tbl.Columns |> Map.tryFind columnName.Value with
| None -> failAt columnName.Source <| Error.noSuchColumn columnName.Value
| Some col -> col)
/// Create or update a schema within the model.
let putSchema (schema : Schema) =
stateful {
let! model = State.get
let newModel = { model with Schemas = model.Schemas |> Map.add schema.SchemaName schema }
return! State.put newModel
}
/// Create or update an object within an existing schema in the model.
let putObject (name : QualifiedObjectName WithSource) (obj : SchemaObject) =
stateful {
let! model = State.get
let! schema = name.Map(fun n -> Some n.SchemaName) |> getRequiredSchema
let newSchema = { schema with Objects = schema.Objects |> Map.add name.Value.ObjectName obj }
return! putSchema newSchema
}
/// Remove an existing object from the model.
let removeObject (name : QualifiedObjectName WithSource) =
stateful {
let! model = State.get
let! schema = name.Map(fun n -> Some n.SchemaName) |> getRequiredSchema
let newSchema = { schema with Objects = schema.Objects |> Map.remove name.Value.ObjectName }
return! putSchema newSchema
}
/// Create a new table with a given name.
let createEmptyTable (tableName : QualifiedObjectName WithSource) =
stateful {
do! requireNoObject tableName
let table =
{ Name = tableName.Value
Columns = Map.empty
Indexes = Map.empty
Constraints = Map.empty
ReverseForeignKeys = Set.empty
}
return! putObject tableName (SchemaTable table)
}
[<NoComparison>]
type AddingColumn =
{ Name : Name WithSource
TypeName : TypeName
Nullable : bool
DefaultValue : Expr option
Collation : Name option
}
/// Add a column to an existing table.
let addTableColumn (tableName : QualifiedObjectName WithSource) (column : AddingColumn) =
stateful {
let! table = getRequiredTable tableName
match table.Columns |> Map.tryFind column.Name.Value with
| None ->
match column.Collation with
| None -> ()
| Some _ ->
if not column.TypeName.SupportsCollation then
failAt column.Name.Source <| Error.cannotCollateType column.TypeName
let schemaColumn =
{ TableName = tableName.Value
ColumnName = column.Name.Value
ColumnType = ColumnType.OfTypeName(column.TypeName, column.Nullable)
ColumnTypeName = column.TypeName
PrimaryKey = false
DefaultValue = column.DefaultValue
Collation = column.Collation
}
let table =
{ table with Columns = table.Columns |> Map.add schemaColumn.ColumnName schemaColumn }
return! putObject tableName (SchemaTable table)
| Some _ ->
failAt column.Name.Source <| Error.columnAlreadyExists column.Name.Value
}
let private mapValues f map =
Map.map (fun _ v -> f v) map
let private replaceMany xs key map =
xs |> Seq.fold (fun m x -> Map.add (key x) x m) map
/// Add a table constraint.
let addConstraint (tableName : QualifiedObjectName WithSource) (constraintName : Name WithSource) constraintType cols =
stateful {
let qualifiedConstraintName =
{ SchemaName = tableName.Value.SchemaName; ObjectName = constraintName.Value }
|> atSource constraintName.Source
do! requireNoObject qualifiedConstraintName
let! table = getRequiredTable tableName
match table.Constraints |> Map.tryFind constraintName.Value with
| None ->
let constr =
{ TableName = tableName.Value
ConstraintName = constraintName.Value
ConstraintType = constraintType
Columns = cols
}
let table =
match constraintType with
| PrimaryKeyConstraintType autoIncrement ->
let existingPk =
table.Constraints |> Map.tryPick (fun _ constr ->
match constr.ConstraintType with
| PrimaryKeyConstraintType _ -> Some constr.ConstraintName
| _ -> None)
match existingPk with
| Some existingPk ->
failAt constraintName.Source <| Error.tableAlreadyHasPrimaryKey table.Name existingPk
| None -> ()
let columns =
cols
|> Seq.map (fun c ->
let found = Map.find c table.Columns
if autoIncrement then
match found.ColumnType.Type with
| IntegerType _ -> ()
| _ -> failAt constraintName.Source <| Error.onlyIntPrimaryKeyAutoincrement
{ found with PrimaryKey = true })
{ table with Columns = table.Columns |> replaceMany columns (fun c -> c.ColumnName) }
| ForeignKeyConstraintType _
| CheckConstraintType
| UniqueConstraintType -> table
let table =
{ table with Constraints = table.Constraints |> Map.add constraintName.Value constr }
do! putObject tableName (SchemaTable table)
do! putObject qualifiedConstraintName (SchemaConstraint constr)
match constraintType with
| ForeignKeyConstraintType fk ->
let targetName = artificialSource fk.ToTable
let! target = getRequiredTable targetName
let reverse =
{ FromTable = tableName.Value
FromConstraint = constraintName.Value
OnDelete = fk.OnDelete
}
let target =
{ target with ReverseForeignKeys = target.ReverseForeignKeys |> Set.add reverse }
do! putObject targetName (SchemaTable target)
| _ -> ()
| Some _ -> failAt constraintName.Source <| Error.constraintAlreadyExists constraintName.Value
}
/// Create an index to a table. There must not be an existing index with the same name.
let createIndex (tableName : QualifiedObjectName WithSource) (indexName : QualifiedObjectName WithSource) cols =
stateful {
if indexName.Value.SchemaName <> tableName.Value.SchemaName then
failAt indexName.Source <| Error.indexSchemasMismatch indexName.Value tableName.Value
do! requireNoObject indexName
let! table = getRequiredTable tableName
match table.Indexes |> Map.tryFind indexName.Value.ObjectName with
| None ->
let index =
{ TableName = tableName.Value
IndexName = indexName.Value.ObjectName
Columns = cols
}
let table = { table with Indexes = table.Indexes |> Map.add indexName.Value.ObjectName index }
do! putObject indexName (SchemaIndex index)
return! putObject tableName (SchemaTable table)
| Some _ -> failAt indexName.Source <| Error.indexAlreadyExists indexName.Value
}
/// Create a view.
let createView (viewName : QualifiedObjectName WithSource) (createDefinition : CreateViewStmt) =
stateful {
do! requireNoObject viewName
let view =
{ SchemaName = viewName.Value.SchemaName
ViewName = viewName.Value.ObjectName
CreateDefinition = createDefinition
}
return! putObject viewName (SchemaView view)
}
/// Rename an existing table *and* update other references in the schema that point to it (child objects of the table
/// and foreign keys in other tables). Does not update source code of views, however.
let renameTable (oldName : QualifiedObjectName WithSource) (newName : QualifiedObjectName WithSource) =
stateful {
let! oldTable = getRequiredTable oldName
do! requireNoObject newName
let tn = newName.Value
let newTable =
{ Name = tn
Columns = oldTable.Columns |> mapValues (fun c -> { c with TableName = tn })
Indexes = oldTable.Indexes |> mapValues (fun i -> { i with TableName = tn })
Constraints = oldTable.Constraints |> mapValues (fun c -> { c with TableName = tn })
ReverseForeignKeys = oldTable.ReverseForeignKeys
}
do! removeObject oldName
do! putObject newName (SchemaTable newTable)
for reverseFk in newTable.ReverseForeignKeys do
let fromTableName = artificialSource reverseFk.FromTable
let! fromTable = getRequiredTable fromTableName
let fromTable =
let updateConstraint (constr : SchemaConstraint) =
match constr.ConstraintType with
| ForeignKeyConstraintType fk ->
{ constr with
ConstraintType = ForeignKeyConstraintType { fk with ToTable = newName.Value } }
| _ -> constr
{ fromTable with
Constraints = fromTable.Constraints |> mapValues updateConstraint
}
do! putObject fromTableName (SchemaTable fromTable)
}
let dropColumn tableName (column : Name) =
stateful {
let! table = getRequiredTable tableName
match table.Columns |> Map.tryFind column with
| None ->
// IMPROVEMENT oughta have better source location
failAt tableName.Source <| Error.noSuchColumn column
| Some existing ->
if existing.DefaultValue |> Option.isSome then
let! model = State.get
if not model.BackendCharacteristics.CanDropColumnWithDefaultValue then
failAt tableName.Source <| Error.cannotDropColumnWithDefault column
let coveredByConstraints =
table.Constraints
|> Seq.filter (function KeyValue(_, constr) -> constr.Columns |> Set.contains column)
|> Seq.map (function KeyValue(_, constr) -> constr.ConstraintName)
|> Seq.cache
if Seq.isEmpty coveredByConstraints then
for rfk in table.ReverseForeignKeys do
let! referencingTable = getRequiredTable (artificialSource rfk.FromTable)
let referencingConstr = referencingTable.Constraints |> Map.find rfk.FromConstraint
match referencingConstr.ConstraintType with
| ForeignKeyConstraintType fk ->
if fk.ToColumns |> Set.contains column then
let refName =
string referencingTable.Name + "." + string referencingConstr.ConstraintName
failAt tableName.Source <| Error.columnIsReferencedByConstraints column [refName]
| _ -> ()
let table = { table with Columns = table.Columns |> Map.remove column }
if table.Columns |> Map.isEmpty then
failAt tableName.Source <| Error.cannotDropLastColumn tableName.Value column
return! putObject tableName (SchemaTable table)
else
failAt tableName.Source <| Error.columnIsReferencedByConstraints column coveredByConstraints
}
/// Remove an existing table from the model.
/// This handles checking for references to the table, and removing reverse references.
let dropTable (tableName : QualifiedObjectName WithSource) =
stateful {
let! tbl = getRequiredTable tableName
let referencingTables = tbl.ReverseForeignKeys |> Set.map (fun fk -> fk.FromTable)
if Set.isEmpty referencingTables then
for constr in tbl.Constraints do
match constr.Value.ConstraintType with
| ForeignKeyConstraintType fk -> // remove reverse foreign keys from target table
let targetTableName = artificialSource fk.ToTable
let! targetTable = getRequiredTable targetTableName
let reverseKeys =
targetTable.ReverseForeignKeys
|> Set.filter (fun r -> r.FromTable <> tableName.Value)
do! putObject targetTableName (SchemaTable { targetTable with ReverseForeignKeys = reverseKeys })
| _ -> ()
for constr in tbl.Constraints do
do! removeObject (artificialSource { tbl.Name with ObjectName = constr.Key })
for idx in tbl.Indexes do
do! removeObject (artificialSource { tbl.Name with ObjectName = idx.Key })
return! removeObject tableName
else
failAt tableName.Source <| Error.tableIsReferencedByFKs tableName.Value referencingTables
}
/// Remove an existing view from the model.
let dropView (viewName : QualifiedObjectName WithSource) =
stateful {
let! _ = getRequiredView viewName // ensure it exists
return! removeObject viewName
}
/// Remove an existing index from the model.
let dropIndex (indexName : QualifiedObjectName WithSource) =
stateful {
let! index = getRequiredIndex indexName
let tableName = artificialSource index.TableName
let! table = getRequiredTable tableName
let table = { table with Indexes = table.Indexes |> Map.remove index.IndexName }
do! putObject tableName (SchemaTable table)
return! removeObject indexName
}
/// Remove an existing table constraint from the mode.
let dropConstraint (tableName : QualifiedObjectName WithSource) (constraintName : Name WithSource) =
stateful {
let! table = getRequiredTable tableName
match table.Constraints |> Map.tryFind constraintName.Value with
| None -> failAt constraintName.Source <| Error.noSuchConstraint tableName.Value constraintName.Value
| Some constr ->
let table = { table with Constraints = table.Constraints |> Map.remove constraintName.Value }
do! putObject tableName (SchemaTable table)
let qualifiedConstraintName =
{ SchemaName = tableName.Value.SchemaName; ObjectName = constraintName.Value }
|> atSource constraintName.Source
do! removeObject qualifiedConstraintName
match constr.ConstraintType with
| ForeignKeyConstraintType fk ->
// go remove reverse FK from targeted table
let targetTableName = artificialSource fk.ToTable
let! targetTable = getRequiredTable targetTableName
let reverseForeignKeys =
targetTable.ReverseForeignKeys
|> Set.filter (fun r -> r.FromTable <> tableName.Value || r.FromConstraint <> constraintName.Value)
let targetTable = { targetTable with ReverseForeignKeys = reverseForeignKeys }
return! putObject targetTableName (SchemaTable targetTable)
| PrimaryKeyConstraintType _ ->
// remove PK attribute from columns
let unPKed = constr.Columns |> Seq.map (fun c -> { Map.find c table.Columns with PrimaryKey = false })
let table = { table with Columns = table.Columns |> replaceMany unPKed (fun c -> c.ColumnName) }
return! putObject tableName (SchemaTable table)
| CheckConstraintType _
| UniqueConstraintType -> ()
}
let addColumnDefault (tableName : QualifiedObjectName WithSource) (columnName : Name WithSource) (defaultVal : Expr) =
stateful {
let! table = getRequiredTable tableName
match table.Columns |> Map.tryFind columnName.Value with
| None -> failAt columnName.Source <| Error.noSuchColumn columnName.Value
| Some col ->
match col.DefaultValue with
| Some _ -> failAt columnName.Source <| Error.columnAlreadyHasDefault columnName.Value
| None ->
let col = { col with DefaultValue = Some defaultVal }
let table = { table with Columns = table.Columns |> Map.add columnName.Value col }
return! putObject tableName (SchemaTable table)
}
/// Remove the default value from a column.
let dropColumnDefault (tableName : QualifiedObjectName WithSource) (columnName : Name WithSource) =
stateful {
let! table = getRequiredTable tableName
match table.Columns |> Map.tryFind columnName.Value with
| None -> failAt columnName.Source <| Error.noSuchColumn columnName.Value
| Some col ->
match col.DefaultValue with
| None -> failAt columnName.Source <| Error.noDefaultConstraintToDrop tableName.Value columnName.Value
| Some _ ->
let col = { col with DefaultValue = None }
let table = { table with Columns = table.Columns |> Map.add columnName.Value col }
return! putObject tableName (SchemaTable table)
}
/// Change a column's type.
let changeColumnType tableName (columnName : Name WithSource) newType =
stateful {
let! table = getRequiredTable tableName
match table.Columns |> Map.tryFind columnName.Value with
| None ->
failAt columnName.Source <| Error.noSuchColumn columnName.Value
| Some col ->
if col.PrimaryKey then
failAt columnName.Source <| Error.cannotAlterPrimaryKeyColumn columnName.Value
if col.ColumnTypeName = newType then
failAt columnName.Source <| Error.columnTypeIsAlready columnName.Value newType
// FUTURE validate that referencing FKs have compatible type? default value has compatible type?
let newColumn =
{ col with
ColumnType = ColumnType.OfTypeName(newType, col.ColumnType.Nullable)
ColumnTypeName = newType
Collation = if newType.SupportsCollation then col.Collation else None
}
let table = { table with Columns = table.Columns |> Map.add columnName.Value newColumn }
return! putObject tableName (SchemaTable table)
}
let changeColumnNullability tableName (columnName : Name WithSource) newNullable =
stateful {
let! table = getRequiredTable tableName
match table.Columns |> Map.tryFind columnName.Value with
| None ->
failAt columnName.Source <| Error.noSuchColumn columnName.Value
| Some col ->
if col.PrimaryKey then
failAt columnName.Source <| Error.cannotAlterPrimaryKeyColumn columnName.Value
if col.ColumnType.Nullable = newNullable then
failAt columnName.Source <| Error.columnNullabilityIsAlready columnName.Value newNullable
let newColumn =
{ col with ColumnType = { col.ColumnType with Nullable = newNullable } }
let table = { table with Columns = table.Columns |> Map.add columnName.Value newColumn }
return! putObject tableName (SchemaTable table)
}
let changeColumnCollation tableName (columnName : Name WithSource) newCollation =
stateful {
let! table = getRequiredTable tableName
match table.Columns |> Map.tryFind columnName.Value with
| None ->
failAt columnName.Source <| Error.noSuchColumn columnName.Value
| Some col ->
if col.PrimaryKey then
failAt columnName.Source <| Error.cannotAlterPrimaryKeyColumn columnName.Value
if col.Collation = Some newCollation then
failAt columnName.Source <| Error.columnCollationIsAlready columnName.Value newCollation
if not col.ColumnTypeName.SupportsCollation then
failAt columnName.Source <| Error.cannotCollateType col.ColumnTypeName
let newColumn =
{ col with Collation = Some newCollation }
let table = { table with Columns = table.Columns |> Map.add columnName.Value newColumn }
return! putObject tableName (SchemaTable table)
}