WIP on docs; finish PG, half thru SQLite

This commit is contained in:
Daniel J. Summers 2024-12-27 22:41:32 -05:00
parent 5f3f84d607
commit f40c93ee66
5 changed files with 752 additions and 259 deletions

View File

@ -4,7 +4,7 @@ open Npgsql
open Npgsql.FSharp open Npgsql.FSharp
open WithProps open WithProps
/// F# Extensions for the NpgsqlConnection type /// <summary>F# Extensions for the NpgsqlConnection type</summary>
[<AutoOpen>] [<AutoOpen>]
module Extensions = module Extensions =
@ -377,247 +377,455 @@ module Extensions =
open System.Runtime.CompilerServices open System.Runtime.CompilerServices
/// C# extensions on the NpgsqlConnection type /// <summary>C# extensions on the NpgsqlConnection type</summary>
type NpgsqlConnectionCSharpExtensions = type NpgsqlConnectionCSharpExtensions =
/// Execute a query that returns a list of results /// <summary>Execute a query that returns a list of results</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function between the document and the domain item</param>
/// <returns>A list of results for the given query</returns>
[<Extension>] [<Extension>]
static member inline CustomList<'TDoc>(conn, query, parameters, mapFunc: System.Func<RowReader, 'TDoc>) = static member inline CustomList<'TDoc>(conn, query, parameters, mapFunc: System.Func<RowReader, 'TDoc>) =
Custom.List<'TDoc>(query, parameters, mapFunc, Sql.existingConnection conn) Custom.List<'TDoc>(query, parameters, mapFunc, Sql.existingConnection conn)
/// Execute a query that returns one or no results; returns None if not found /// <summary>Execute a query that returns one or no results</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function between the document and the domain item</param>
/// <returns>The first matching result, or <tt>null</tt> if not found</returns>
[<Extension>] [<Extension>]
static member inline CustomSingle<'TDoc when 'TDoc: null and 'TDoc: not struct>( static member inline CustomSingle<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, query, parameters, mapFunc: System.Func<RowReader, 'TDoc>) = conn, query, parameters, mapFunc: System.Func<RowReader, 'TDoc>) =
Custom.Single<'TDoc>(query, parameters, mapFunc, Sql.existingConnection conn) Custom.Single<'TDoc>(query, parameters, mapFunc, Sql.existingConnection conn)
/// Execute a query that returns no results /// <summary>Execute a query that returns no results</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
[<Extension>] [<Extension>]
static member inline CustomNonQuery(conn, query, parameters) = static member inline CustomNonQuery(conn, query, parameters) =
Custom.nonQuery query parameters (Sql.existingConnection conn) Custom.nonQuery query parameters (Sql.existingConnection conn)
/// Execute a query that returns a scalar value /// <summary>Execute a query that returns a scalar value</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="query">The query to retrieve the value</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function to obtain the value</param>
/// <returns>The scalar value for the query</returns>
[<Extension>] [<Extension>]
static member inline CustomScalar<'T when 'T: struct>( static member inline CustomScalar<'T when 'T: struct>(
conn, query, parameters, mapFunc: System.Func<RowReader, 'T>) = conn, query, parameters, mapFunc: System.Func<RowReader, 'T>) =
Custom.Scalar(query, parameters, mapFunc, Sql.existingConnection conn) Custom.Scalar(query, parameters, mapFunc, Sql.existingConnection conn)
/// Create a document table /// <summary>Create a document table</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="name">The table whose existence should be ensured (may include schema)</param>
[<Extension>] [<Extension>]
static member inline EnsureTable(conn, name) = static member inline EnsureTable(conn, name) =
Definition.ensureTable name (Sql.existingConnection conn) Definition.ensureTable name (Sql.existingConnection conn)
/// Create an index on documents in the specified table /// <summary>Create an index on documents in the specified table</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="name">The table to be indexed (may include schema)</param>
/// <param name="idxType">The type of document index to create</param>
[<Extension>] [<Extension>]
static member inline EnsureDocumentIndex(conn, name, idxType) = static member inline EnsureDocumentIndex(conn, name, idxType) =
Definition.ensureDocumentIndex name idxType (Sql.existingConnection conn) Definition.ensureDocumentIndex name idxType (Sql.existingConnection conn)
/// Create an index on field(s) within documents in the specified table /// <summary>Create an index on field(s) within documents in the specified table</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table to be indexed (may include schema)</param>
/// <param name="indexName">The name of the index to create</param>
/// <param name="fields">One or more fields to be indexed</param>
[<Extension>] [<Extension>]
static member inline EnsureFieldIndex(conn, tableName, indexName, fields) = static member inline EnsureFieldIndex(conn, tableName, indexName, fields) =
Definition.ensureFieldIndex tableName indexName fields (Sql.existingConnection conn) Definition.ensureFieldIndex tableName indexName fields (Sql.existingConnection conn)
/// Insert a new document /// <summary>Insert a new document</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table into which the document should be inserted (may include schema)</param>
/// <param name="document">The document to be inserted</param>
[<Extension>] [<Extension>]
static member inline Insert<'TDoc>(conn, tableName, document: 'TDoc) = static member inline Insert<'TDoc>(conn, tableName, document: 'TDoc) =
insert<'TDoc> tableName document (Sql.existingConnection conn) insert<'TDoc> tableName document (Sql.existingConnection conn)
/// Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert") /// <summary>Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table into which the document should be saved (may include schema)</param>
/// <param name="document">The document to be saved</param>
[<Extension>] [<Extension>]
static member inline Save<'TDoc>(conn, tableName, document: 'TDoc) = static member inline Save<'TDoc>(conn, tableName, document: 'TDoc) =
save<'TDoc> tableName document (Sql.existingConnection conn) save<'TDoc> tableName document (Sql.existingConnection conn)
/// Count all documents in a table /// <summary>Count all documents in a table</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be counted (may include schema)</param>
/// <returns>The count of the documents in the table</returns>
[<Extension>] [<Extension>]
static member inline CountAll(conn, tableName) = static member inline CountAll(conn, tableName) =
Count.all tableName (Sql.existingConnection conn) Count.all tableName (Sql.existingConnection conn)
/// Count matching documents using a JSON field comparison query (->> =) /// <summary>Count matching documents using JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be counted (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <returns>The count of matching documents in the table</returns>
[<Extension>] [<Extension>]
static member inline CountByFields(conn, tableName, howMatched, fields) = static member inline CountByFields(conn, tableName, howMatched, fields) =
Count.byFields tableName howMatched fields (Sql.existingConnection conn) Count.byFields tableName howMatched fields (Sql.existingConnection conn)
/// Count matching documents using a JSON containment query (@>) /// <summary>Count matching documents using a JSON containment query (<tt>@&gt;</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be counted (may include schema)</param>
/// <param name="criteria">The document to match with the containment query</param>
/// <returns>The count of the documents in the table</returns>
[<Extension>] [<Extension>]
static member inline CountByContains(conn, tableName, criteria: 'TCriteria) = static member inline CountByContains(conn, tableName, criteria: 'TCriteria) =
Count.byContains tableName criteria (Sql.existingConnection conn) Count.byContains tableName criteria (Sql.existingConnection conn)
/// Count matching documents using a JSON Path match query (@?) /// <summary>Count matching documents using a JSON Path match query (<tt>@?</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be counted (may include schema)</param>
/// <param name="jsonPath">The JSON Path expression to be matched</param>
/// <returns>The count of the documents in the table</returns>
[<Extension>] [<Extension>]
static member inline CountByJsonPath(conn, tableName, jsonPath) = static member inline CountByJsonPath(conn, tableName, jsonPath) =
Count.byJsonPath tableName jsonPath (Sql.existingConnection conn) Count.byJsonPath tableName jsonPath (Sql.existingConnection conn)
/// Determine if a document exists for the given ID /// <summary>Determine if a document exists for the given ID</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which existence should be checked (may include schema)</param>
/// <param name="docId">The ID of the document whose existence should be checked</param>
/// <returns>True if a document exists, false if not</returns>
[<Extension>] [<Extension>]
static member inline ExistsById(conn, tableName, docId) = static member inline ExistsById(conn, tableName, docId) =
Exists.byId tableName docId (Sql.existingConnection conn) Exists.byId tableName docId (Sql.existingConnection conn)
/// Determine if documents exist using a JSON field comparison query (->> =) /// <summary>Determine if a document exists using JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which existence should be checked (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <returns>True if any matching documents exist, false if not</returns>
[<Extension>] [<Extension>]
static member inline ExistsByFields(conn, tableName, howMatched, fields) = static member inline ExistsByFields(conn, tableName, howMatched, fields) =
Exists.byFields tableName howMatched fields (Sql.existingConnection conn) Exists.byFields tableName howMatched fields (Sql.existingConnection conn)
/// Determine if documents exist using a JSON containment query (@>) /// <summary>Determine if a document exists using a JSON containment query (<tt>@&gt;</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which existence should be checked (may include schema)</param>
/// <param name="criteria">The document to match with the containment query</param>
/// <returns>True if any matching documents exist, false if not</returns>
[<Extension>] [<Extension>]
static member inline ExistsByContains(conn, tableName, criteria: 'TCriteria) = static member inline ExistsByContains(conn, tableName, criteria: 'TCriteria) =
Exists.byContains tableName criteria (Sql.existingConnection conn) Exists.byContains tableName criteria (Sql.existingConnection conn)
/// Determine if documents exist using a JSON Path match query (@?) /// <summary>Determine if a document exists using a JSON Path match query (<tt>@?</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which existence should be checked (may include schema)</param>
/// <param name="jsonPath">The JSON Path expression to be matched</param>
/// <returns>True if any matching documents exist, false if not</returns>
[<Extension>] [<Extension>]
static member inline ExistsByJsonPath(conn, tableName, jsonPath) = static member inline ExistsByJsonPath(conn, tableName, jsonPath) =
Exists.byJsonPath tableName jsonPath (Sql.existingConnection conn) Exists.byJsonPath tableName jsonPath (Sql.existingConnection conn)
/// Retrieve all documents in the given table /// <summary>Retrieve all documents in the given table</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <returns>All documents from the given table</returns>
[<Extension>] [<Extension>]
static member inline FindAll<'TDoc>(conn, tableName) = static member inline FindAll<'TDoc>(conn, tableName) =
Find.All<'TDoc>(tableName, Sql.existingConnection conn) Find.All<'TDoc>(tableName, Sql.existingConnection conn)
/// Retrieve all documents in the given table ordered by the given fields in the document /// <summary>Retrieve all documents in the given table ordered by the given fields in the document</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <returns>All documents from the given table, ordered by the given fields</returns>
[<Extension>] [<Extension>]
static member inline FindAllOrdered<'TDoc>(conn, tableName, orderFields) = static member inline FindAllOrdered<'TDoc>(conn, tableName, orderFields) =
Find.AllOrdered<'TDoc>(tableName, orderFields, Sql.existingConnection conn) Find.AllOrdered<'TDoc>(tableName, orderFields, Sql.existingConnection conn)
/// Retrieve a document by its ID; returns None if not found /// <summary>Retrieve a document by its ID</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="docId">The ID of the document to retrieve</param>
/// <returns>The document if found, <tt>null</tt> otherwise</returns>
[<Extension>] [<Extension>]
static member inline FindById<'TKey, 'TDoc when 'TDoc: null and 'TDoc: not struct>(conn, tableName, docId: 'TKey) = static member inline FindById<'TKey, 'TDoc when 'TDoc: null and 'TDoc: not struct>(conn, tableName, docId: 'TKey) =
Find.ById<'TKey, 'TDoc>(tableName, docId, Sql.existingConnection conn) Find.ById<'TKey, 'TDoc>(tableName, docId, Sql.existingConnection conn)
/// Retrieve documents matching a JSON field comparison query (->> =) /// <summary>Retrieve documents matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <returns>All documents matching the given fields</returns>
[<Extension>] [<Extension>]
static member inline FindByFields<'TDoc>(conn, tableName, howMatched, fields) = static member inline FindByFields<'TDoc>(conn, tableName, howMatched, fields) =
Find.ByFields<'TDoc>(tableName, howMatched, fields, Sql.existingConnection conn) Find.ByFields<'TDoc>(tableName, howMatched, fields, Sql.existingConnection conn)
/// Retrieve documents matching a JSON field comparison query (->> =) ordered by the given fields in the document /// <summary>
/// Retrieve documents matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.) ordered by the given fields in
/// the document
/// </summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="queryFields">The field conditions to match</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <returns>All documents matching the given fields, ordered by the other given fields</returns>
[<Extension>] [<Extension>]
static member inline FindByFieldsOrdered<'TDoc>(conn, tableName, howMatched, queryFields, orderFields) = static member inline FindByFieldsOrdered<'TDoc>(conn, tableName, howMatched, queryFields, orderFields) =
Find.ByFieldsOrdered<'TDoc>( Find.ByFieldsOrdered<'TDoc>(
tableName, howMatched, queryFields, orderFields, Sql.existingConnection conn) tableName, howMatched, queryFields, orderFields, Sql.existingConnection conn)
/// Retrieve documents matching a JSON containment query (@>) /// <summary>Retrieve documents matching a JSON containment query (<tt>@&gt;</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="criteria">The document to match with the containment query</param>
/// <returns>All documents matching the given containment query</returns>
[<Extension>] [<Extension>]
static member inline FindByContains<'TDoc>(conn, tableName, criteria: obj) = static member inline FindByContains<'TDoc>(conn, tableName, criteria: obj) =
Find.ByContains<'TDoc>(tableName, criteria, Sql.existingConnection conn) Find.ByContains<'TDoc>(tableName, criteria, Sql.existingConnection conn)
/// Retrieve documents matching a JSON containment query (@>) ordered by the given fields in the document /// <summary>
/// Retrieve documents matching a JSON containment query (<tt>@&gt;</tt>) ordered by the given fields in the
/// document
/// </summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="criteria">The document to match with the containment query</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <returns>All documents matching the given containment query, ordered by the given fields</returns>
[<Extension>] [<Extension>]
static member inline FindByContainsOrdered<'TDoc>(conn, tableName, criteria: obj, orderFields) = static member inline FindByContainsOrdered<'TDoc>(conn, tableName, criteria: obj, orderFields) =
Find.ByContainsOrdered<'TDoc>(tableName, criteria, orderFields, Sql.existingConnection conn) Find.ByContainsOrdered<'TDoc>(tableName, criteria, orderFields, Sql.existingConnection conn)
/// Retrieve documents matching a JSON Path match query (@?) /// <summary>Retrieve documents matching a JSON Path match query (<tt>@?</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="jsonPath">The JSON Path expression to match</param>
/// <returns>All documents matching the given JSON Path expression</returns>
[<Extension>] [<Extension>]
static member inline FindByJsonPath<'TDoc>(conn, tableName, jsonPath) = static member inline FindByJsonPath<'TDoc>(conn, tableName, jsonPath) =
Find.ByJsonPath<'TDoc>(tableName, jsonPath, Sql.existingConnection conn) Find.ByJsonPath<'TDoc>(tableName, jsonPath, Sql.existingConnection conn)
/// Retrieve documents matching a JSON Path match query (@?) ordered by the given fields in the document /// <summary>
/// Retrieve documents matching a JSON Path match query (<tt>@?</tt>) ordered by the given fields in the document
/// </summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="jsonPath">The JSON Path expression to match</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <returns>All documents matching the given JSON Path expression, ordered by the given fields</returns>
[<Extension>] [<Extension>]
static member inline FindByJsonPathOrdered<'TDoc>(conn, tableName, jsonPath, orderFields) = static member inline FindByJsonPathOrdered<'TDoc>(conn, tableName, jsonPath, orderFields) =
Find.ByJsonPathOrdered<'TDoc>(tableName, jsonPath, orderFields, Sql.existingConnection conn) Find.ByJsonPathOrdered<'TDoc>(tableName, jsonPath, orderFields, Sql.existingConnection conn)
/// Retrieve the first document matching a JSON field comparison query (->> =); returns null if not found /// <summary>Retrieve the first document matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <returns>The first document, or <tt>null</tt> if not found</returns>
[<Extension>] [<Extension>]
static member inline FindFirstByFields<'TDoc when 'TDoc: null and 'TDoc: not struct>( static member inline FindFirstByFields<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, tableName, howMatched, fields) = conn, tableName, howMatched, fields) =
Find.FirstByFields<'TDoc>(tableName, howMatched, fields, Sql.existingConnection conn) Find.FirstByFields<'TDoc>(tableName, howMatched, fields, Sql.existingConnection conn)
/// Retrieve the first document matching a JSON field comparison query (->> =) ordered by the given fields in the /// <summary>
/// document; returns null if not found /// Retrieve the first document matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.) ordered by the given
/// fields in the document
/// </summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="queryFields">The field conditions to match</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <returns>The first document ordered by the given fields, or <tt>null</tt> if not found</returns>
[<Extension>] [<Extension>]
static member inline FindFirstByFieldsOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>( static member inline FindFirstByFieldsOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, tableName, howMatched, queryFields, orderFields) = conn, tableName, howMatched, queryFields, orderFields) =
Find.FirstByFieldsOrdered<'TDoc>( Find.FirstByFieldsOrdered<'TDoc>(
tableName, howMatched, queryFields, orderFields, Sql.existingConnection conn) tableName, howMatched, queryFields, orderFields, Sql.existingConnection conn)
/// Retrieve the first document matching a JSON containment query (@>); returns None if not found /// <summary>Retrieve the first document matching a JSON containment query (<tt>@&gt;</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="criteria">The document to match with the containment query</param>
/// <returns>The first document, or <tt>null</tt> if not found</returns>
[<Extension>] [<Extension>]
static member inline FindFirstByContains<'TDoc when 'TDoc: null and 'TDoc: not struct>( static member inline FindFirstByContains<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, tableName, criteria: obj) = conn, tableName, criteria: obj) =
Find.FirstByContains<'TDoc>(tableName, criteria, Sql.existingConnection conn) Find.FirstByContains<'TDoc>(tableName, criteria, Sql.existingConnection conn)
/// Retrieve the first document matching a JSON containment query (@>) ordered by the given fields in the document; /// <summary>
/// returns None if not found /// Retrieve the first document matching a JSON containment query (<tt>@&gt;</tt>) ordered by the given fields in
/// the document
/// </summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="criteria">The document to match with the containment query</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <returns>The first document ordered by the given fields, or <tt>null</tt> if not found</returns>
[<Extension>] [<Extension>]
static member inline FindFirstByContainsOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>( static member inline FindFirstByContainsOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, tableName, criteria: obj, orderFields) = conn, tableName, criteria: obj, orderFields) =
Find.FirstByContainsOrdered<'TDoc>(tableName, criteria, orderFields, Sql.existingConnection conn) Find.FirstByContainsOrdered<'TDoc>(tableName, criteria, orderFields, Sql.existingConnection conn)
/// Retrieve the first document matching a JSON Path match query (@?); returns None if not found /// <summary>Retrieve the first document matching a JSON Path match query (<tt>@?</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="jsonPath">The JSON Path expression to match</param>
/// <returns>The first document, or <tt>null</tt> if not found</returns>
[<Extension>] [<Extension>]
static member inline FindFirstByJsonPath<'TDoc when 'TDoc: null and 'TDoc: not struct>(conn, tableName, jsonPath) = static member inline FindFirstByJsonPath<'TDoc when 'TDoc: null and 'TDoc: not struct>(conn, tableName, jsonPath) =
Find.FirstByJsonPath<'TDoc>(tableName, jsonPath, Sql.existingConnection conn) Find.FirstByJsonPath<'TDoc>(tableName, jsonPath, Sql.existingConnection conn)
/// Retrieve the first document matching a JSON Path match query (@?) ordered by the given fields in the document; /// <summary>
/// returns None if not found /// Retrieve the first document matching a JSON Path match query (<tt>@?</tt>) ordered by the given fields in the
/// document
/// </summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="jsonPath">The JSON Path expression to match</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <returns>The first document ordered by the given fields, or <tt>null</tt> if not found</returns>
[<Extension>] [<Extension>]
static member inline FindFirstByJsonPathOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>( static member inline FindFirstByJsonPathOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, tableName, jsonPath, orderFields) = conn, tableName, jsonPath, orderFields) =
Find.FirstByJsonPathOrdered<'TDoc>(tableName, jsonPath, orderFields, Sql.existingConnection conn) Find.FirstByJsonPathOrdered<'TDoc>(tableName, jsonPath, orderFields, Sql.existingConnection conn)
/// Update an entire document by its ID /// <summary>Update (replace) an entire document by its ID</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which a document should be updated (may include schema)</param>
/// <param name="docId">The ID of the document to be updated (replaced)</param>
/// <param name="document">The new document</param>
[<Extension>] [<Extension>]
static member inline UpdateById(conn, tableName, docId: 'TKey, document: 'TDoc) = static member inline UpdateById(conn, tableName, docId: 'TKey, document: 'TDoc) =
Update.byId tableName docId document (Sql.existingConnection conn) Update.byId tableName docId document (Sql.existingConnection conn)
/// Update an entire document by its ID, using the provided function to obtain the ID from the document /// <summary>
/// Update (replace) an entire document by its ID, using the provided function to obtain the ID from the document
/// </summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which a document should be updated (may include schema)</param>
/// <param name="idFunc">The function to obtain the ID of the document</param>
/// <param name="document">The new document</param>
[<Extension>] [<Extension>]
static member inline UpdateByFunc(conn, tableName, idFunc: System.Func<'TDoc, 'TKey>, document: 'TDoc) = static member inline UpdateByFunc(conn, tableName, idFunc: System.Func<'TDoc, 'TKey>, document: 'TDoc) =
Update.ByFunc(tableName, idFunc, document, Sql.existingConnection conn) Update.ByFunc(tableName, idFunc, document, Sql.existingConnection conn)
/// Patch a document by its ID /// <summary>Patch a document by its ID</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which a document should be patched (may include schema)</param>
/// <param name="docId">The ID of the document to patch</param>
/// <param name="patch">The partial document to patch the existing document</param>
[<Extension>] [<Extension>]
static member inline PatchById(conn, tableName, docId: 'TKey, patch: 'TPatch) = static member inline PatchById(conn, tableName, docId: 'TKey, patch: 'TPatch) =
Patch.byId tableName docId patch (Sql.existingConnection conn) Patch.byId tableName docId patch (Sql.existingConnection conn)
/// Patch documents using a JSON field comparison query in the WHERE clause (->> =) /// <summary>
/// Patch documents using a JSON field comparison query in the <tt>WHERE</tt> clause (<tt>-&gt;&gt; =</tt>, etc.)
/// </summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be patched (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="patch">The partial document to patch the existing document</param>
[<Extension>] [<Extension>]
static member inline PatchByFields(conn, tableName, howMatched, fields, patch: 'TPatch) = static member inline PatchByFields(conn, tableName, howMatched, fields, patch: 'TPatch) =
Patch.byFields tableName howMatched fields patch (Sql.existingConnection conn) Patch.byFields tableName howMatched fields patch (Sql.existingConnection conn)
/// Patch documents using a JSON containment query in the WHERE clause (@>) /// <summary>Patch documents using a JSON containment query in the <tt>WHERE</tt> clause (<tt>@&gt;</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be patched (may include schema)</param>
/// <param name="criteria">The document to match the containment query</param>
/// <param name="patch">The partial document to patch the existing document</param>
[<Extension>] [<Extension>]
static member inline PatchByContains(conn, tableName, criteria: 'TCriteria, patch: 'TPatch) = static member inline PatchByContains(conn, tableName, criteria: 'TCriteria, patch: 'TPatch) =
Patch.byContains tableName criteria patch (Sql.existingConnection conn) Patch.byContains tableName criteria patch (Sql.existingConnection conn)
/// Patch documents using a JSON Path match query in the WHERE clause (@?) /// <summary>Patch documents using a JSON Path match query in the <tt>WHERE</tt> clause (<tt>@?</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be patched (may include schema)</param>
/// <param name="jsonPath">The JSON Path expression to match</param>
/// <param name="patch">The partial document to patch the existing document</param>
[<Extension>] [<Extension>]
static member inline PatchByJsonPath(conn, tableName, jsonPath, patch: 'TPatch) = static member inline PatchByJsonPath(conn, tableName, jsonPath, patch: 'TPatch) =
Patch.byJsonPath tableName jsonPath patch (Sql.existingConnection conn) Patch.byJsonPath tableName jsonPath patch (Sql.existingConnection conn)
/// Remove fields from a document by the document's ID /// <summary>Remove fields from a document by the document's ID</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which a document should be modified (may include schema)</param>
/// <param name="docId">The ID of the document to modify</param>
/// <param name="fieldNames">One or more field names to remove from the document</param>
[<Extension>] [<Extension>]
static member inline RemoveFieldsById(conn, tableName, docId: 'TKey, fieldNames) = static member inline RemoveFieldsById(conn, tableName, docId: 'TKey, fieldNames) =
RemoveFields.byId tableName docId fieldNames (Sql.existingConnection conn) RemoveFields.byId tableName docId fieldNames (Sql.existingConnection conn)
/// Remove fields from documents via a comparison on JSON fields in the document /// <summary>Remove fields from documents via a comparison on JSON fields in the document</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be modified (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="fieldNames">One or more field names to remove from the matching documents</param>
[<Extension>] [<Extension>]
static member inline RemoveFieldsByFields(conn, tableName, howMatched, fields, fieldNames) = static member inline RemoveFieldsByFields(conn, tableName, howMatched, fields, fieldNames) =
RemoveFields.byFields tableName howMatched fields fieldNames (Sql.existingConnection conn) RemoveFields.byFields tableName howMatched fields fieldNames (Sql.existingConnection conn)
/// Remove fields from documents via a JSON containment query (@>) /// <summary>Remove fields from documents via a JSON containment query (<tt>@&gt;</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be modified (may include schema)</param>
/// <param name="criteria">The document to match the containment query</param>
/// <param name="fieldNames">One or more field names to remove from the matching documents</param>
[<Extension>] [<Extension>]
static member inline RemoveFieldsByContains(conn, tableName, criteria: 'TContains, fieldNames) = static member inline RemoveFieldsByContains(conn, tableName, criteria: 'TContains, fieldNames) =
RemoveFields.byContains tableName criteria fieldNames (Sql.existingConnection conn) RemoveFields.byContains tableName criteria fieldNames (Sql.existingConnection conn)
/// Remove fields from documents via a JSON Path match query (@?) /// <summary>Remove fields from documents via a JSON Path match query (<tt>@?</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be modified (may include schema)</param>
/// <param name="jsonPath">The JSON Path expression to match</param>
/// <param name="fieldNames">One or more field names to remove from the matching documents</param>
[<Extension>] [<Extension>]
static member inline RemoveFieldsByJsonPath(conn, tableName, jsonPath, fieldNames) = static member inline RemoveFieldsByJsonPath(conn, tableName, jsonPath, fieldNames) =
RemoveFields.byJsonPath tableName jsonPath fieldNames (Sql.existingConnection conn) RemoveFields.byJsonPath tableName jsonPath fieldNames (Sql.existingConnection conn)
/// Delete a document by its ID /// <summary>Delete a document by its ID</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which a document should be deleted (may include schema)</param>
/// <param name="docId">The ID of the document to delete</param>
[<Extension>] [<Extension>]
static member inline DeleteById(conn, tableName, docId: 'TKey) = static member inline DeleteById(conn, tableName, docId: 'TKey) =
Delete.byId tableName docId (Sql.existingConnection conn) Delete.byId tableName docId (Sql.existingConnection conn)
/// Delete documents by matching a JSON field comparison query (->> =) /// <summary>Delete documents by matching a JSON field comparison query (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be deleted (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
[<Extension>] [<Extension>]
static member inline DeleteByFields(conn, tableName, howMatched, fields) = static member inline DeleteByFields(conn, tableName, howMatched, fields) =
Delete.byFields tableName howMatched fields (Sql.existingConnection conn) Delete.byFields tableName howMatched fields (Sql.existingConnection conn)
/// Delete documents by matching a JSON containment query (@>) /// <summary>Delete documents by matching a JSON contains query (<tt>@&gt;</tt>)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be deleted (may include schema)</param>
/// <param name="criteria">The document to match the containment query</param>
[<Extension>] [<Extension>]
static member inline DeleteByContains(conn, tableName, criteria: 'TContains) = static member inline DeleteByContains(conn, tableName, criteria: 'TContains) =
Delete.byContains tableName criteria (Sql.existingConnection conn) Delete.byContains tableName criteria (Sql.existingConnection conn)
/// Delete documents by matching a JSON Path match query (@?) /// <summary>Delete documents by matching a JSON Path match query (@?)</summary>
/// <param name="conn">The <tt>NpgsqlConnection</tt> on which to run the query</param>
/// <param name="tableName">The table in which documents should be deleted (may include schema)</param>
/// <param name="jsonPath">The JSON Path expression to match</param>
[<Extension>] [<Extension>]
static member inline DeleteByJsonPath(conn, tableName, path) = static member inline DeleteByJsonPath(conn, tableName, jsonPath) =
Delete.byJsonPath tableName path (Sql.existingConnection conn) Delete.byJsonPath tableName jsonPath (Sql.existingConnection conn)

View File

@ -250,7 +250,7 @@ module Exists =
toExists toExists
sqlProps sqlProps
/// <summary>Commands to determine if documents exist</summary> /// <summary>Commands to retrieve documents</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Find = module Find =

View File

@ -3,20 +3,25 @@
open BitBadger.Documents open BitBadger.Documents
open Microsoft.Data.Sqlite open Microsoft.Data.Sqlite
/// Configuration for document handling /// <summary>Configuration for document handling</summary>
module Configuration = module Configuration =
/// The connection string to use for query execution /// The connection string to use for query execution
let mutable internal connectionString: string option = None let mutable internal connectionString: string option = None
/// Register a connection string to use for query execution (enables foreign keys) /// <summary>Register a connection string to use for query execution</summary>
/// <param name="connStr">The connection string to use for connections from this library</param>
/// <remarks>This also enables foreign keys</remarks>
[<CompiledName "UseConnectionString">] [<CompiledName "UseConnectionString">]
let useConnectionString connStr = let useConnectionString connStr =
let builder = SqliteConnectionStringBuilder connStr let builder = SqliteConnectionStringBuilder connStr
builder.ForeignKeys <- Option.toNullable (Some true) builder.ForeignKeys <- Option.toNullable (Some true)
connectionString <- Some (string builder) connectionString <- Some (string builder)
/// Retrieve the currently configured data source /// <summary>Retrieve a new connection using currently configured connection string</summary>
/// <returns>A new database connection</returns>
/// <exception cref="T:System.InvalidOperationException">If no data source has been configured</exception>
/// <exception cref="SqliteException">If the connection cannot be opened</exception>
[<CompiledName "DbConn">] [<CompiledName "DbConn">]
let dbConn () = let dbConn () =
match connectionString with match connectionString with
@ -27,11 +32,16 @@ module Configuration =
| None -> invalidOp "Please provide a connection string before attempting data access" | None -> invalidOp "Please provide a connection string before attempting data access"
/// Query definitions /// <summary>Query definitions</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Query = module Query =
/// Create a WHERE clause fragment to implement a comparison on fields in a JSON document /// <summary>
/// Create a <tt>WHERE</tt> clause fragment to implement a comparison on fields in a JSON document
/// </summary>
/// <param name="howMatched">How the fields should be matched</param>
/// <param name="fields">The fields for the comparisons</param>
/// <returns>A <tt>WHERE</tt> clause implementing the comparisons for the given fields</returns>
[<CompiledName "WhereByFields">] [<CompiledName "WhereByFields">]
let whereByFields (howMatched: FieldMatch) fields = let whereByFields (howMatched: FieldMatch) fields =
let name = ParameterName() let name = ParameterName()
@ -53,58 +63,82 @@ module Query =
| _ -> $"{it.Path SQLite AsSql} {it.Comparison.OpSql} {name.Derive it.ParameterName}") | _ -> $"{it.Path SQLite AsSql} {it.Comparison.OpSql} {name.Derive it.ParameterName}")
|> String.concat $" {howMatched} " |> String.concat $" {howMatched} "
/// Create a WHERE clause fragment to implement an ID-based query /// <summary>Create a <tt>WHERE</tt> clause fragment to implement an ID-based query</summary>
/// <param name="docId">The ID of the document</param>
/// <returns>A <tt>WHERE</tt> clause fragment identifying a document by its ID</returns>
[<CompiledName "WhereById">] [<CompiledName "WhereById">]
let whereById paramName = let whereById (docId: 'TKey) =
whereByFields Any [ { Field.Equal (Configuration.idField ()) 0 with ParameterName = Some paramName } ] whereByFields Any [ { Field.Equal (Configuration.idField ()) docId with ParameterName = Some "@id" } ]
/// Create an UPDATE statement to patch documents /// <summary>Create an <tt>UPDATE</tt> statement to patch documents</summary>
/// <param name="tableName">The table to be updated</param>
/// <returns>A query to patch documents</returns>
[<CompiledName "Patch">] [<CompiledName "Patch">]
let patch tableName = let patch tableName =
$"UPDATE %s{tableName} SET data = json_patch(data, json(@data))" $"UPDATE %s{tableName} SET data = json_patch(data, json(@data))"
/// Create an UPDATE statement to remove fields from documents /// <summary>Create an <tt>UPDATE</tt> statement to remove fields from documents</summary>
/// <param name="tableName">The table to be updated</param>
/// <param name="parameters">The parameters with the field names to be removed</param>
/// <returns>A query to remove fields from documents</returns>
[<CompiledName "RemoveFields">] [<CompiledName "RemoveFields">]
let removeFields tableName (parameters: SqliteParameter seq) = let removeFields tableName (parameters: SqliteParameter seq) =
let paramNames = parameters |> Seq.map _.ParameterName |> String.concat ", " let paramNames = parameters |> Seq.map _.ParameterName |> String.concat ", "
$"UPDATE %s{tableName} SET data = json_remove(data, {paramNames})" $"UPDATE %s{tableName} SET data = json_remove(data, {paramNames})"
/// Create a query by a document's ID /// <summary>Create a query by a document's ID</summary>
/// <param name="statement">The SQL statement to be run against a document by its ID</param>
/// <param name="docId">The ID of the document targeted</param>
/// <returns>A query addressing a document by its ID</returns>
[<CompiledName "ById">] [<CompiledName "ById">]
let byId<'TKey> statement (docId: 'TKey) = let byId<'TKey> statement (docId: 'TKey) =
Query.statementWhere Query.statementWhere
statement statement
(whereByFields Any [ { Field.Equal (Configuration.idField ()) docId with ParameterName = Some "@id" } ]) (whereByFields Any [ { Field.Equal (Configuration.idField ()) docId with ParameterName = Some "@id" } ])
/// Create a query on JSON fields /// <summary>Create a query on JSON fields</summary>
/// <param name="statement">The SQL statement to be run against matching fields</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to be matched</param>
/// <returns>A query addressing documents by field matching conditions</returns>
[<CompiledName "ByFields">] [<CompiledName "ByFields">]
let byFields statement howMatched fields = let byFields statement howMatched fields =
Query.statementWhere statement (whereByFields howMatched fields) Query.statementWhere statement (whereByFields howMatched fields)
/// Data definition /// <summary>Data definition</summary>
module Definition = module Definition =
/// SQL statement to create a document table /// <summary>SQL statement to create a document table</summary>
/// <param name="name">The name of the table (may include schema)</param>
/// <returns>A query to create the table if it does not exist</returns>
[<CompiledName "EnsureTable">] [<CompiledName "EnsureTable">]
let ensureTable name = let ensureTable name =
Query.Definition.ensureTableFor name "TEXT" Query.Definition.ensureTableFor name "TEXT"
/// Parameter handling helpers /// <summary>Parameter handling helpers</summary>
[<AutoOpen>] [<AutoOpen>]
module Parameters = module Parameters =
/// Create an ID parameter (name "@id", key will be treated as a string) /// <summary>Create an ID parameter (name "@id")</summary>
/// <param name="key">The key value for the ID parameter</param>
/// <returns>The name and parameter value for the ID</returns>
[<CompiledName "Id">] [<CompiledName "Id">]
let idParam (key: 'TKey) = let idParam (key: 'TKey) =
SqliteParameter("@id", string key) SqliteParameter("@id", string key)
/// Create a parameter with a JSON value /// <summary>Create a parameter with a JSON value</summary>
/// <param name="name">The name of the parameter to create</param>
/// <param name="it">The criteria to provide as JSON</param>
/// <returns>The name and parameter value for the JSON field</returns>
[<CompiledName "Json">] [<CompiledName "Json">]
let jsonParam name (it: 'TJson) = let jsonParam name (it: 'TJson) =
SqliteParameter(name, Configuration.serializer().Serialize it) SqliteParameter(name, Configuration.serializer().Serialize it)
/// Create JSON field parameters /// <summary>Create JSON field parameters</summary>
/// <param name="fields">The <tt>Field</tt>s to convert to parameters</param>
/// <param name="parameters">The current parameters for the query</param>
/// <returns>A unified sequence of parameter names and values</returns>
[<CompiledName "AddFields">] [<CompiledName "AddFields">]
let addFieldParams fields parameters = let addFieldParams fields parameters =
let name = ParameterName() let name = ParameterName()
@ -132,7 +166,10 @@ module Parameters =
let addFieldParam name field parameters = let addFieldParam name field parameters =
addFieldParams [ { field with ParameterName = Some name } ] parameters addFieldParams [ { field with ParameterName = Some name } ] parameters
/// Append JSON field name parameters for the given field names to the given parameters /// <summary>Append JSON field name parameters for the given field names to the given parameters</summary>
/// <param name="paramName">The name of the parameter to use for each field</param>
/// <param name="fieldNames">The names of fields to be addressed</param>
/// <returns>The name (<tt>@name</tt>) and parameter value for the field names</returns>
[<CompiledName "FieldNames">] [<CompiledName "FieldNames">]
let fieldNameParams paramName fieldNames = let fieldNameParams paramName fieldNames =
fieldNames fieldNames
@ -140,27 +177,37 @@ module Parameters =
|> Seq.toList |> Seq.toList
|> Seq.ofList |> Seq.ofList
/// An empty parameter sequence /// <summary>An empty parameter sequence</summary>
[<CompiledName "None">] [<CompiledName "None">]
let noParams = let noParams =
Seq.empty<SqliteParameter> Seq.empty<SqliteParameter>
/// Helper functions for handling results /// <summary>Helper functions for handling results</summary>
[<AutoOpen>] [<AutoOpen>]
module Results = module Results =
/// Create a domain item from a document, specifying the field in which the document is found /// <summary>Create a domain item from a document, specifying the field in which the document is found</summary>
/// <param name="field">The field name containing the JSON document</param>
/// <param name="rdr">A <tt>SqliteDataReader</tt> set to the row with the document to be constructed</param>
/// <returns>The constructed domain item</returns>
[<CompiledName "FromDocument">] [<CompiledName "FromDocument">]
let fromDocument<'TDoc> field (rdr: SqliteDataReader) : 'TDoc = let fromDocument<'TDoc> field (rdr: SqliteDataReader) : 'TDoc =
Configuration.serializer().Deserialize<'TDoc>(rdr.GetString(rdr.GetOrdinal field)) Configuration.serializer().Deserialize<'TDoc>(rdr.GetString(rdr.GetOrdinal field))
/// Create a domain item from a document /// <summary>Create a domain item from a document</summary>
/// <param name="rdr">A <tt>SqliteDataReader</tt> set to the row with the document to be constructed</param>
/// <returns>The constructed domain item</returns>
[<CompiledName "FromData">] [<CompiledName "FromData">]
let fromData<'TDoc> rdr = let fromData<'TDoc> rdr =
fromDocument<'TDoc> "data" rdr fromDocument<'TDoc> "data" rdr
/// <summary>
/// Create a list of items for the results of the given command, using the specified mapping function /// Create a list of items for the results of the given command, using the specified mapping function
/// </summary>
/// <param name="cmd">The command to execute</param>
/// <param name="mapFunc">The mapping function from data reader to domain class instance</param>
/// <returns>A list of items from the reader</returns>
[<CompiledName "FSharpToCustomList">] [<CompiledName "FSharpToCustomList">]
let toCustomList<'TDoc> (cmd: SqliteCommand) (mapFunc: SqliteDataReader -> 'TDoc) = backgroundTask { let toCustomList<'TDoc> (cmd: SqliteCommand) (mapFunc: SqliteDataReader -> 'TDoc) = backgroundTask {
use! rdr = cmd.ExecuteReaderAsync() use! rdr = cmd.ExecuteReaderAsync()
@ -170,35 +217,60 @@ module Results =
return List.ofSeq it return List.ofSeq it
} }
/// Extract a count from the first column /// <summary>
[<CompiledName "ToCount">] /// Create a list of items for the results of the given command, using the specified mapping function
let toCount (row: SqliteDataReader) = /// </summary>
row.GetInt64 0 /// <param name="cmd">The command to execute</param>
/// <param name="mapFunc">The mapping function from data reader to domain class instance</param>
/// <returns>A list of items from the reader</returns>
let ToCustomList<'TDoc>(cmd: SqliteCommand, mapFunc: System.Func<SqliteDataReader, 'TDoc>) = backgroundTask {
use! rdr = cmd.ExecuteReaderAsync()
let it = ResizeArray<'TDoc>()
while! rdr.ReadAsync() do
it.Add(mapFunc.Invoke rdr)
return it
}
/// Extract a true/false value from a count in the first column /// <summary>Extract a count from the first column</summary>
/// <param name="rdr">A <tt>SqliteDataReader</tt> set to the row with the count to retrieve</param>
/// <returns>The count from the row</returns>
[<CompiledName "ToCount">]
let toCount (rdr: SqliteDataReader) =
rdr.GetInt64 0
/// <summary>Extract a true/false value from the first column</summary>
/// <param name="rdr">A <tt>SqliteDataReader</tt> set to the row with the true/false value to retrieve</param>
/// <returns>The true/false value from the row</returns>
/// <remarks>SQLite implements boolean as 1 = true, 0 = false</remarks>
[<CompiledName "ToExists">] [<CompiledName "ToExists">]
let toExists row = let toExists rdr =
toCount(row) > 0L toCount rdr > 0L
[<AutoOpen>] [<AutoOpen>]
module internal Helpers = module internal Helpers =
/// Execute a non-query command /// <summary>Execute a non-query command</summary>
/// <param name="cmd">The command to be executed</param>
let internal write (cmd: SqliteCommand) = backgroundTask { let internal write (cmd: SqliteCommand) = backgroundTask {
let! _ = cmd.ExecuteNonQueryAsync() let! _ = cmd.ExecuteNonQueryAsync()
() ()
} }
/// Versions of queries that accept a SqliteConnection as the last parameter /// <summary>Versions of queries that accept a <tt>SqliteConnection</tt> as the last parameter</summary>
module WithConn = module WithConn =
/// Commands to execute custom SQL queries /// <summary>Commands to execute custom SQL queries</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Custom = module Custom =
/// Execute a query that returns a list of results /// <summary>Execute a query that returns a list of results</summary>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function between the document and the domain item</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>A list of results for the given query</returns>
[<CompiledName "FSharpList">] [<CompiledName "FSharpList">]
let list<'TDoc> query (parameters: SqliteParameter seq) (mapFunc: SqliteDataReader -> 'TDoc) let list<'TDoc> query (parameters: SqliteParameter seq) (mapFunc: SqliteDataReader -> 'TDoc)
(conn: SqliteConnection) = (conn: SqliteConnection) =
@ -207,20 +279,39 @@ module WithConn =
cmd.Parameters.AddRange parameters cmd.Parameters.AddRange parameters
toCustomList<'TDoc> cmd mapFunc toCustomList<'TDoc> cmd mapFunc
/// Execute a query that returns a list of results /// <summary>Execute a query that returns a list of results</summary>
let List<'TDoc>(query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>, conn) = backgroundTask { /// <param name="query">The query to retrieve the results</param>
let! results = list<'TDoc> query parameters mapFunc.Invoke conn /// <param name="parameters">Parameters to use for the query</param>
return ResizeArray<'TDoc> results /// <param name="mapFunc">The mapping function between the document and the domain item</param>
} /// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>A list of results for the given query</returns>
let List<'TDoc>(
query, parameters: SqliteParameter seq, mapFunc: System.Func<SqliteDataReader, 'TDoc>,
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 (returns None if not found) /// <summary>Execute a query that returns one or no results</summary>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function between the document and the domain item</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns><tt>Some</tt> with the first matching result, or <tt>None</tt> if not found</returns>
[<CompiledName "FSharpSingle">] [<CompiledName "FSharpSingle">]
let single<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) conn = backgroundTask { let single<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) conn = backgroundTask {
let! results = list query parameters mapFunc conn let! results = list query parameters mapFunc conn
return FSharp.Collections.List.tryHead results return FSharp.Collections.List.tryHead results
} }
/// Execute a query that returns one or no results (returns null if not found) /// <summary>Execute a query that returns one or no results</summary>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function between the document and the domain item</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>The first matching result, or <tt>null</tt> if not found</returns>
let Single<'TDoc when 'TDoc: null and 'TDoc: not struct>( let Single<'TDoc when 'TDoc: null and 'TDoc: not struct>(
query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>, conn query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>, conn
) = backgroundTask { ) = backgroundTask {
@ -228,7 +319,10 @@ module WithConn =
return Option.toObj result return Option.toObj result
} }
/// Execute a query that does not return a value /// <summary>Execute a query that returns no results</summary>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "NonQuery">] [<CompiledName "NonQuery">]
let nonQuery query (parameters: SqliteParameter seq) (conn: SqliteConnection) = let nonQuery query (parameters: SqliteParameter seq) (conn: SqliteConnection) =
use cmd = conn.CreateCommand() use cmd = conn.CreateCommand()
@ -236,7 +330,12 @@ module WithConn =
cmd.Parameters.AddRange parameters cmd.Parameters.AddRange parameters
write cmd write cmd
/// Execute a query that returns a scalar value /// <summary>Execute a query that returns a scalar value</summary>
/// <param name="query">The query to retrieve the value</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function to obtain the value</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>The scalar value for the query</returns>
[<CompiledName "FSharpScalar">] [<CompiledName "FSharpScalar">]
let scalar<'T when 'T : struct> query (parameters: SqliteParameter seq) (mapFunc: SqliteDataReader -> 'T) let scalar<'T when 'T : struct> query (parameters: SqliteParameter seq) (mapFunc: SqliteDataReader -> 'T)
(conn: SqliteConnection) = backgroundTask { (conn: SqliteConnection) = backgroundTask {
@ -248,31 +347,45 @@ module WithConn =
return if isFound then mapFunc rdr else Unchecked.defaultof<'T> return if isFound then mapFunc rdr else Unchecked.defaultof<'T>
} }
/// Execute a query that returns a scalar value /// <summary>Execute a query that returns a scalar value</summary>
/// <param name="query">The query to retrieve the value</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function to obtain the value</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>The scalar value for the query</returns>
let Scalar<'T when 'T: struct>(query, parameters, mapFunc: System.Func<SqliteDataReader, 'T>, conn) = let Scalar<'T when 'T: struct>(query, parameters, mapFunc: System.Func<SqliteDataReader, 'T>, conn) =
scalar<'T> query parameters mapFunc.Invoke conn scalar<'T> query parameters mapFunc.Invoke conn
/// Functions to create tables and indexes /// <summary>Functions to create tables and indexes</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Definition = module Definition =
/// Create a document table /// <summary>Create a document table</summary>
/// <param name="name">The table whose existence should be ensured (may include schema)</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "EnsureTable">] [<CompiledName "EnsureTable">]
let ensureTable name conn = backgroundTask { let ensureTable name conn = backgroundTask {
do! Custom.nonQuery (Query.Definition.ensureTable name) [] conn do! Custom.nonQuery (Query.Definition.ensureTable name) [] conn
do! Custom.nonQuery (Query.Definition.ensureKey name SQLite) [] conn do! Custom.nonQuery (Query.Definition.ensureKey name SQLite) [] conn
} }
/// Create an index on a document table /// <summary>Create an index on field(s) within documents in the specified table</summary>
/// <param name="tableName">The table to be indexed (may include schema)</param>
/// <param name="indexName">The name of the index to create</param>
/// <param name="fields">One or more fields to be indexed</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "EnsureFieldIndex">] [<CompiledName "EnsureFieldIndex">]
let ensureFieldIndex tableName indexName fields conn = let ensureFieldIndex tableName indexName fields conn =
Custom.nonQuery (Query.Definition.ensureIndexOn tableName indexName fields SQLite) [] conn Custom.nonQuery (Query.Definition.ensureIndexOn tableName indexName fields SQLite) [] conn
/// Commands to add documents /// <summary>Commands to add documents</summary>
[<AutoOpen>] [<AutoOpen>]
module Document = module Document =
/// Insert a new document /// <summary>Insert a new document</summary>
/// <param name="tableName">The table into which the document should be inserted (may include schema)</param>
/// <param name="document">The document to be inserted</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "Insert">] [<CompiledName "Insert">]
let insert<'TDoc> tableName (document: 'TDoc) conn = let insert<'TDoc> tableName (document: 'TDoc) conn =
let query = let query =
@ -292,36 +405,58 @@ module WithConn =
(Query.insert tableName).Replace("@data", dataParam) (Query.insert tableName).Replace("@data", dataParam)
Custom.nonQuery query [ jsonParam "@data" document ] conn Custom.nonQuery query [ jsonParam "@data" document ] conn
/// <summary>
/// Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert") /// Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
/// </summary>
/// <param name="tableName">The table into which the document should be saved (may include schema)</param>
/// <param name="document">The document to be saved</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "Save">] [<CompiledName "Save">]
let save<'TDoc> tableName (document: 'TDoc) conn = let save<'TDoc> tableName (document: 'TDoc) conn =
Custom.nonQuery (Query.save tableName) [ jsonParam "@data" document ] conn Custom.nonQuery (Query.save tableName) [ jsonParam "@data" document ] conn
/// Commands to count documents /// <summary>Commands to count documents</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Count = module Count =
/// Count all documents in a table /// <summary>Count all documents in a table</summary>
/// <param name="tableName">The table in which documents should be counted (may include schema)</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>The count of the documents in the table</returns>
[<CompiledName "All">] [<CompiledName "All">]
let all tableName conn = let all tableName conn =
Custom.scalar (Query.count tableName) [] toCount conn Custom.scalar (Query.count tableName) [] toCount conn
/// Count matching documents using a comparison on JSON fields /// <summary>Count matching documents using JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="tableName">The table in which documents should be counted (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>The count of matching documents in the table</returns>
[<CompiledName "ByFields">] [<CompiledName "ByFields">]
let byFields tableName howMatched fields conn = let byFields tableName howMatched fields conn =
Custom.scalar Custom.scalar
(Query.byFields (Query.count tableName) howMatched fields) (addFieldParams fields []) toCount conn (Query.byFields (Query.count tableName) howMatched fields) (addFieldParams fields []) toCount conn
/// Commands to determine if documents exist /// <summary>Commands to determine if documents exist</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Exists = module Exists =
/// Determine if a document exists for the given ID /// <summary>Determine if a document exists for the given ID</summary>
/// <param name="tableName">The table in which existence should be checked (may include schema)</param>
/// <param name="docId">The ID of the document whose existence should be checked</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>True if a document exists, false if not</returns>
[<CompiledName "ById">] [<CompiledName "ById">]
let byId tableName (docId: 'TKey) conn = let byId tableName (docId: 'TKey) conn =
Custom.scalar (Query.exists tableName (Query.whereById "@id")) [ idParam docId ] toExists conn Custom.scalar (Query.exists tableName (Query.whereById docId)) [ idParam docId ] toExists conn
/// Determine if a document exists using a comparison on JSON fields /// <summary>Determine if a document exists using JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="tableName">The table in which existence should be checked (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>True if any matching documents exist, false if not</returns>
[<CompiledName "ByFields">] [<CompiledName "ByFields">]
let byFields tableName howMatched fields conn = let byFields tableName howMatched fields conn =
Custom.scalar Custom.scalar
@ -330,38 +465,65 @@ module WithConn =
toExists toExists
conn conn
/// Commands to retrieve documents /// <summary>Commands to retrieve documents</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Find = module Find =
/// Retrieve all documents in the given table /// <summary>Retrieve all documents in the given table</summary>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>All documents from the given table</returns>
[<CompiledName "FSharpAll">] [<CompiledName "FSharpAll">]
let all<'TDoc> tableName conn = let all<'TDoc> tableName conn =
Custom.list<'TDoc> (Query.find tableName) [] fromData<'TDoc> conn Custom.list<'TDoc> (Query.find tableName) [] fromData<'TDoc> conn
/// Retrieve all documents in the given table /// <summary>Retrieve all documents in the given table</summary>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>All documents from the given table</returns>
let All<'TDoc>(tableName, conn) = let All<'TDoc>(tableName, conn) =
Custom.List(Query.find tableName, [], fromData<'TDoc>, conn) Custom.List(Query.find tableName, [], fromData<'TDoc>, conn)
/// Retrieve all documents in the given table ordered by the given fields in the document /// <summary>Retrieve all documents in the given table ordered by the given fields in the document</summary>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>All documents from the given table, ordered by the given fields</returns>
[<CompiledName "FSharpAllOrdered">] [<CompiledName "FSharpAllOrdered">]
let allOrdered<'TDoc> tableName orderFields conn = let allOrdered<'TDoc> tableName orderFields conn =
Custom.list<'TDoc> (Query.find tableName + Query.orderBy orderFields SQLite) [] fromData<'TDoc> 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 /// <summary>Retrieve all documents in the given table ordered by the given fields in the document</summary>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>All documents from the given table, ordered by the given fields</returns>
let AllOrdered<'TDoc>(tableName, orderFields, conn) = let AllOrdered<'TDoc>(tableName, orderFields, conn) =
Custom.List(Query.find tableName + Query.orderBy orderFields SQLite, [], fromData<'TDoc>, conn) Custom.List(Query.find tableName + Query.orderBy orderFields SQLite, [], fromData<'TDoc>, conn)
/// Retrieve a document by its ID (returns None if not found) /// <summary>Retrieve a document by its ID</summary>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="docId">The ID of the document to retrieve</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns><tt>Some</tt> with the document if found, <tt>None</tt> otherwise</returns>
[<CompiledName "FSharpById">] [<CompiledName "FSharpById">]
let byId<'TKey, 'TDoc> tableName (docId: 'TKey) conn = let byId<'TKey, 'TDoc> tableName (docId: 'TKey) conn =
Custom.single<'TDoc> (Query.byId (Query.find tableName) docId) [ idParam docId ] fromData<'TDoc> conn Custom.single<'TDoc> (Query.byId (Query.find tableName) docId) [ idParam docId ] fromData<'TDoc> conn
/// Retrieve a document by its ID (returns null if not found) /// <summary>Retrieve a document by its ID</summary>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="docId">The ID of the document to retrieve</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>The document if found, <tt>null</tt> otherwise</returns>
let ById<'TKey, 'TDoc when 'TDoc: null and 'TDoc: not struct>(tableName, docId: 'TKey, conn) = 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) Custom.Single<'TDoc>(Query.byId (Query.find tableName) docId, [ idParam docId ], fromData<'TDoc>, conn)
/// Retrieve documents via a comparison on JSON fields /// <summary>Retrieve documents matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>All documents matching the given fields</returns>
[<CompiledName "FSharpByFields">] [<CompiledName "FSharpByFields">]
let byFields<'TDoc> tableName howMatched fields conn = let byFields<'TDoc> tableName howMatched fields conn =
Custom.list<'TDoc> Custom.list<'TDoc>
@ -370,7 +532,12 @@ module WithConn =
fromData<'TDoc> fromData<'TDoc>
conn conn
/// Retrieve documents via a comparison on JSON fields /// <summary>Retrieve documents matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>All documents matching the given fields</returns>
let ByFields<'TDoc>(tableName, howMatched, fields, conn) = let ByFields<'TDoc>(tableName, howMatched, fields, conn) =
Custom.List<'TDoc>( Custom.List<'TDoc>(
Query.byFields (Query.find tableName) howMatched fields, Query.byFields (Query.find tableName) howMatched fields,
@ -378,7 +545,16 @@ module WithConn =
fromData<'TDoc>, fromData<'TDoc>,
conn) conn)
/// Retrieve documents via a comparison on JSON fields ordered by the given fields in the document /// <summary>
/// Retrieve documents matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.) ordered by the given fields
/// in the document
/// </summary>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="queryFields">The field conditions to match</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>All documents matching the given fields, ordered by the other given fields</returns>
[<CompiledName "FSharpByFieldsOrdered">] [<CompiledName "FSharpByFieldsOrdered">]
let byFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields conn = let byFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields conn =
Custom.list<'TDoc> Custom.list<'TDoc>
@ -387,7 +563,16 @@ module WithConn =
fromData<'TDoc> fromData<'TDoc>
conn conn
/// Retrieve documents via a comparison on JSON fields ordered by the given fields in the document /// <summary>
/// Retrieve documents matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.) ordered by the given fields
/// in the document
/// </summary>
/// <param name="tableName">The table from which documents should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="queryFields">The field conditions to match</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>All documents matching the given fields, ordered by the other given fields</returns>
let ByFieldsOrdered<'TDoc>(tableName, howMatched, queryFields, orderFields, conn) = let ByFieldsOrdered<'TDoc>(tableName, howMatched, queryFields, orderFields, conn) =
Custom.List<'TDoc>( Custom.List<'TDoc>(
Query.byFields (Query.find tableName) howMatched queryFields + Query.orderBy orderFields SQLite, Query.byFields (Query.find tableName) howMatched queryFields + Query.orderBy orderFields SQLite,
@ -395,7 +580,12 @@ module WithConn =
fromData<'TDoc>, fromData<'TDoc>,
conn) conn)
/// Retrieve documents via a comparison on JSON fields, returning only the first result /// <summary>Retrieve the first document matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns><tt>Some</tt> with the first document, or <tt>None</tt> if not found</returns>
[<CompiledName "FSharpFirstByFields">] [<CompiledName "FSharpFirstByFields">]
let firstByFields<'TDoc> tableName howMatched fields conn = let firstByFields<'TDoc> tableName howMatched fields conn =
Custom.single Custom.single
@ -404,7 +594,12 @@ module WithConn =
fromData<'TDoc> fromData<'TDoc>
conn conn
/// Retrieve documents via a comparison on JSON fields, returning only the first result /// <summary>Retrieve the first document matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>The first document, or <tt>null</tt> if not found</returns>
let FirstByFields<'TDoc when 'TDoc: null and 'TDoc: not struct>(tableName, howMatched, fields, conn) = let FirstByFields<'TDoc when 'TDoc: null and 'TDoc: not struct>(tableName, howMatched, fields, conn) =
Custom.Single( Custom.Single(
$"{Query.byFields (Query.find tableName) howMatched fields} LIMIT 1", $"{Query.byFields (Query.find tableName) howMatched fields} LIMIT 1",
@ -412,8 +607,18 @@ module WithConn =
fromData<'TDoc>, fromData<'TDoc>,
conn) conn)
/// Retrieve documents via a comparison on JSON fields ordered by the given fields in the document, returning /// <summary>
/// only the first result /// Retrieve the first document matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.) ordered by the
/// given fields in the document
/// </summary>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="queryFields">The field conditions to match</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>
/// <tt>Some</tt> with the first document ordered by the given fields, or <tt>None</tt> if not found
/// </returns>
[<CompiledName "FSharpFirstByFieldsOrdered">] [<CompiledName "FSharpFirstByFieldsOrdered">]
let firstByFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields conn = let firstByFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields conn =
Custom.single Custom.single
@ -422,8 +627,16 @@ module WithConn =
fromData<'TDoc> fromData<'TDoc>
conn conn
/// Retrieve documents via a comparison on JSON fields ordered by the given fields in the document, returning /// <summary>
/// only the first result /// Retrieve the first document matching JSON field comparisons (<tt>-&gt;&gt; =</tt>, etc.) ordered by the
/// given fields in the document
/// </summary>
/// <param name="tableName">The table from which a document should be retrieved (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="queryFields">The field conditions to match</param>
/// <param name="orderFields">Fields by which the results should be ordered</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
/// <returns>The first document ordered by the given fields, or <tt>null</tt> if not found</returns>
let FirstByFieldsOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>( let FirstByFieldsOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>(
tableName, howMatched, queryFields, orderFields, conn) = tableName, howMatched, queryFields, orderFields, conn) =
Custom.Single( Custom.Single(
@ -432,38 +645,68 @@ module WithConn =
fromData<'TDoc>, fromData<'TDoc>,
conn) conn)
/// Commands to update documents /// <summary>Commands to update documents</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Update = module Update =
/// Update an entire document by its ID /// <summary>Update (replace) an entire document by its ID</summary>
/// <param name="tableName">The table in which a document should be updated (may include schema)</param>
/// <param name="docId">The ID of the document to be updated (replaced)</param>
/// <param name="document">The new document</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "ById">] [<CompiledName "ById">]
let byId tableName (docId: 'TKey) (document: 'TDoc) conn = let byId tableName (docId: 'TKey) (document: 'TDoc) conn =
Custom.nonQuery Custom.nonQuery
(Query.statementWhere (Query.update tableName) (Query.whereById "@id")) (Query.statementWhere (Query.update tableName) (Query.whereById docId))
[ idParam docId; jsonParam "@data" document ] [ idParam docId; jsonParam "@data" document ]
conn conn
/// Update an entire document by its ID, using the provided function to obtain the ID from the document /// <summary>
/// Update (replace) an entire document by its ID, using the provided function to obtain the ID from the
/// document
/// </summary>
/// <param name="tableName">The table in which a document should be updated (may include schema)</param>
/// <param name="idFunc">The function to obtain the ID of the document</param>
/// <param name="document">The new document</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "FSharpByFunc">] [<CompiledName "FSharpByFunc">]
let byFunc tableName (idFunc: 'TDoc -> 'TKey) (document: 'TDoc) conn = let byFunc tableName (idFunc: 'TDoc -> 'TKey) (document: 'TDoc) conn =
byId tableName (idFunc document) document conn byId tableName (idFunc document) document conn
/// Update an entire document by its ID, using the provided function to obtain the ID from the document /// <summary>
/// Update (replace) an entire document by its ID, using the provided function to obtain the ID from the
/// document
/// </summary>
/// <param name="tableName">The table in which a document should be updated (may include schema)</param>
/// <param name="idFunc">The function to obtain the ID of the document</param>
/// <param name="document">The new document</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
let ByFunc(tableName, idFunc: System.Func<'TDoc, 'TKey>, document: 'TDoc, conn) = let ByFunc(tableName, idFunc: System.Func<'TDoc, 'TKey>, document: 'TDoc, conn) =
byFunc tableName idFunc.Invoke document conn byFunc tableName idFunc.Invoke document conn
/// Commands to patch (partially update) documents /// <summary>Commands to patch (partially update) documents</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Patch = module Patch =
/// Patch a document by its ID /// <summary>Patch a document by its ID</summary>
/// <param name="tableName">The table in which a document should be patched (may include schema)</param>
/// <param name="docId">The ID of the document to patch</param>
/// <param name="patch">The partial document to patch the existing document</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "ById">] [<CompiledName "ById">]
let byId tableName (docId: 'TKey) (patch: 'TPatch) conn = let byId tableName (docId: 'TKey) (patch: 'TPatch) conn =
Custom.nonQuery Custom.nonQuery
(Query.byId (Query.patch tableName) docId) [ idParam docId; jsonParam "@data" patch ] conn (Query.byId (Query.patch tableName) docId) [ idParam docId; jsonParam "@data" patch ] conn
/// Patch documents using a comparison on JSON fields /// <summary>
/// Patch documents using a JSON field comparison query in the <tt>WHERE</tt> clause (<tt>-&gt;&gt; =</tt>,
/// etc.)
/// </summary>
/// <param name="tableName">The table in which documents should be patched (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="patch">The partial document to patch the existing document</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "ByFields">] [<CompiledName "ByFields">]
let byFields tableName howMatched fields (patch: 'TPatch) conn = let byFields tableName howMatched fields (patch: 'TPatch) conn =
Custom.nonQuery Custom.nonQuery
@ -471,11 +714,15 @@ module WithConn =
(addFieldParams fields [ jsonParam "@data" patch ]) (addFieldParams fields [ jsonParam "@data" patch ])
conn conn
/// Commands to remove fields from documents /// <summary>Commands to remove fields from documents</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module RemoveFields = module RemoveFields =
/// Remove fields from a document by the document's ID /// <summary>Remove fields from a document by the document's ID</summary>
/// <param name="tableName">The table in which a document should be modified (may include schema)</param>
/// <param name="docId">The ID of the document to modify</param>
/// <param name="fieldNames">One or more field names to remove from the document</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "ById">] [<CompiledName "ById">]
let byId tableName (docId: 'TKey) fieldNames conn = let byId tableName (docId: 'TKey) fieldNames conn =
let nameParams = fieldNameParams "@name" fieldNames let nameParams = fieldNameParams "@name" fieldNames
@ -484,7 +731,12 @@ module WithConn =
(idParam docId |> Seq.singleton |> Seq.append nameParams) (idParam docId |> Seq.singleton |> Seq.append nameParams)
conn conn
/// Remove fields from documents via a comparison on JSON fields in the document /// <summary>Remove fields from documents via a comparison on JSON fields in the document</summary>
/// <param name="tableName">The table in which documents should be modified (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="fieldNames">One or more field names to remove from the matching documents</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "ByFields">] [<CompiledName "ByFields">]
let byFields tableName howMatched fields fieldNames conn = let byFields tableName howMatched fields fieldNames conn =
let nameParams = fieldNameParams "@name" fieldNames let nameParams = fieldNameParams "@name" fieldNames
@ -497,57 +749,90 @@ module WithConn =
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Delete = module Delete =
/// Delete a document by its ID /// <summary>Delete a document by its ID</summary>
/// <param name="tableName">The table in which a document should be deleted (may include schema)</param>
/// <param name="docId">The ID of the document to delete</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "ById">] [<CompiledName "ById">]
let byId tableName (docId: 'TKey) conn = let byId tableName (docId: 'TKey) conn =
Custom.nonQuery (Query.byId (Query.delete tableName) docId) [ idParam docId ] conn Custom.nonQuery (Query.byId (Query.delete tableName) docId) [ idParam docId ] conn
/// Delete documents by matching a comparison on JSON fields /// <summary>Delete documents by matching a JSON field comparison query (<tt>-&gt;&gt; =</tt>, etc.)</summary>
/// <param name="tableName">The table in which documents should be deleted (may include schema)</param>
/// <param name="howMatched">Whether to match any or all of the field conditions</param>
/// <param name="fields">The field conditions to match</param>
/// <param name="conn">The <tt>SqliteConnection</tt> to use to execute the query</param>
[<CompiledName "ByFields">] [<CompiledName "ByFields">]
let byFields tableName howMatched fields conn = let byFields tableName howMatched fields conn =
Custom.nonQuery (Query.byFields (Query.delete tableName) howMatched fields) (addFieldParams fields []) conn Custom.nonQuery (Query.byFields (Query.delete tableName) howMatched fields) (addFieldParams fields []) conn
/// Commands to execute custom SQL queries /// <summary>Commands to execute custom SQL queries</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Custom = module Custom =
/// Execute a query that returns a list of results /// <summary>Execute a query that returns a list of results</summary>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function between the document and the domain item</param>
/// <returns>A list of results for the given query</returns>
[<CompiledName "FSharpList">] [<CompiledName "FSharpList">]
let list<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) = let list<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) =
use conn = Configuration.dbConn () use conn = Configuration.dbConn ()
WithConn.Custom.list<'TDoc> query parameters mapFunc conn WithConn.Custom.list<'TDoc> query parameters mapFunc conn
/// Execute a query that returns a list of results /// <summary>Execute a query that returns a list of results</summary>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function between the document and the domain item</param>
/// <returns>A list of results for the given query</returns>
let List<'TDoc>(query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>) = let List<'TDoc>(query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>) =
use conn = Configuration.dbConn () use conn = Configuration.dbConn ()
WithConn.Custom.List<'TDoc>(query, parameters, mapFunc, conn) WithConn.Custom.List<'TDoc>(query, parameters, mapFunc, conn)
/// Execute a query that returns one or no results (returns None if not found) /// <summary>Execute a query that returns one or no results</summary>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function between the document and the domain item</param>
/// <returns><tt>Some</tt> with the first matching result, or <tt>None</tt> if not found</returns>
[<CompiledName "FSharpSingle">] [<CompiledName "FSharpSingle">]
let single<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) = let single<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) =
use conn = Configuration.dbConn () use conn = Configuration.dbConn ()
WithConn.Custom.single<'TDoc> query parameters mapFunc conn WithConn.Custom.single<'TDoc> query parameters mapFunc conn
/// Execute a query that returns one or no results (returns null if not found) /// <summary>Execute a query that returns one or no results</summary>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function between the document and the domain item</param>
/// <returns>The first matching result, or <tt>null</tt> if not found</returns>
let Single<'TDoc when 'TDoc: null and 'TDoc: not struct>( let Single<'TDoc when 'TDoc: null and 'TDoc: not struct>(
query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>) = query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>) =
use conn = Configuration.dbConn () use conn = Configuration.dbConn ()
WithConn.Custom.Single<'TDoc>(query, parameters, mapFunc, conn) WithConn.Custom.Single<'TDoc>(query, parameters, mapFunc, conn)
/// Execute a query that does not return a value /// <summary>Execute a query that returns no results</summary>
/// <param name="query">The query to retrieve the results</param>
/// <param name="parameters">Parameters to use for the query</param>
[<CompiledName "NonQuery">] [<CompiledName "NonQuery">]
let nonQuery query parameters = let nonQuery query parameters =
use conn = Configuration.dbConn () use conn = Configuration.dbConn ()
WithConn.Custom.nonQuery query parameters conn WithConn.Custom.nonQuery query parameters conn
/// Execute a query that returns a scalar value /// <summary>Execute a query that returns a scalar value</summary>
/// <param name="query">The query to retrieve the value</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function to obtain the value</param>
/// <returns>The scalar value for the query</returns>
[<CompiledName "FSharpScalar">] [<CompiledName "FSharpScalar">]
let scalar<'T when 'T: struct> query parameters (mapFunc: SqliteDataReader -> 'T) = let scalar<'T when 'T: struct> query parameters (mapFunc: SqliteDataReader -> 'T) =
use conn = Configuration.dbConn () use conn = Configuration.dbConn ()
WithConn.Custom.scalar<'T> query parameters mapFunc conn WithConn.Custom.scalar<'T> query parameters mapFunc conn
/// Execute a query that returns a scalar value /// <summary>Execute a query that returns a scalar value</summary>
/// <param name="query">The query to retrieve the value</param>
/// <param name="parameters">Parameters to use for the query</param>
/// <param name="mapFunc">The mapping function to obtain the value</param>
/// <returns>The scalar value for the query</returns>
let Scalar<'T when 'T: struct>(query, parameters, mapFunc: System.Func<SqliteDataReader, 'T>) = let Scalar<'T when 'T: struct>(query, parameters, mapFunc: System.Func<SqliteDataReader, 'T>) =
use conn = Configuration.dbConn () use conn = Configuration.dbConn ()
WithConn.Custom.Scalar<'T>(query, parameters, mapFunc, conn) WithConn.Custom.Scalar<'T>(query, parameters, mapFunc, conn)

View File

@ -75,7 +75,7 @@ public static class SqliteCSharpTests
]), ]),
TestCase("WhereById succeeds", () => TestCase("WhereById succeeds", () =>
{ {
Expect.equal(Sqlite.Query.WhereById("@id"), "data->>'Id' = @id", "WHERE clause not correct"); Expect.equal(Sqlite.Query.WhereById("abc"), "data->>'Id' = @id", "WHERE clause not correct");
}), }),
TestCase("Patch succeeds", () => TestCase("Patch succeeds", () =>
{ {

View File

@ -65,7 +65,7 @@ let queryTests = testList "Query" [
} }
] ]
test "whereById succeeds" { test "whereById succeeds" {
Expect.equal (Query.whereById "@id") "data->>'Id' = @id" "WHERE clause not correct" Expect.equal (Query.whereById "abc") "data->>'Id' = @id" "WHERE clause not correct"
} }
test "patch succeeds" { test "patch succeeds" {
Expect.equal Expect.equal