namespace BitBadger.Documents.Sqlite
open BitBadger.Documents
open Microsoft.Data.Sqlite
/// Configuration for document handling
module Configuration =
/// The connection string to use for query execution
let mutable internal connectionString: string option = None
/// Register a connection string to use for query execution
/// The connection string to use for connections from this library
/// This also enables foreign keys
[]
let useConnectionString connStr =
let builder = SqliteConnectionStringBuilder connStr
builder.ForeignKeys <- Option.toNullable (Some true)
connectionString <- Some (string builder)
/// Retrieve a new connection using currently configured connection string
/// A new database connection
/// If no data source has been configured
/// If the connection cannot be opened
[]
let dbConn () =
match connectionString with
| Some connStr ->
let conn = new SqliteConnection(connStr)
conn.Open()
conn
| None -> invalidOp "Please provide a connection string before attempting data access"
/// Query definitions
[]
module Query =
///
/// Create a WHERE clause fragment to implement a comparison on fields in a JSON document
///
/// How the fields should be matched
/// The fields for the comparisons
/// A WHERE clause implementing the comparisons for the given fields
[]
let whereByFields (howMatched: FieldMatch) fields =
let name = ParameterName()
fields
|> Seq.map (fun it ->
match it.Comparison with
| Exists | NotExists -> $"{it.Path SQLite AsSql} {it.Comparison.OpSql}"
| Between _ ->
let p = name.Derive it.ParameterName
$"{it.Path SQLite AsSql} {it.Comparison.OpSql} {p}min AND {p}max"
| In values ->
let p = name.Derive it.ParameterName
let paramNames = values |> Seq.mapi (fun idx _ -> $"{p}_{idx}") |> String.concat ", "
$"{it.Path SQLite AsSql} {it.Comparison.OpSql} ({paramNames})"
| InArray (table, values) ->
let p = name.Derive it.ParameterName
let paramNames = values |> Seq.mapi (fun idx _ -> $"{p}_{idx}") |> String.concat ", "
$"EXISTS (SELECT 1 FROM json_each({table}.data, '$.{it.Name}') WHERE value IN ({paramNames}))"
| _ -> $"{it.Path SQLite AsSql} {it.Comparison.OpSql} {name.Derive it.ParameterName}")
|> String.concat $" {howMatched} "
/// Create a WHERE clause fragment to implement an ID-based query
/// The ID of the document
/// A WHERE clause fragment identifying a document by its ID
[]
let whereById (docId: 'TKey) =
whereByFields Any [ { Field.Equal (Configuration.idField ()) docId with ParameterName = Some "@id" } ]
/// Create an UPDATE statement to patch documents
/// The table to be updated
/// A query to patch documents
[]
let patch tableName =
$"UPDATE %s{tableName} SET data = json_patch(data, json(@data))"
/// Create an UPDATE statement to remove fields from documents
/// The table to be updated
/// The parameters with the field names to be removed
/// A query to remove fields from documents
[]
let removeFields tableName (parameters: SqliteParameter seq) =
let paramNames = parameters |> Seq.map _.ParameterName |> String.concat ", "
$"UPDATE %s{tableName} SET data = json_remove(data, {paramNames})"
/// Create a query by a document's ID
/// The SQL statement to be run against a document by its ID
/// The ID of the document targeted
/// A query addressing a document by its ID
[]
let byId<'TKey> statement (docId: 'TKey) =
Query.statementWhere
statement
(whereByFields Any [ { Field.Equal (Configuration.idField ()) docId with ParameterName = Some "@id" } ])
/// Create a query on JSON fields
/// The SQL statement to be run against matching fields
/// Whether to match any or all of the field conditions
/// The field conditions to be matched
/// A query addressing documents by field matching conditions
[]
let byFields statement howMatched fields =
Query.statementWhere statement (whereByFields howMatched fields)
/// Data definition
module Definition =
/// SQL statement to create a document table
/// The name of the table (may include schema)
/// A query to create the table if it does not exist
[]
let ensureTable name =
Query.Definition.ensureTableFor name "TEXT"
/// Parameter handling helpers
[]
module Parameters =
/// Create an ID parameter (name "@id")
/// The key value for the ID parameter
/// The name and parameter value for the ID
[]
let idParam (key: 'TKey) =
SqliteParameter("@id", string key)
/// Create a parameter with a JSON value
/// The name of the parameter to create
/// The criteria to provide as JSON
/// The name and parameter value for the JSON field
[]
let jsonParam name (it: 'TJson) =
SqliteParameter(name, Configuration.serializer().Serialize it)
/// Create JSON field parameters
/// The Fields to convert to parameters
/// The current parameters for the query
/// A unified sequence of parameter names and values
[]
let addFieldParams fields parameters =
let name = ParameterName()
fields
|> Seq.map (fun it ->
seq {
match it.Comparison with
| Exists | NotExists -> ()
| Between (min, max) ->
let p = name.Derive it.ParameterName
yield! [ SqliteParameter($"{p}min", min); SqliteParameter($"{p}max", max) ]
| In values | InArray (_, values) ->
let p = name.Derive it.ParameterName
yield! values |> Seq.mapi (fun idx v -> SqliteParameter($"{p}_{idx}", v))
| Equal v | Greater v | GreaterOrEqual v | Less v | LessOrEqual v | NotEqual v ->
yield SqliteParameter(name.Derive it.ParameterName, v) })
|> Seq.collect id
|> Seq.append parameters
|> Seq.toList
|> Seq.ofList
/// Create a JSON field parameter (name "@field")
[]
[]
let addFieldParam name field parameters =
addFieldParams [ { field with ParameterName = Some name } ] parameters
/// Append JSON field name parameters for the given field names to the given parameters
/// The name of the parameter to use for each field
/// The names of fields to be addressed
/// The name (@name) and parameter value for the field names
[]
let fieldNameParams paramName fieldNames =
fieldNames
|> Seq.mapi (fun idx name -> SqliteParameter($"%s{paramName}{idx}", $"$.%s{name}"))
|> Seq.toList
|> Seq.ofList
/// An empty parameter sequence
[]
let noParams =
Seq.empty
/// Helper functions for handling results
[]
module Results =
/// Create a domain item from a document, specifying the field in which the document is found
/// The field name containing the JSON document
/// A SqliteDataReader set to the row with the document to be constructed
/// The constructed domain item
[]
let fromDocument<'TDoc> field (rdr: SqliteDataReader) : 'TDoc =
Configuration.serializer().Deserialize<'TDoc>(rdr.GetString(rdr.GetOrdinal field))
/// Create a domain item from a document
/// A SqliteDataReader set to the row with the document to be constructed
/// The constructed domain item
[]
let fromData<'TDoc> rdr =
fromDocument<'TDoc> "data" rdr
///
/// Create a list of items for the results of the given command, using the specified mapping function
///
/// The command to execute
/// The mapping function from data reader to domain class instance
/// A list of items from the reader
[]
let toCustomList<'TDoc> (cmd: SqliteCommand) (mapFunc: SqliteDataReader -> 'TDoc) = backgroundTask {
use! rdr = cmd.ExecuteReaderAsync()
let mutable it = Seq.empty<'TDoc>
while! rdr.ReadAsync() do
it <- Seq.append it (Seq.singleton (mapFunc rdr))
return List.ofSeq it
}
///
/// Create a list of items for the results of the given command, using the specified mapping function
///
/// The command to execute
/// The mapping function from data reader to domain class instance
/// A list of items from the reader
let ToCustomList<'TDoc>(cmd: SqliteCommand, mapFunc: System.Func) = backgroundTask {
use! rdr = cmd.ExecuteReaderAsync()
let it = ResizeArray<'TDoc>()
while! rdr.ReadAsync() do
it.Add(mapFunc.Invoke rdr)
return it
}
/// Extract a count from the first column
/// A SqliteDataReader set to the row with the count to retrieve
/// The count from the row
[]
let toCount (rdr: SqliteDataReader) =
rdr.GetInt64 0
/// Extract a true/false value from the first column
/// A SqliteDataReader set to the row with the true/false value to retrieve
/// The true/false value from the row
/// SQLite implements boolean as 1 = true, 0 = false
[]
let toExists rdr =
toCount rdr > 0L
[]
module internal Helpers =
/// Execute a non-query command
/// The command to be executed
let internal write (cmd: SqliteCommand) = backgroundTask {
let! _ = cmd.ExecuteNonQueryAsync()
()
}
/// Versions of queries that accept a SqliteConnection as the last parameter
module WithConn =
/// Commands to execute custom SQL queries
[]
module Custom =
/// Execute a query that returns a list of results
/// The query to retrieve the results
/// Parameters to use for the query
/// The mapping function between the document and the domain item
/// The SqliteConnection to use to execute the query
/// A list of results for the given query
[]
let list<'TDoc> query (parameters: SqliteParameter seq) (mapFunc: SqliteDataReader -> 'TDoc)
(conn: SqliteConnection) =
use cmd = conn.CreateCommand()
cmd.CommandText <- query
cmd.Parameters.AddRange parameters
toCustomList<'TDoc> cmd mapFunc
/// Execute a query that returns a list of results
/// The query to retrieve the results
/// Parameters to use for the query
/// The mapping function between the document and the domain item
/// The SqliteConnection to use to execute the query
/// A list of results for the given query
let List<'TDoc>(
query, parameters: SqliteParameter seq, mapFunc: System.Func,
conn: SqliteConnection
) =
use cmd = conn.CreateCommand()
cmd.CommandText <- query
cmd.Parameters.AddRange parameters
ToCustomList<'TDoc>(cmd, mapFunc)
/// Execute a query that returns one or no results
/// The query to retrieve the results
/// Parameters to use for the query
/// The mapping function between the document and the domain item
/// The SqliteConnection to use to execute the query
/// Some with the first matching result, or None if not found
[]
let single<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) conn = backgroundTask {
let! results = list query parameters mapFunc conn
return FSharp.Collections.List.tryHead results
}
/// Execute a query that returns one or no results
/// The query to retrieve the results
/// Parameters to use for the query
/// The mapping function between the document and the domain item
/// The SqliteConnection to use to execute the query
/// The first matching result, or null if not found
let Single<'TDoc when 'TDoc: null and 'TDoc: not struct>(
query, parameters, mapFunc: System.Func, conn
) = backgroundTask {
let! result = single<'TDoc> query parameters mapFunc.Invoke conn
return Option.toObj result
}
/// Execute a query that returns no results
/// The query to retrieve the results
/// Parameters to use for the query
/// The SqliteConnection to use to execute the query
[]
let nonQuery query (parameters: SqliteParameter seq) (conn: SqliteConnection) =
use cmd = conn.CreateCommand()
cmd.CommandText <- query
cmd.Parameters.AddRange parameters
write cmd
/// Execute a query that returns a scalar value
/// The query to retrieve the value
/// Parameters to use for the query
/// The mapping function to obtain the value
/// The SqliteConnection to use to execute the query
/// The scalar value for the query
[]
let scalar<'T when 'T : struct> query (parameters: SqliteParameter seq) (mapFunc: SqliteDataReader -> 'T)
(conn: SqliteConnection) = backgroundTask {
use cmd = conn.CreateCommand()
cmd.CommandText <- query
cmd.Parameters.AddRange parameters
use! rdr = cmd.ExecuteReaderAsync()
let! isFound = rdr.ReadAsync()
return if isFound then mapFunc rdr else Unchecked.defaultof<'T>
}
/// Execute a query that returns a scalar value
/// The query to retrieve the value
/// Parameters to use for the query
/// The mapping function to obtain the value
/// The SqliteConnection to use to execute the query
/// The scalar value for the query
let Scalar<'T when 'T: struct>(query, parameters, mapFunc: System.Func, conn) =
scalar<'T> query parameters mapFunc.Invoke conn
/// Functions to create tables and indexes
[]
module Definition =
/// Create a document table
/// The table whose existence should be ensured (may include schema)
/// The SqliteConnection to use to execute the query
[]
let ensureTable name conn = backgroundTask {
do! Custom.nonQuery (Query.Definition.ensureTable name) [] conn
do! Custom.nonQuery (Query.Definition.ensureKey name SQLite) [] conn
}
/// Create an index on field(s) within documents in the specified table
/// The table to be indexed (may include schema)
/// The name of the index to create
/// One or more fields to be indexed
/// The SqliteConnection to use to execute the query
[]
let ensureFieldIndex tableName indexName fields conn =
Custom.nonQuery (Query.Definition.ensureIndexOn tableName indexName fields SQLite) [] conn
/// Commands to add documents
[]
module Document =
/// Insert a new document
/// The table into which the document should be inserted (may include schema)
/// The document to be inserted
/// The SqliteConnection to use to execute the query
[]
let insert<'TDoc> tableName (document: 'TDoc) conn =
let query =
match Configuration.autoIdStrategy () with
| Disabled -> Query.insert tableName
| strategy ->
let idField = Configuration.idField ()
let dataParam =
if AutoId.NeedsAutoId strategy document idField then
match strategy with
| Number -> $"(SELECT coalesce(max(data->>'{idField}'), 0) + 1 FROM {tableName})"
| Guid -> $"'{AutoId.GenerateGuid()}'"
| RandomString -> $"'{AutoId.GenerateRandomString(Configuration.idStringLength ())}'"
| Disabled -> "@data"
|> function it -> $"json_set(@data, '$.{idField}', {it})"
else "@data"
(Query.insert tableName).Replace("@data", dataParam)
Custom.nonQuery query [ jsonParam "@data" document ] conn
///
/// Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
///
/// The table into which the document should be saved (may include schema)
/// The document to be saved
/// The SqliteConnection to use to execute the query
[]
let save<'TDoc> tableName (document: 'TDoc) conn =
Custom.nonQuery (Query.save tableName) [ jsonParam "@data" document ] conn
/// Commands to count documents
[]
module Count =
/// Count all documents in a table
/// The table in which documents should be counted (may include schema)
/// The SqliteConnection to use to execute the query
/// The count of the documents in the table
[]
let all tableName conn =
Custom.scalar (Query.count tableName) [] toCount conn
/// Count matching documents using JSON field comparisons (->> =, etc.)
/// The table in which documents should be counted (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// The SqliteConnection to use to execute the query
/// The count of matching documents in the table
[]
let byFields tableName howMatched fields conn =
Custom.scalar
(Query.byFields (Query.count tableName) howMatched fields) (addFieldParams fields []) toCount conn
/// Commands to determine if documents exist
[]
module Exists =
/// Determine if a document exists for the given ID
/// The table in which existence should be checked (may include schema)
/// The ID of the document whose existence should be checked
/// The SqliteConnection to use to execute the query
/// True if a document exists, false if not
[]
let byId tableName (docId: 'TKey) conn =
Custom.scalar (Query.exists tableName (Query.whereById docId)) [ idParam docId ] toExists conn
/// Determine if a document exists using JSON field comparisons (->> =, etc.)
/// The table in which existence should be checked (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// The SqliteConnection to use to execute the query
/// True if any matching documents exist, false if not
[]
let byFields tableName howMatched fields conn =
Custom.scalar
(Query.exists tableName (Query.whereByFields howMatched fields))
(addFieldParams fields [])
toExists
conn
/// Commands to retrieve documents
[]
module Find =
/// Retrieve all documents in the given table
/// The table from which documents should be retrieved (may include schema)
/// The SqliteConnection to use to execute the query
/// All documents from the given table
[]
let all<'TDoc> tableName conn =
Custom.list<'TDoc> (Query.find tableName) [] fromData<'TDoc> conn
/// Retrieve all documents in the given table
/// The table from which documents should be retrieved (may include schema)
/// The SqliteConnection to use to execute the query
/// All documents from the given table
let All<'TDoc>(tableName, conn) =
Custom.List(Query.find tableName, [], fromData<'TDoc>, conn)
/// Retrieve all documents in the given table ordered by the given fields in the document
/// The table from which documents should be retrieved (may include schema)
/// Fields by which the results should be ordered
/// The SqliteConnection to use to execute the query
/// All documents from the given table, ordered by the given fields
[]
let allOrdered<'TDoc> tableName orderFields conn =
Custom.list<'TDoc> (Query.find tableName + Query.orderBy orderFields SQLite) [] fromData<'TDoc> conn
/// Retrieve all documents in the given table ordered by the given fields in the document
/// The table from which documents should be retrieved (may include schema)
/// Fields by which the results should be ordered
/// The SqliteConnection to use to execute the query
/// All documents from the given table, ordered by the given fields
let AllOrdered<'TDoc>(tableName, orderFields, conn) =
Custom.List(Query.find tableName + Query.orderBy orderFields SQLite, [], fromData<'TDoc>, conn)
/// Retrieve a document by its ID
/// The table from which a document should be retrieved (may include schema)
/// The ID of the document to retrieve
/// The SqliteConnection to use to execute the query
/// Some with the document if found, None otherwise
[]
let byId<'TKey, 'TDoc> tableName (docId: 'TKey) conn =
Custom.single<'TDoc> (Query.byId (Query.find tableName) docId) [ idParam docId ] fromData<'TDoc> conn
/// Retrieve a document by its ID
/// The table from which a document should be retrieved (may include schema)
/// The ID of the document to retrieve
/// The SqliteConnection to use to execute the query
/// The document if found, null otherwise
let ById<'TKey, 'TDoc when 'TDoc: null and 'TDoc: not struct>(tableName, docId: 'TKey, conn) =
Custom.Single<'TDoc>(Query.byId (Query.find tableName) docId, [ idParam docId ], fromData<'TDoc>, conn)
/// Retrieve documents matching JSON field comparisons (->> =, etc.)
/// The table from which documents should be retrieved (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// The SqliteConnection to use to execute the query
/// All documents matching the given fields
[]
let byFields<'TDoc> tableName howMatched fields conn =
Custom.list<'TDoc>
(Query.byFields (Query.find tableName) howMatched fields)
(addFieldParams fields [])
fromData<'TDoc>
conn
/// Retrieve documents matching JSON field comparisons (->> =, etc.)
/// The table from which documents should be retrieved (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// The SqliteConnection to use to execute the query
/// All documents matching the given fields
let ByFields<'TDoc>(tableName, howMatched, fields, conn) =
Custom.List<'TDoc>(
Query.byFields (Query.find tableName) howMatched fields,
addFieldParams fields [],
fromData<'TDoc>,
conn)
///
/// Retrieve documents matching JSON field comparisons (->> =, etc.) ordered by the given fields
/// in the document
///
/// The table from which documents should be retrieved (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// Fields by which the results should be ordered
/// The SqliteConnection to use to execute the query
/// All documents matching the given fields, ordered by the other given fields
[]
let byFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields conn =
Custom.list<'TDoc>
(Query.byFields (Query.find tableName) howMatched queryFields + Query.orderBy orderFields SQLite)
(addFieldParams queryFields [])
fromData<'TDoc>
conn
///
/// Retrieve documents matching JSON field comparisons (->> =, etc.) ordered by the given fields
/// in the document
///
/// The table from which documents should be retrieved (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// Fields by which the results should be ordered
/// The SqliteConnection to use to execute the query
/// All documents matching the given fields, ordered by the other given fields
let ByFieldsOrdered<'TDoc>(tableName, howMatched, queryFields, orderFields, conn) =
Custom.List<'TDoc>(
Query.byFields (Query.find tableName) howMatched queryFields + Query.orderBy orderFields SQLite,
addFieldParams queryFields [],
fromData<'TDoc>,
conn)
/// Retrieve the first document matching JSON field comparisons (->> =, etc.)
/// The table from which a document should be retrieved (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// The SqliteConnection to use to execute the query
/// Some with the first document, or None if not found
[]
let firstByFields<'TDoc> tableName howMatched fields conn =
Custom.single
$"{Query.byFields (Query.find tableName) howMatched fields} LIMIT 1"
(addFieldParams fields [])
fromData<'TDoc>
conn
/// Retrieve the first document matching JSON field comparisons (->> =, etc.)
/// The table from which a document should be retrieved (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// The SqliteConnection to use to execute the query
/// The first document, or null if not found
let FirstByFields<'TDoc when 'TDoc: null and 'TDoc: not struct>(tableName, howMatched, fields, conn) =
Custom.Single(
$"{Query.byFields (Query.find tableName) howMatched fields} LIMIT 1",
addFieldParams fields [],
fromData<'TDoc>,
conn)
///
/// Retrieve the first document matching JSON field comparisons (->> =, etc.) ordered by the
/// given fields in the document
///
/// The table from which a document should be retrieved (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// Fields by which the results should be ordered
/// The SqliteConnection to use to execute the query
///
/// Some with the first document ordered by the given fields, or None if not found
///
[]
let firstByFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields conn =
Custom.single
$"{Query.byFields (Query.find tableName) howMatched queryFields}{Query.orderBy orderFields SQLite} LIMIT 1"
(addFieldParams queryFields [])
fromData<'TDoc>
conn
///
/// Retrieve the first document matching JSON field comparisons (->> =, etc.) ordered by the
/// given fields in the document
///
/// The table from which a document should be retrieved (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// Fields by which the results should be ordered
/// The SqliteConnection to use to execute the query
/// The first document ordered by the given fields, or null if not found
let FirstByFieldsOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>(
tableName, howMatched, queryFields, orderFields, conn) =
Custom.Single(
$"{Query.byFields (Query.find tableName) howMatched queryFields}{Query.orderBy orderFields SQLite} LIMIT 1",
addFieldParams queryFields [],
fromData<'TDoc>,
conn)
/// Commands to update documents
[]
module Update =
/// Update (replace) an entire document by its ID
/// The table in which a document should be updated (may include schema)
/// The ID of the document to be updated (replaced)
/// The new document
/// The SqliteConnection to use to execute the query
[]
let byId tableName (docId: 'TKey) (document: 'TDoc) conn =
Custom.nonQuery
(Query.statementWhere (Query.update tableName) (Query.whereById docId))
[ idParam docId; jsonParam "@data" document ]
conn
///
/// Update (replace) an entire document by its ID, using the provided function to obtain the ID from the
/// document
///
/// The table in which a document should be updated (may include schema)
/// The function to obtain the ID of the document
/// The new document
/// The SqliteConnection to use to execute the query
[]
let byFunc tableName (idFunc: 'TDoc -> 'TKey) (document: 'TDoc) conn =
byId tableName (idFunc document) document conn
///
/// Update (replace) an entire document by its ID, using the provided function to obtain the ID from the
/// document
///
/// The table in which a document should be updated (may include schema)
/// The function to obtain the ID of the document
/// The new document
/// The SqliteConnection to use to execute the query
let ByFunc(tableName, idFunc: System.Func<'TDoc, 'TKey>, document: 'TDoc, conn) =
byFunc tableName idFunc.Invoke document conn
/// Commands to patch (partially update) documents
[]
module Patch =
/// Patch a document by its ID
/// The table in which a document should be patched (may include schema)
/// The ID of the document to patch
/// The partial document to patch the existing document
/// The SqliteConnection to use to execute the query
[]
let byId tableName (docId: 'TKey) (patch: 'TPatch) conn =
Custom.nonQuery
(Query.byId (Query.patch tableName) docId) [ idParam docId; jsonParam "@data" patch ] conn
///
/// Patch documents using a JSON field comparison query in the WHERE clause (->> =,
/// etc.)
///
/// The table in which documents should be patched (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// The partial document to patch the existing document
/// The SqliteConnection to use to execute the query
[]
let byFields tableName howMatched fields (patch: 'TPatch) conn =
Custom.nonQuery
(Query.byFields (Query.patch tableName) howMatched fields)
(addFieldParams fields [ jsonParam "@data" patch ])
conn
/// Commands to remove fields from documents
[]
module RemoveFields =
/// Remove fields from a document by the document's ID
/// The table in which a document should be modified (may include schema)
/// The ID of the document to modify
/// One or more field names to remove from the document
/// The SqliteConnection to use to execute the query
[]
let byId tableName (docId: 'TKey) fieldNames conn =
let nameParams = fieldNameParams "@name" fieldNames
Custom.nonQuery
(Query.byId (Query.removeFields tableName nameParams) docId)
(idParam docId |> Seq.singleton |> Seq.append nameParams)
conn
/// Remove fields from documents via a comparison on JSON fields in the document
/// The table in which documents should be modified (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// One or more field names to remove from the matching documents
/// The SqliteConnection to use to execute the query
[]
let byFields tableName howMatched fields fieldNames conn =
let nameParams = fieldNameParams "@name" fieldNames
Custom.nonQuery
(Query.byFields (Query.removeFields tableName nameParams) howMatched fields)
(addFieldParams fields nameParams)
conn
/// Commands to delete documents
[]
module Delete =
/// Delete a document by its ID
/// The table in which a document should be deleted (may include schema)
/// The ID of the document to delete
/// The SqliteConnection to use to execute the query
[]
let byId tableName (docId: 'TKey) conn =
Custom.nonQuery (Query.byId (Query.delete tableName) docId) [ idParam docId ] conn
/// Delete documents by matching a JSON field comparison query (->> =, etc.)
/// The table in which documents should be deleted (may include schema)
/// Whether to match any or all of the field conditions
/// The field conditions to match
/// The SqliteConnection to use to execute the query
[]
let byFields tableName howMatched fields conn =
Custom.nonQuery (Query.byFields (Query.delete tableName) howMatched fields) (addFieldParams fields []) conn
/// Commands to execute custom SQL queries
[]
module Custom =
/// Execute a query that returns a list of results
/// The query to retrieve the results
/// Parameters to use for the query
/// The mapping function between the document and the domain item
/// A list of results for the given query
[]
let list<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Custom.list<'TDoc> query parameters mapFunc conn
/// Execute a query that returns a list of results
/// The query to retrieve the results
/// Parameters to use for the query
/// The mapping function between the document and the domain item
/// A list of results for the given query
let List<'TDoc>(query, parameters, mapFunc: System.Func) =
use conn = Configuration.dbConn ()
WithConn.Custom.List<'TDoc>(query, parameters, mapFunc, conn)
/// Execute a query that returns one or no results
/// The query to retrieve the results
/// Parameters to use for the query
/// The mapping function between the document and the domain item
/// Some with the first matching result, or None if not found
[]
let single<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Custom.single<'TDoc> query parameters mapFunc conn
/// Execute a query that returns one or no results
/// The query to retrieve the results
/// Parameters to use for the query
/// The mapping function between the document and the domain item
/// The first matching result, or null if not found
let Single<'TDoc when 'TDoc: null and 'TDoc: not struct>(
query, parameters, mapFunc: System.Func) =
use conn = Configuration.dbConn ()
WithConn.Custom.Single<'TDoc>(query, parameters, mapFunc, conn)
/// Execute a query that returns no results
/// The query to retrieve the results
/// Parameters to use for the query
[]
let nonQuery query parameters =
use conn = Configuration.dbConn ()
WithConn.Custom.nonQuery query parameters conn
/// Execute a query that returns a scalar value
/// The query to retrieve the value
/// Parameters to use for the query
/// The mapping function to obtain the value
/// The scalar value for the query
[]
let scalar<'T when 'T: struct> query parameters (mapFunc: SqliteDataReader -> 'T) =
use conn = Configuration.dbConn ()
WithConn.Custom.scalar<'T> query parameters mapFunc conn
/// Execute a query that returns a scalar value
/// The query to retrieve the value
/// Parameters to use for the query
/// The mapping function to obtain the value
/// The scalar value for the query
let Scalar<'T when 'T: struct>(query, parameters, mapFunc: System.Func) =
use conn = Configuration.dbConn ()
WithConn.Custom.Scalar<'T>(query, parameters, mapFunc, conn)
/// Functions to create tables and indexes
[]
module Definition =
/// Create a document table
[]
let ensureTable name =
use conn = Configuration.dbConn ()
WithConn.Definition.ensureTable name conn
/// Create an index on a document table
[]
let ensureFieldIndex tableName indexName fields =
use conn = Configuration.dbConn ()
WithConn.Definition.ensureFieldIndex tableName indexName fields conn
/// Document insert/save functions
[]
module Document =
/// Insert a new document
[]
let insert<'TDoc> tableName (document: 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Document.insert tableName document conn
/// Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
[]
let save<'TDoc> tableName (document: 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Document.save tableName document conn
/// Commands to count documents
[]
module Count =
/// Count all documents in a table
[]
let all tableName =
use conn = Configuration.dbConn ()
WithConn.Count.all tableName conn
/// Count matching documents using a comparison on JSON fields
[]
let byFields tableName howMatched fields =
use conn = Configuration.dbConn ()
WithConn.Count.byFields tableName howMatched fields conn
/// Commands to determine if documents exist
[]
module Exists =
/// Determine if a document exists for the given ID
[]
let byId tableName (docId: 'TKey) =
use conn = Configuration.dbConn ()
WithConn.Exists.byId tableName docId conn
/// Determine if a document exists using a comparison on JSON fields
[]
let byFields tableName howMatched fields =
use conn = Configuration.dbConn ()
WithConn.Exists.byFields tableName howMatched fields conn
/// Commands to determine if documents exist
[]
module Find =
/// Retrieve all documents in the given table
[]
let all<'TDoc> tableName =
use conn = Configuration.dbConn ()
WithConn.Find.all<'TDoc> tableName conn
/// Retrieve all documents in the given table
let All<'TDoc> tableName =
use conn = Configuration.dbConn ()
WithConn.Find.All<'TDoc>(tableName, conn)
/// Retrieve all documents in the given table ordered by the given fields in the document
[]
let allOrdered<'TDoc> tableName orderFields =
use conn = Configuration.dbConn ()
WithConn.Find.allOrdered<'TDoc> tableName orderFields conn
/// Retrieve all documents in the given table ordered by the given fields in the document
let AllOrdered<'TDoc> tableName orderFields =
use conn = Configuration.dbConn ()
WithConn.Find.AllOrdered<'TDoc>(tableName, orderFields, conn)
/// Retrieve a document by its ID (returns None if not found)
[]
let byId<'TKey, 'TDoc> tableName docId =
use conn = Configuration.dbConn ()
WithConn.Find.byId<'TKey, 'TDoc> tableName docId conn
/// Retrieve a document by its ID (returns null if not found)
let ById<'TKey, 'TDoc when 'TDoc: null and 'TDoc: not struct>(tableName, docId) =
use conn = Configuration.dbConn ()
WithConn.Find.ById<'TKey, 'TDoc>(tableName, docId, conn)
/// Retrieve documents via a comparison on JSON fields
[]
let byFields<'TDoc> tableName howMatched fields =
use conn = Configuration.dbConn ()
WithConn.Find.byFields<'TDoc> tableName howMatched fields conn
/// Retrieve documents via a comparison on JSON fields
let ByFields<'TDoc>(tableName, howMatched, fields) =
use conn = Configuration.dbConn ()
WithConn.Find.ByFields<'TDoc>(tableName, howMatched, fields, conn)
/// Retrieve documents via a comparison on JSON fields ordered by the given fields in the document
[]
let byFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields =
use conn = Configuration.dbConn ()
WithConn.Find.byFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields conn
/// Retrieve documents via a comparison on JSON fields ordered by the given fields in the document
let ByFieldsOrdered<'TDoc>(tableName, howMatched, queryFields, orderFields) =
use conn = Configuration.dbConn ()
WithConn.Find.ByFieldsOrdered<'TDoc>(tableName, howMatched, queryFields, orderFields, conn)
/// Retrieve documents via a comparison on JSON fields, returning only the first result
[]
let firstByFields<'TDoc> tableName howMatched fields =
use conn = Configuration.dbConn ()
WithConn.Find.firstByFields<'TDoc> tableName howMatched fields conn
/// Retrieve documents via a comparison on JSON fields, returning only the first result
let FirstByFields<'TDoc when 'TDoc: null and 'TDoc: not struct>(tableName, howMatched, fields) =
use conn = Configuration.dbConn ()
WithConn.Find.FirstByFields<'TDoc>(tableName, howMatched, fields, conn)
/// Retrieve documents via a comparison on JSON fields ordered by the given fields in the document, returning only
/// the first result
[]
let firstByFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields =
use conn = Configuration.dbConn ()
WithConn.Find.firstByFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields conn
/// Retrieve documents via a comparison on JSON fields ordered by the given fields in the document, returning only
/// the first result
let FirstByFieldsOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>(
tableName, howMatched, queryFields, orderFields) =
use conn = Configuration.dbConn ()
WithConn.Find.FirstByFieldsOrdered<'TDoc>(tableName, howMatched, queryFields, orderFields, conn)
/// Commands to update documents
[]
module Update =
/// Update an entire document by its ID
[]
let byId tableName (docId: 'TKey) (document: 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Update.byId tableName docId document conn
/// Update an entire document by its ID, using the provided function to obtain the ID from the document
[]
let byFunc tableName (idFunc: 'TDoc -> 'TKey) (document: 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Update.byFunc tableName idFunc document conn
/// Update an entire document by its ID, using the provided function to obtain the ID from the document
let ByFunc(tableName, idFunc: System.Func<'TDoc, 'TKey>, document: 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Update.ByFunc(tableName, idFunc, document, conn)
/// Commands to patch (partially update) documents
[]
module Patch =
/// Patch a document by its ID
[]
let byId tableName (docId: 'TKey) (patch: 'TPatch) =
use conn = Configuration.dbConn ()
WithConn.Patch.byId tableName docId patch conn
/// Patch documents using a comparison on JSON fields in the WHERE clause
[]
let byFields tableName howMatched fields (patch: 'TPatch) =
use conn = Configuration.dbConn ()
WithConn.Patch.byFields tableName howMatched fields patch conn
/// Commands to remove fields from documents
[]
module RemoveFields =
/// Remove fields from a document by the document's ID
[]
let byId tableName (docId: 'TKey) fieldNames =
use conn = Configuration.dbConn ()
WithConn.RemoveFields.byId tableName docId fieldNames conn
/// Remove field from documents via a comparison on JSON fields in the document
[]
let byFields tableName howMatched fields fieldNames =
use conn = Configuration.dbConn ()
WithConn.RemoveFields.byFields tableName howMatched fields fieldNames conn
/// Commands to delete documents
[]
module Delete =
/// Delete a document by its ID
[]
let byId tableName (docId: 'TKey) =
use conn = Configuration.dbConn ()
WithConn.Delete.byId tableName docId conn
/// Delete documents by matching a comparison on JSON fields
[]
let byFields tableName howMatched fields =
use conn = Configuration.dbConn ()
WithConn.Delete.byFields tableName howMatched fields conn