-
Notifications
You must be signed in to change notification settings - Fork 0
/
Database.fs
440 lines (380 loc) · 16.8 KB
/
Database.fs
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
/// Module containing database access models and functions.
[<CompilationRepresentation (CompilationRepresentationFlags.ModuleSuffix)>]
module NikonTheThird.Krystallizer.Database
open FSharp.Control
open Npgsql
open Serilog
open System
open System.Data.Common
open System.Threading
/// The directory model for the database.
type [<Struct>] DirectoryEntry = {
/// The id of the directory. When inserting, the id
/// will be set by the database.
Id : int32
/// The parent directory id of this directory, or none
/// when the directory is a root directory.
ParentId : int32 voption
/// The name of the directory.
Name : string
}
/// The file model for the database.
type [<Struct>] FileEntry = {
/// The id of the file. When inserting, the id
/// will be set by the database.
Id : int32
/// The id of the directory the file is in.
DirectoryId : int32
/// The name of the file.
Name : string
/// The length of the file in bytes.
Length : int64
/// The computed hash of the file contents.
Hash : byte array
}
/// SQL statement to create the "Directories" table.
let [<Literal>] private CreateDirectoryTableSql = """
create table if not exists "Directories" (
"Id" serial primary key,
"ParentId" integer,
"Name" text not null,
foreign key ("ParentId") references "Directories" ("Id") on delete cascade
)
"""
/// SQL statement to create the "Files" table.
let [<Literal>] private CreateFileTableSql = """
create table if not exists "Files" (
"Id" serial primary key,
"DirectoryId" integer not null,
"Name" text not null,
"Length" bigint not null,
"Hash" bytea not null,
foreign key ("DirectoryId") references "Directories" ("Id") on delete cascade
)
"""
/// SQL statement to create an index for the "ParentId" column of
/// the "Directories" table. This index is used when looking for
/// all subdirectories of a particular directory.
let [<Literal>] private CreateDirectoryParentIdIndexSql = """
create index if not exists "DirectoriesParentIdIndex"
on "Directories" ("ParentId")
"""
/// SQL statement to create an index for the "DirectoryId" column
/// of the "Files" table. This index is used when looking for
/// all files in a particular directory.
let [<Literal>] private CreateFileDirectoryIdIndexSql = """
create index if not exists "FilesDirectoryIdIndex"
on "Files" ("DirectoryId")
"""
/// SQL statement to create an index for the "Hash" column
/// of the "Files" table. This index is used to find all
/// duplicate files.
let [<Literal>] private CreateFileHashIndexSql = """
create index if not exists "FilesHashIndex"
on "Files" ("Hash")
"""
/// SQL statement to insert a new directory entry.
let [<Literal>] private InsertDirectorySql = """
insert into "Directories" (
"ParentId",
"Name"
) values (
@parentId,
@name
) returning "Id"
"""
/// SQL statement that selects all columns of the "Directories"
/// table and is used to construct other queries on this table.
let [<Literal>] private SelectDirectoryTemplateSql = """
select d."Id",
d."ParentId",
d."Name"
from "Directories" d
"""
/// SQL statement to select a single directory entry by its id.
let [<Literal>] private SelectDirectoryByIdSql =
SelectDirectoryTemplateSql + """
where d."Id" = @id
"""
/// SQL statement to select a single directory entry by its parent
/// directory id and name. This combination is unique.
let [<Literal>] private SelectDirectoryByParentIdAndNameSql =
SelectDirectoryTemplateSql + """
where (
(d."ParentId" = @parentId and @parentId is not null) or
(d."ParentId" is null and @parentId is null)
) and
d."Name" = @name
"""
/// SQL statement that selects all subdirectory entries with
/// the same parent directory id.
let [<Literal>] private SelectDirectoriesByParentIdSql =
SelectDirectoryTemplateSql + """
where (d."ParentId" = @parentId and @parentId is not null) or
(d."ParentId" is null and @parentId is null)
"""
/// SQL statement to delete a directory entry.
/// Cascade delete removes all subdirectory entries and
/// file entries as well.
let [<Literal>] private DeleteDirectorySql = """
delete from "Directories"
where "Id" = @id
"""
/// SQL statement to insert a new file entry.
let [<Literal>] private InsertFileSql = """
insert into "Files" (
"DirectoryId",
"Name",
"Length",
"Hash"
) values (
@directoryId,
@name,
@length,
@hash
) returning "Id"
"""
/// SQL statement that selects all columns of the "Files"
/// table and is used to construct other queries on this table.
let [<Literal>] private SelectFileTemplateSql = """
select f."Id",
f."DirectoryId",
f."Name",
f."Length",
f."Hash"
from "Files" f
"""
/// SQL statement to select a single file entry by its id.
let [<Literal>] private SelectFileByIdSql =
SelectFileTemplateSql + """
where f."Id" = @id
"""
/// SQL statement that selects all file entries in a
/// particular directory.
let [<Literal>] private SelectFilesByDirectoryIdSql =
SelectFileTemplateSql + """
where f."DirectoryId" = @directoryId
"""
/// SQL statement that selects all file entries that
/// have duplicate hashes.
let [<Literal>] private SelectDuplicateFilesSql =
SelectFileTemplateSql + """
join (
select inner_f."Hash"
from "Files" inner_f
group by inner_f."Hash"
having count(*) > 1
) d on f."Hash" = d."Hash"
"""
/// SQL statement to delete a file entry.
let [<Literal>] private DeleteFileSql = """
delete from "Files"
where "Id" = @id
"""
/// Represents an open database connection.
type DatabaseConnection private (connection : NpgsqlConnection) =
static let logger = Log.ForContext<DatabaseConnection> ()
let semaphore = new SemaphoreSlim 1
/// Establish a connection to the database using the given
/// connection string.
static member EstablishConnection connectionString = async {
let! token = Async.CancellationToken
do logger.Debug "Establishing a database connection"
let connection = new NpgsqlConnection (connectionString)
do! connection.OpenAsync token |> Async.AwaitTask
return new DatabaseConnection (connection)
}
/// Reads a directory entry from the given data reader
/// according to the columns in the directory select template.
member inline private _.ReadDirectory (reader : DbDataReader) = {
Id = reader.GetInt32 0
ParentId = reader.GetInt32Option 1
Name = reader.GetString 2
}
/// Reads a file entry from the given data reader
/// according to the columns in the file select template.
member inline private _.ReadFile (reader : DbDataReader) = {
Id = reader.GetInt32 0
DirectoryId = reader.GetInt32 1
Name = reader.GetString 2
Length = reader.GetInt64 3
Hash = reader.GetByteArray 4
}
/// Creates all tables and indexes in the database
/// if they do not exist.
member _.CreateDatabaseStructure () = async {
let! token = Async.CancellationToken
let createStatements = [
CreateDirectoryTableSql
CreateFileTableSql
CreateDirectoryParentIdIndexSql
CreateFileDirectoryIdIndexSql
CreateFileHashIndexSql
]
do! semaphore.WaitAsync token |> Async.AwaitTask
try for createStatement in createStatements do
use command = connection.CreateCommand ()
do command.CommandText <- createStatement
do! command.ExecuteNonQueryAsync token |> Async.AwaitTask |> Async.Ignore
finally semaphore.Release () |> ignore
}
/// Adds a new directory entry to the database. The id of the given directory
/// entry is ignored and a new directory entry with the correct id is returned.
member _.AddDirectory ({ ParentId = parentId; Name = name } as directoryEntry) = async {
let! token = Async.CancellationToken
do! semaphore.WaitAsync token |> Async.AwaitTask
try use command = connection.CreateCommand ()
do command.CommandText <- InsertDirectorySql
do command.AddTypedOptionParameter (nameof parentId, parentId)
do command.AddTypedParameter (nameof name, name)
use! reader = command.ExecuteReaderAsync token |> Async.AwaitTask
match! reader.ReadAsync token |> Async.AwaitTask with
| true ->
return { directoryEntry with Id = reader.GetInt32 0 }
| false ->
do logger.Error ("Could not add directory entry with parent id {parentId} and name {name}, no id returned", parentId, name)
return failwithf "Could not add directory entry with parent id %A and name %s, no id returned" parentId name
finally semaphore.Release () |> ignore
}
/// Returns a directory entry with the given id. If the directory entry does
/// not exist, an exception is raised.
member this.GetDirectoryById id = async {
let! token = Async.CancellationToken
do! semaphore.WaitAsync token |> Async.AwaitTask
try use command = connection.CreateCommand ()
do command.CommandText <- SelectDirectoryByIdSql
do command.AddTypedParameter<int32> (nameof id, id)
use! reader = command.ExecuteReaderAsync token |> Async.AwaitTask
match! reader.ReadAsync token |> Async.AwaitTask with
| true ->
return this.ReadDirectory reader
| false ->
do logger.Error ("Could not get directory entry with id {id}", id)
return failwithf "Could not get directory entry with id %d" id
finally semaphore.Release () |> ignore
}
/// Returns a directory entry with the given parent directory id and name.
/// If the directory entry does not exist, none is returned.
member this.TryGetDirectoryByParentIdAndName (parentId, name) = async {
let! token = Async.CancellationToken
do! semaphore.WaitAsync token |> Async.AwaitTask
try use command = connection.CreateCommand ()
do command.CommandText <- SelectDirectoryByParentIdAndNameSql
do command.AddTypedOptionParameter<int32> (nameof parentId, parentId)
do command.AddTypedParameter<string> (nameof name, name)
use! reader = command.ExecuteReaderAsync token |> Async.AwaitTask
match! reader.ReadAsync token |> Async.AwaitTask with
| true ->
return this.ReadDirectory reader |> ValueSome
| false ->
return ValueNone
finally semaphore.Release () |> ignore
}
/// Returns a directory entry with the given parent directory id and name.
/// If no such directory entry exists, an exception is raised.
member this.GetDirectoryByParentIdAndName (parentId, name) = async {
match! this.TryGetDirectoryByParentIdAndName (parentId, name) with
| ValueSome directory ->
return directory
| ValueNone ->
do logger.Error ("Could not get directory entry with parent id {parentId} and name {name}", parentId, name)
return failwithf "Could not get directory entry with parent id %A and name %s" parentId name
}
/// Returns all subdirectory entries of the given parent directory id.
member this.GetDirectoriesByParentId parentId = asyncSeq {
let! token = Async.CancellationToken
do! semaphore.WaitAsync token |> Async.AwaitTask
try use command = connection.CreateCommand ()
do command.CommandText <- SelectDirectoriesByParentIdSql
do command.AddTypedOptionParameter<int32> (nameof parentId, parentId)
use! reader = command.ExecuteReaderAsync token |> Async.AwaitTask
while reader.ReadAsync token |> Async.AwaitTask do
yield this.ReadDirectory reader
finally semaphore.Release () |> ignore
}
/// Removes the directory entry with the given id.
member _.RemoveDirectory id = async {
let! token = Async.CancellationToken
do! semaphore.WaitAsync token |> Async.AwaitTask
try use command = connection.CreateCommand ()
do command.CommandText <- DeleteDirectorySql
do command.AddTypedParameter<int32> (nameof id, id)
do! command.ExecuteNonQueryAsync token |> Async.AwaitTask |> Async.Ignore
finally semaphore.Release () |> ignore
}
/// Adds a new file entry to the database. The id of the given file
/// entry is ignored and a new file entry with the correct id is returned.
member _.AddFile ({ DirectoryId = directoryId; Name = name; Length = length; Hash = hash } as fileEntry) = async {
let! token = Async.CancellationToken
do! semaphore.WaitAsync token |> Async.AwaitTask
try use command = connection.CreateCommand ()
do command.CommandText <- InsertFileSql
do command.AddTypedParameter (nameof directoryId, directoryId)
do command.AddTypedParameter (nameof name, name)
do command.AddTypedParameter (nameof length, length)
do command.AddTypedParameter (nameof hash, hash)
use! reader = command.ExecuteReaderAsync token |> Async.AwaitTask
match! reader.ReadAsync token |> Async.AwaitTask with
| true ->
return { fileEntry with Id = reader.GetInt32 0 }
| false ->
do logger.Error ("Could not add file entry with directory id {directoryId} and name {name}, no id returned", directoryId, name)
return failwithf "Could not add file entry with directory id %d and name %s, no id returned" directoryId name
finally semaphore.Release () |> ignore
}
/// Returns a file entry with the given id. If the file entry does
/// not exist, an exception is raised.
member this.GetFileById id = async {
let! token = Async.CancellationToken
do! semaphore.WaitAsync token |> Async.AwaitTask
try use command = connection.CreateCommand ()
do command.CommandText <- SelectFileByIdSql
do command.AddTypedParameter<int32> (nameof id, id)
use! reader = command.ExecuteReaderAsync token |> Async.AwaitTask
match! reader.ReadAsync token |> Async.AwaitTask with
| true ->
return this.ReadFile reader
| false ->
do logger.Error ("Could not get file entry with id {id}", id)
return failwithf "Could not get file entry with id %d" id
finally semaphore.Release () |> ignore
}
/// Returns all file entries that are in the given directory id.
member this.GetFilesByDirectoryId directoryId = asyncSeq {
let! token = Async.CancellationToken
do! semaphore.WaitAsync token |> Async.AwaitTask
try use command = connection.CreateCommand ()
do command.CommandText <- SelectFilesByDirectoryIdSql
do command.AddTypedParameter<int32> (nameof directoryId, directoryId)
use! reader = command.ExecuteReaderAsync token |> Async.AwaitTask
while reader.ReadAsync token |> Async.AwaitTask do
yield this.ReadFile reader
finally semaphore.Release () |> ignore
}
/// Returns all file entries that have duplicate hashes.
member this.GetDuplicateFiles () = asyncSeq {
let! token = Async.CancellationToken
do! semaphore.WaitAsync token |> Async.AwaitTask
try use command = connection.CreateCommand ()
do command.CommandText <- SelectDuplicateFilesSql
use! reader = command.ExecuteReaderAsync token |> Async.AwaitTask
while reader.ReadAsync token |> Async.AwaitTask do
yield this.ReadFile reader
finally semaphore.Release () |> ignore
}
/// Removes the file entry with the given id.
member _.RemoveFile id = async {
let! token = Async.CancellationToken
do! semaphore.WaitAsync token |> Async.AwaitTask
try use command = connection.CreateCommand ()
do command.CommandText <- DeleteFileSql
do command.AddTypedParameter<int32> (nameof id, id)
do! command.ExecuteNonQueryAsync token |> Async.AwaitTask |> Async.Ignore
finally semaphore.Release () |> ignore
}
interface IDisposable with
/// Closes the database connection and cleans up resources.
member _.Dispose () =
logger.Debug "Closing the database connection"
using connection ignore
using semaphore ignore