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 WithProps
/// F# Extensions for the NpgsqlConnection type
/// <summary>F# Extensions for the NpgsqlConnection type</summary>
[<AutoOpen>]
module Extensions =
@ -377,247 +377,455 @@ module Extensions =
open System.Runtime.CompilerServices
/// C# extensions on the NpgsqlConnection type
/// <summary>C# extensions on the NpgsqlConnection type</summary>
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>]
static member inline CustomList<'TDoc>(conn, query, parameters, mapFunc: System.Func<RowReader, 'TDoc>) =
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>]
static member inline CustomSingle<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, query, parameters, mapFunc: System.Func<RowReader, 'TDoc>) =
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>]
static member inline CustomNonQuery(conn, query, parameters) =
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>]
static member inline CustomScalar<'T when 'T: struct>(
conn, query, parameters, mapFunc: System.Func<RowReader, 'T>) =
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>]
static member inline EnsureTable(conn, name) =
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>]
static member inline EnsureDocumentIndex(conn, name, idxType) =
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>]
static member inline EnsureFieldIndex(conn, tableName, indexName, fields) =
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>]
static member inline Insert<'TDoc>(conn, tableName, document: 'TDoc) =
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>]
static member inline Save<'TDoc>(conn, tableName, document: 'TDoc) =
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>]
static member inline CountAll(conn, tableName) =
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>]
static member inline CountByFields(conn, tableName, howMatched, fields) =
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>]
static member inline CountByContains(conn, tableName, criteria: 'TCriteria) =
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>]
static member inline CountByJsonPath(conn, tableName, jsonPath) =
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>]
static member inline ExistsById(conn, tableName, docId) =
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>]
static member inline ExistsByFields(conn, tableName, howMatched, fields) =
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>]
static member inline ExistsByContains(conn, tableName, criteria: 'TCriteria) =
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>]
static member inline ExistsByJsonPath(conn, tableName, jsonPath) =
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>]
static member inline FindAll<'TDoc>(conn, tableName) =
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>]
static member inline FindAllOrdered<'TDoc>(conn, tableName, orderFields) =
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>]
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)
/// 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>]
static member inline FindByFields<'TDoc>(conn, tableName, howMatched, fields) =
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>]
static member inline FindByFieldsOrdered<'TDoc>(conn, tableName, howMatched, queryFields, orderFields) =
Find.ByFieldsOrdered<'TDoc>(
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>]
static member inline FindByContains<'TDoc>(conn, tableName, criteria: obj) =
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>]
static member inline FindByContainsOrdered<'TDoc>(conn, tableName, criteria: obj, orderFields) =
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>]
static member inline FindByJsonPath<'TDoc>(conn, tableName, jsonPath) =
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>]
static member inline FindByJsonPathOrdered<'TDoc>(conn, tableName, jsonPath, orderFields) =
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>]
static member inline FindFirstByFields<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, tableName, howMatched, fields) =
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
/// document; returns null if not found
/// <summary>
/// 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>]
static member inline FindFirstByFieldsOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, tableName, howMatched, queryFields, orderFields) =
Find.FirstByFieldsOrdered<'TDoc>(
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>]
static member inline FindFirstByContains<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, tableName, criteria: obj) =
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;
/// returns None if not found
/// <summary>
/// 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>]
static member inline FindFirstByContainsOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, tableName, criteria: obj, orderFields) =
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>]
static member inline FindFirstByJsonPath<'TDoc when 'TDoc: null and 'TDoc: not struct>(conn, tableName, jsonPath) =
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;
/// returns None if not found
/// <summary>
/// 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>]
static member inline FindFirstByJsonPathOrdered<'TDoc when 'TDoc: null and 'TDoc: not struct>(
conn, tableName, jsonPath, orderFields) =
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>]
static member inline UpdateById(conn, tableName, docId: 'TKey, document: 'TDoc) =
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>]
static member inline UpdateByFunc(conn, tableName, idFunc: System.Func<'TDoc, 'TKey>, document: 'TDoc) =
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>]
static member inline PatchById(conn, tableName, docId: 'TKey, patch: 'TPatch) =
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>]
static member inline PatchByFields(conn, tableName, howMatched, fields, patch: 'TPatch) =
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>]
static member inline PatchByContains(conn, tableName, criteria: 'TCriteria, patch: 'TPatch) =
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>]
static member inline PatchByJsonPath(conn, tableName, jsonPath, patch: 'TPatch) =
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>]
static member inline RemoveFieldsById(conn, tableName, docId: 'TKey, fieldNames) =
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>]
static member inline RemoveFieldsByFields(conn, tableName, howMatched, fields, fieldNames) =
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>]
static member inline RemoveFieldsByContains(conn, tableName, criteria: 'TContains, fieldNames) =
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>]
static member inline RemoveFieldsByJsonPath(conn, tableName, jsonPath, fieldNames) =
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>]
static member inline DeleteById(conn, tableName, docId: 'TKey) =
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>]
static member inline DeleteByFields(conn, tableName, howMatched, fields) =
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>]
static member inline DeleteByContains(conn, tableName, criteria: 'TContains) =
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>]
static member inline DeleteByJsonPath(conn, tableName, path) =
Delete.byJsonPath tableName path (Sql.existingConnection conn)
static member inline DeleteByJsonPath(conn, tableName, jsonPath) =
Delete.byJsonPath tableName jsonPath (Sql.existingConnection conn)

View File

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

View File

@ -3,20 +3,25 @@
open BitBadger.Documents
open Microsoft.Data.Sqlite
/// Configuration for document handling
/// <summary>Configuration for document handling</summary>
module Configuration =
/// The connection string to use for query execution
let mutable internal connectionString: string option = None
/// Register a connection string to use for query execution (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">]
let useConnectionString connStr =
let builder = SqliteConnectionStringBuilder connStr
builder.ForeignKeys <- Option.toNullable (Some true)
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">]
let dbConn () =
match connectionString with
@ -27,11 +32,16 @@ module Configuration =
| None -> invalidOp "Please provide a connection string before attempting data access"
/// Query definitions
/// <summary>Query definitions</summary>
[<RequireQualifiedAccess>]
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">]
let whereByFields (howMatched: FieldMatch) fields =
let name = ParameterName()
@ -53,58 +63,82 @@ module Query =
| _ -> $"{it.Path SQLite AsSql} {it.Comparison.OpSql} {name.Derive it.ParameterName}")
|> String.concat $" {howMatched} "
/// Create a WHERE clause fragment to implement an ID-based query
/// <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">]
let whereById paramName =
whereByFields Any [ { Field.Equal (Configuration.idField ()) 0 with ParameterName = Some paramName } ]
let whereById (docId: 'TKey) =
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">]
let patch tableName =
$"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">]
let removeFields tableName (parameters: SqliteParameter seq) =
let paramNames = parameters |> Seq.map _.ParameterName |> String.concat ", "
$"UPDATE %s{tableName} SET data = json_remove(data, {paramNames})"
/// Create a query by a document's ID
/// <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">]
let byId<'TKey> statement (docId: 'TKey) =
Query.statementWhere
statement
(whereByFields Any [ { Field.Equal (Configuration.idField ()) docId with ParameterName = Some "@id" } ])
/// Create a query on JSON fields
/// <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">]
let byFields statement howMatched fields =
Query.statementWhere statement (whereByFields howMatched fields)
/// Data definition
/// <summary>Data definition</summary>
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">]
let ensureTable name =
Query.Definition.ensureTableFor name "TEXT"
/// Parameter handling helpers
/// <summary>Parameter handling helpers</summary>
[<AutoOpen>]
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">]
let idParam (key: 'TKey) =
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">]
let jsonParam name (it: 'TJson) =
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">]
let addFieldParams fields parameters =
let name = ParameterName()
@ -132,7 +166,10 @@ module Parameters =
let addFieldParam name field parameters =
addFieldParams [ { field with ParameterName = Some name } ] parameters
/// Append JSON field name parameters for the given field names to the given parameters
/// <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">]
let fieldNameParams paramName fieldNames =
fieldNames
@ -140,27 +177,37 @@ module Parameters =
|> Seq.toList
|> Seq.ofList
/// An empty parameter sequence
/// <summary>An empty parameter sequence</summary>
[<CompiledName "None">]
let noParams =
Seq.empty<SqliteParameter>
/// Helper functions for handling results
/// <summary>Helper functions for handling results</summary>
[<AutoOpen>]
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">]
let fromDocument<'TDoc> field (rdr: SqliteDataReader) : 'TDoc =
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">]
let fromData<'TDoc> rdr =
fromDocument<'TDoc> "data" rdr
/// <summary>
/// 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">]
let toCustomList<'TDoc> (cmd: SqliteCommand) (mapFunc: SqliteDataReader -> 'TDoc) = backgroundTask {
use! rdr = cmd.ExecuteReaderAsync()
@ -170,35 +217,60 @@ module Results =
return List.ofSeq it
}
/// Extract a count from the first column
[<CompiledName "ToCount">]
let toCount (row: SqliteDataReader) =
row.GetInt64 0
/// <summary>
/// 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>
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">]
let toExists row =
toCount(row) > 0L
let toExists rdr =
toCount rdr > 0L
[<AutoOpen>]
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! _ = 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 =
/// Commands to execute custom SQL queries
/// <summary>Commands to execute custom SQL queries</summary>
[<RequireQualifiedAccess>]
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">]
let list<'TDoc> query (parameters: SqliteParameter seq) (mapFunc: SqliteDataReader -> 'TDoc)
(conn: SqliteConnection) =
@ -207,20 +279,39 @@ module WithConn =
cmd.Parameters.AddRange parameters
toCustomList<'TDoc> cmd mapFunc
/// Execute a query that returns a list of results
let List<'TDoc>(query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>, conn) = backgroundTask {
let! results = list<'TDoc> query parameters mapFunc.Invoke conn
return ResizeArray<'TDoc> 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>
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">]
let single<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) conn = backgroundTask {
let! results = list query parameters mapFunc conn
return FSharp.Collections.List.tryHead results
}
/// Execute a query that returns one or no results (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>(
query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>, conn
) = backgroundTask {
@ -228,7 +319,10 @@ module WithConn =
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">]
let nonQuery query (parameters: SqliteParameter seq) (conn: SqliteConnection) =
use cmd = conn.CreateCommand()
@ -236,7 +330,12 @@ module WithConn =
cmd.Parameters.AddRange parameters
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">]
let scalar<'T when 'T : struct> query (parameters: SqliteParameter seq) (mapFunc: SqliteDataReader -> 'T)
(conn: SqliteConnection) = backgroundTask {
@ -248,31 +347,45 @@ module WithConn =
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) =
scalar<'T> query parameters mapFunc.Invoke conn
/// Functions to create tables and indexes
/// <summary>Functions to create tables and indexes</summary>
[<RequireQualifiedAccess>]
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">]
let ensureTable name conn = backgroundTask {
do! Custom.nonQuery (Query.Definition.ensureTable name) [] conn
do! Custom.nonQuery (Query.Definition.ensureKey name SQLite) [] conn
}
/// Create an index on 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">]
let ensureFieldIndex tableName indexName fields conn =
Custom.nonQuery (Query.Definition.ensureIndexOn tableName indexName fields SQLite) [] conn
/// Commands to add documents
/// <summary>Commands to add documents</summary>
[<AutoOpen>]
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">]
let insert<'TDoc> tableName (document: 'TDoc) conn =
let query =
@ -292,36 +405,58 @@ module WithConn =
(Query.insert tableName).Replace("@data", dataParam)
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")
/// </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">]
let save<'TDoc> tableName (document: 'TDoc) conn =
Custom.nonQuery (Query.save tableName) [ jsonParam "@data" document ] conn
/// Commands to count documents
/// <summary>Commands to count documents</summary>
[<RequireQualifiedAccess>]
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">]
let all tableName 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">]
let byFields tableName howMatched fields conn =
Custom.scalar
(Query.byFields (Query.count tableName) howMatched fields) (addFieldParams fields []) toCount conn
/// Commands to determine if documents exist
/// <summary>Commands to determine if documents exist</summary>
[<RequireQualifiedAccess>]
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">]
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">]
let byFields tableName howMatched fields conn =
Custom.scalar
@ -330,38 +465,65 @@ module WithConn =
toExists
conn
/// Commands to retrieve documents
/// <summary>Commands to retrieve documents</summary>
[<RequireQualifiedAccess>]
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">]
let all<'TDoc> tableName 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) =
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">]
let allOrdered<'TDoc> tableName orderFields conn =
Custom.list<'TDoc> (Query.find tableName + Query.orderBy orderFields SQLite) [] fromData<'TDoc> conn
/// Retrieve all documents in the given table ordered by the given fields in the document
/// <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) =
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">]
let byId<'TKey, 'TDoc> tableName (docId: 'TKey) conn =
Custom.single<'TDoc> (Query.byId (Query.find tableName) docId) [ idParam docId ] fromData<'TDoc> conn
/// Retrieve a document by its ID (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) =
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">]
let byFields<'TDoc> tableName howMatched fields conn =
Custom.list<'TDoc>
@ -370,7 +532,12 @@ module WithConn =
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>
let ByFields<'TDoc>(tableName, howMatched, fields, conn) =
Custom.List<'TDoc>(
Query.byFields (Query.find tableName) howMatched fields,
@ -378,7 +545,16 @@ module WithConn =
fromData<'TDoc>,
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">]
let byFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields conn =
Custom.list<'TDoc>
@ -387,7 +563,16 @@ module WithConn =
fromData<'TDoc>
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) =
Custom.List<'TDoc>(
Query.byFields (Query.find tableName) howMatched queryFields + Query.orderBy orderFields SQLite,
@ -395,7 +580,12 @@ module WithConn =
fromData<'TDoc>,
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">]
let firstByFields<'TDoc> tableName howMatched fields conn =
Custom.single
@ -404,7 +594,12 @@ module WithConn =
fromData<'TDoc>
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) =
Custom.Single(
$"{Query.byFields (Query.find tableName) howMatched fields} LIMIT 1",
@ -412,8 +607,18 @@ module WithConn =
fromData<'TDoc>,
conn)
/// Retrieve documents via a comparison on JSON fields ordered by the given fields in the document, returning
/// only the first result
/// <summary>
/// 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">]
let firstByFieldsOrdered<'TDoc> tableName howMatched queryFields orderFields conn =
Custom.single
@ -422,8 +627,16 @@ module WithConn =
fromData<'TDoc>
conn
/// Retrieve documents via a comparison on JSON fields ordered by the given fields in the document, returning
/// only the first result
/// <summary>
/// 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>(
tableName, howMatched, queryFields, orderFields, conn) =
Custom.Single(
@ -432,38 +645,68 @@ module WithConn =
fromData<'TDoc>,
conn)
/// Commands to update documents
/// <summary>Commands to update documents</summary>
[<RequireQualifiedAccess>]
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">]
let byId tableName (docId: 'TKey) (document: 'TDoc) conn =
Custom.nonQuery
(Query.statementWhere (Query.update tableName) (Query.whereById "@id"))
(Query.statementWhere (Query.update tableName) (Query.whereById docId))
[ idParam docId; jsonParam "@data" 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>
[<CompiledName "FSharpByFunc">]
let byFunc tableName (idFunc: 'TDoc -> 'TKey) (document: 'TDoc) 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) =
byFunc tableName idFunc.Invoke document conn
/// Commands to patch (partially update) documents
/// <summary>Commands to patch (partially update) documents</summary>
[<RequireQualifiedAccess>]
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">]
let byId tableName (docId: 'TKey) (patch: 'TPatch) conn =
Custom.nonQuery
(Query.byId (Query.patch tableName) docId) [ idParam docId; jsonParam "@data" patch ] conn
/// Patch documents using a 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">]
let byFields tableName howMatched fields (patch: 'TPatch) conn =
Custom.nonQuery
@ -471,11 +714,15 @@ module WithConn =
(addFieldParams fields [ jsonParam "@data" patch ])
conn
/// Commands to remove fields from documents
/// <summary>Commands to remove fields from documents</summary>
[<RequireQualifiedAccess>]
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">]
let byId tableName (docId: 'TKey) fieldNames conn =
let nameParams = fieldNameParams "@name" fieldNames
@ -484,7 +731,12 @@ module WithConn =
(idParam docId |> Seq.singleton |> Seq.append nameParams)
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">]
let byFields tableName howMatched fields fieldNames conn =
let nameParams = fieldNameParams "@name" fieldNames
@ -497,57 +749,90 @@ module WithConn =
[<RequireQualifiedAccess>]
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">]
let byId tableName (docId: 'TKey) 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">]
let byFields tableName howMatched 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>]
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">]
let list<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Custom.list<'TDoc> query parameters mapFunc conn
/// Execute a query that returns a list of results
/// <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>) =
use conn = Configuration.dbConn ()
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">]
let single<'TDoc> query parameters (mapFunc: SqliteDataReader -> 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Custom.single<'TDoc> query parameters mapFunc conn
/// Execute a query that returns one or no results (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>(
query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>) =
use conn = Configuration.dbConn ()
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">]
let nonQuery query parameters =
use conn = Configuration.dbConn ()
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">]
let scalar<'T when 'T: struct> query parameters (mapFunc: SqliteDataReader -> 'T) =
use conn = Configuration.dbConn ()
WithConn.Custom.scalar<'T> query parameters mapFunc conn
/// Execute a query that returns a scalar value
/// <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>) =
use conn = Configuration.dbConn ()
WithConn.Custom.Scalar<'T>(query, parameters, mapFunc, conn)

View File

@ -75,7 +75,7 @@ public static class SqliteCSharpTests
]),
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", () =>
{

View File

@ -65,7 +65,7 @@ let queryTests = testList "Query" [
}
]
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" {
Expect.equal