This encompasses:
- New behavior for SQLite
- Migrated behavior for PostrgeSQL (from BitBadger.Npgsql.FSharp.Documents)
- New "byField" behavior for PostgreSQL
- A unification of C# and F# centric implementations
This commit was merged in pull request #1.
This commit is contained in:
2024-01-06 15:51:48 -05:00
committed by GitHub
parent a0a4f6604c
commit 68ad874256
36 changed files with 8604 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<PackageReleaseNotes>Initial release; SQLite document implementation similar to BitBadger.Npgsql.Documents (RC 1)</PackageReleaseNotes>
<PackageTags>JSON Document SQLite</PackageTags>
</PropertyGroup>
<ItemGroup>
<Compile Include="Library.fs" />
<Compile Include="Extensions.fs" />
<None Include="README.md" Pack="true" PackagePath="\" />
<None Include="..\icon.png" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>BitBadger.Documents.Tests</_Parameter1>
</AssemblyAttribute>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>BitBadger.Documents.Tests.CSharp</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\BitBadger.Documents.Common.fsproj" />
</ItemGroup>
</Project>

215
src/Sqlite/Extensions.fs Normal file
View File

@@ -0,0 +1,215 @@
namespace BitBadger.Documents.Sqlite
open Microsoft.Data.Sqlite
/// F# extensions for the SqliteConnection type
[<AutoOpen>]
module Extensions =
type SqliteConnection with
/// Execute a query that returns a list of results
member conn.customList<'TDoc> query parameters mapFunc =
WithConn.Custom.list<'TDoc> query parameters mapFunc conn
/// Execute a query that returns one or no results
member conn.customSingle<'TDoc> query parameters mapFunc =
WithConn.Custom.single<'TDoc> query parameters mapFunc conn
/// Execute a query that does not return a value
member conn.customNonQuery query parameters =
WithConn.Custom.nonQuery query parameters conn
/// Execute a query that returns a scalar value
member conn.customScalar<'T when 'T: struct> query parameters mapFunc =
WithConn.Custom.scalar<'T> query parameters mapFunc conn
/// Create a document table
member conn.ensureTable name =
WithConn.Definition.ensureTable name conn
/// Create an index on a document table
member conn.ensureFieldIndex tableName indexName fields =
WithConn.Definition.ensureFieldIndex tableName indexName fields conn
/// Insert a new document
member conn.insert<'TDoc> tableName (document: 'TDoc) =
WithConn.insert<'TDoc> tableName document conn
/// Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
member conn.save<'TDoc> tableName (document: 'TDoc) =
WithConn.save tableName document conn
/// Count all documents in a table
member conn.countAll tableName =
WithConn.Count.all tableName conn
/// Count matching documents using a comparison on a JSON field
member conn.countByField tableName fieldName op (value: obj) =
WithConn.Count.byField tableName fieldName op value conn
/// Determine if a document exists for the given ID
member conn.existsById tableName (docId: 'TKey) =
WithConn.Exists.byId tableName docId conn
/// Determine if a document exists using a comparison on a JSON field
member conn.existsByField tableName fieldName op (value: obj) =
WithConn.Exists.byField tableName fieldName op value conn
/// Retrieve all documents in the given table
member conn.findAll<'TDoc> tableName =
WithConn.Find.all<'TDoc> tableName conn
/// Retrieve a document by its ID
member conn.findById<'TKey, 'TDoc> tableName (docId: 'TKey) =
WithConn.Find.byId<'TKey, 'TDoc> tableName docId conn
/// Retrieve documents via a comparison on a JSON field
member conn.findByField<'TDoc> tableName fieldName op (value: obj) =
WithConn.Find.byField<'TDoc> tableName fieldName op value conn
/// Retrieve documents via a comparison on a JSON field, returning only the first result
member conn.findFirstByField<'TDoc> tableName fieldName op (value: obj) =
WithConn.Find.firstByField<'TDoc> tableName fieldName op value conn
/// Update an entire document by its ID
member conn.updateById tableName (docId: 'TKey) (document: 'TDoc) =
WithConn.Update.byId tableName docId document conn
/// Update an entire document by its ID, using the provided function to obtain the ID from the document
member conn.updateByFunc tableName (idFunc: 'TDoc -> 'TKey) (document: 'TDoc) =
WithConn.Update.byFunc tableName idFunc document conn
/// Patch a document by its ID
member conn.patchById tableName (docId: 'TKey) (patch: 'TPatch) =
WithConn.Patch.byId tableName docId patch conn
/// Patch documents using a comparison on a JSON field
member conn.patchByField tableName fieldName op (value: obj) (patch: 'TPatch) =
WithConn.Patch.byField tableName fieldName op value patch conn
/// Delete a document by its ID
member conn.deleteById tableName (docId: 'TKey) =
WithConn.Delete.byId tableName docId conn
/// Delete documents by matching a comparison on a JSON field
member conn.deleteByField tableName fieldName op (value: obj) =
WithConn.Delete.byField tableName fieldName op value conn
open System.Runtime.CompilerServices
/// C# extensions on the SqliteConnection type
type SqliteConnectionCSharpExtensions =
/// Execute a query that returns a list of results
[<Extension>]
static member inline CustomList<'TDoc>(conn, query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>) =
WithConn.Custom.List<'TDoc>(query, parameters, mapFunc, conn)
/// Execute a query that returns one or no results
[<Extension>]
static member inline CustomSingle<'TDoc when 'TDoc: null>(
conn, query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>) =
WithConn.Custom.Single<'TDoc>(query, parameters, mapFunc, conn)
/// Execute a query that does not return a value
[<Extension>]
static member inline CustomNonQuery(conn, query, parameters) =
WithConn.Custom.nonQuery query parameters conn
/// Execute a query that returns a scalar value
[<Extension>]
static member inline CustomScalar<'T when 'T: struct>(
conn, query, parameters, mapFunc: System.Func<SqliteDataReader, 'T>) =
WithConn.Custom.Scalar<'T>(query, parameters, mapFunc, conn)
/// Create a document table
[<Extension>]
static member inline EnsureTable(conn, name) =
WithConn.Definition.ensureTable name conn
/// Create an index on one or more fields in a document table
[<Extension>]
static member inline EnsureFieldIndex(conn, tableName, indexName, fields) =
WithConn.Definition.ensureFieldIndex tableName indexName fields conn
/// Insert a new document
[<Extension>]
static member inline Insert<'TDoc>(conn, tableName, document: 'TDoc) =
WithConn.insert<'TDoc> tableName document conn
/// Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
[<Extension>]
static member inline Save<'TDoc>(conn, tableName, document: 'TDoc) =
WithConn.save<'TDoc> tableName document conn
/// Count all documents in a table
[<Extension>]
static member inline CountAll(conn, tableName) =
WithConn.Count.all tableName conn
/// Count matching documents using a comparison on a JSON field
[<Extension>]
static member inline CountByField(conn, tableName, fieldName, op, value: obj) =
WithConn.Count.byField tableName fieldName op value conn
/// Determine if a document exists for the given ID
[<Extension>]
static member inline ExistsById<'TKey>(conn, tableName, docId: 'TKey) =
WithConn.Exists.byId tableName docId conn
/// Determine if a document exists using a comparison on a JSON field
[<Extension>]
static member inline ExistsByField(conn, tableName, fieldName, op, value: obj) =
WithConn.Exists.byField tableName fieldName op value conn
/// Retrieve all documents in the given table
[<Extension>]
static member inline FindAll<'TDoc>(conn, tableName) =
WithConn.Find.All<'TDoc>(tableName, conn)
/// Retrieve a document by its ID
[<Extension>]
static member inline FindById<'TKey, 'TDoc when 'TDoc: null>(conn, tableName, docId: 'TKey) =
WithConn.Find.ById<'TKey, 'TDoc>(tableName, docId, conn)
/// Retrieve documents via a comparison on a JSON field
[<Extension>]
static member inline FindByField<'TDoc>(conn, tableName, fieldName, op, value) =
WithConn.Find.ByField<'TDoc>(tableName, fieldName, op, value, conn)
/// Retrieve documents via a comparison on a JSON field, returning only the first result
[<Extension>]
static member inline FindFirstByField<'TDoc when 'TDoc: null>(conn, tableName, fieldName, op, value: obj) =
WithConn.Find.FirstByField<'TDoc>(tableName, fieldName, op, value, conn)
/// Update an entire document by its ID
[<Extension>]
static member inline UpdateById<'TKey, 'TDoc>(conn, tableName, docId: 'TKey, document: 'TDoc) =
WithConn.Update.byId tableName docId document conn
/// Update an entire document by its ID, using the provided function to obtain the ID from the document
[<Extension>]
static member inline UpdateByFunc<'TKey, 'TDoc>(conn, tableName, idFunc: System.Func<'TDoc, 'TKey>, doc: 'TDoc) =
WithConn.Update.ByFunc(tableName, idFunc, doc, conn)
/// Patch a document by its ID
[<Extension>]
static member inline PatchById<'TKey, 'TPatch>(conn, tableName, docId: 'TKey, patch: 'TPatch) =
WithConn.Patch.byId tableName docId patch conn
/// Patch documents using a comparison on a JSON field
[<Extension>]
static member inline PatchByField<'TPatch>(conn, tableName, fieldName, op, value: obj, patch: 'TPatch) =
WithConn.Patch.byField tableName fieldName op value patch conn
/// Delete a document by its ID
[<Extension>]
static member inline DeleteById<'TKey>(conn, tableName, docId: 'TKey) =
WithConn.Delete.byId tableName docId conn
/// Delete documents by matching a comparison on a JSON field
[<Extension>]
static member inline DeleteByField(conn, tableName, fieldName, op, value: obj) =
WithConn.Delete.byField tableName fieldName op value conn

539
src/Sqlite/Library.fs Normal file
View File

@@ -0,0 +1,539 @@
namespace BitBadger.Documents.Sqlite
open BitBadger.Documents
open Microsoft.Data.Sqlite
/// Configuration for document handling
module Configuration =
/// The connection string to use for query execution
let mutable internal connectionString: string option = None
/// Register a connection string to use for query execution (enables foreign keys)
[<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
[<CompiledName "DbConn">]
let dbConn () =
match connectionString with
| Some connStr ->
let conn = new SqliteConnection(connStr)
conn.Open()
conn
| None -> invalidOp "Please provide a connection string before attempting data access"
/// Query definitions
[<RequireQualifiedAccess>]
module Query =
/// Data definition
module Definition =
/// SQL statement to create a document table
[<CompiledName "EnsureTable">]
let ensureTable name =
Query.Definition.ensureTableFor name "TEXT"
/// Document patching (partial update) queries
module Patch =
/// Query to patch (partially update) a document by its ID
[<CompiledName "ById">]
let byId tableName =
$"""UPDATE %s{tableName} SET data = json_patch(data, json(@data)) WHERE {Query.whereById "@id"}"""
/// Query to patch (partially update) a document via a comparison on a JSON field
[<CompiledName "ByField">]
let byField tableName fieldName op =
sprintf
"UPDATE %s SET data = json_patch(data, json(@data)) WHERE %s"
tableName (Query.whereByField fieldName op "@field")
/// Parameter handling helpers
[<AutoOpen>]
module Parameters =
/// Create an ID parameter (name "@id", key will be treated as a string)
[<CompiledName "Id">]
let idParam (key: 'TKey) =
SqliteParameter("@id", string key)
/// Create a parameter with a JSON value
[<CompiledName "Json">]
let jsonParam name (it: 'TJson) =
SqliteParameter(name, Configuration.serializer().Serialize it)
/// Create a JSON field parameter (name "@field")
[<CompiledName "Field">]
let fieldParam (value: obj) =
SqliteParameter("@field", value)
/// An empty parameter sequence
[<CompiledName "None">]
let noParams =
Seq.empty<SqliteParameter>
/// Helper functions for handling results
[<AutoOpen>]
module Results =
/// Create a domain item from a document, specifying the field in which the document is found
[<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
[<CompiledName "FromData">]
let fromData<'TDoc> rdr =
fromDocument<'TDoc> "data" rdr
/// Create a list of items for the results of the given command, using the specified mapping function
[<CompiledName "FSharpToCustomList">]
let toCustomList<'TDoc> (cmd: SqliteCommand) (mapFunc: SqliteDataReader -> 'TDoc) = backgroundTask {
use! rdr = cmd.ExecuteReaderAsync()
let mutable it = Seq.empty<'TDoc>
while! rdr.ReadAsync() do
it <- Seq.append it (Seq.singleton (mapFunc rdr))
return List.ofSeq it
}
/// Extract a count from the first column
[<CompiledName "ToCount">]
let toCount (row: SqliteDataReader) =
row.GetInt64 0
/// Extract a true/false value from a count in the first column
[<CompiledName "ToExists">]
let toExists row =
toCount(row) > 0L
[<AutoOpen>]
module internal Helpers =
/// Execute a non-query command
let internal write (cmd: SqliteCommand) = backgroundTask {
let! _ = cmd.ExecuteNonQueryAsync()
()
}
/// Versions of queries that accept a SqliteConnection as the last parameter
module WithConn =
/// Commands to execute custom SQL queries
[<RequireQualifiedAccess>]
module Custom =
/// Execute a query that returns a list of results
[<CompiledName "FSharpList">]
let list<'TDoc> query (parameters: SqliteParameter seq) (mapFunc: SqliteDataReader -> 'TDoc)
(conn: SqliteConnection) =
use cmd = conn.CreateCommand()
cmd.CommandText <- query
cmd.Parameters.AddRange parameters
toCustomList<'TDoc> cmd mapFunc
/// Execute a query that returns a list of results
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
}
/// Execute a query that returns one or no results (returns None if not found)
[<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)
let Single<'TDoc when 'TDoc: null>(
query, parameters, mapFunc: System.Func<SqliteDataReader, 'TDoc>, conn
) = backgroundTask {
let! result = single<'TDoc> query parameters mapFunc.Invoke conn
return Option.toObj result
}
/// Execute a query that does not return a value
[<CompiledName "NonQuery">]
let nonQuery query (parameters: SqliteParameter seq) (conn: SqliteConnection) =
use cmd = conn.CreateCommand()
cmd.CommandText <- query
cmd.Parameters.AddRange parameters
write cmd
/// Execute a query that returns a scalar value
[<CompiledName "FSharpScalar">]
let scalar<'T when 'T : struct> query (parameters: SqliteParameter seq) (mapFunc: SqliteDataReader -> 'T)
(conn: SqliteConnection) = backgroundTask {
use cmd = conn.CreateCommand()
cmd.CommandText <- query
cmd.Parameters.AddRange parameters
use! rdr = cmd.ExecuteReaderAsync()
let! isFound = rdr.ReadAsync()
return if isFound then mapFunc rdr else Unchecked.defaultof<'T>
}
/// Execute a query that returns a scalar value
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
[<RequireQualifiedAccess>]
module Definition =
/// Create a document table
[<CompiledName "EnsureTable">]
let ensureTable name conn = backgroundTask {
do! Custom.nonQuery (Query.Definition.ensureTable name) [] conn
do! Custom.nonQuery (Query.Definition.ensureKey name) [] conn
}
/// Create an index on a document table
[<CompiledName "EnsureFieldIndex">]
let ensureFieldIndex tableName indexName fields conn =
Custom.nonQuery (Query.Definition.ensureIndexOn tableName indexName fields) [] conn
/// Insert a new document
[<CompiledName "Insert">]
let insert<'TDoc> tableName (document: 'TDoc) conn =
Custom.nonQuery (Query.insert tableName) [ jsonParam "@data" document ] conn
/// Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
[<CompiledName "Save">]
let save<'TDoc> tableName (document: 'TDoc) conn =
Custom.nonQuery (Query.save tableName) [ jsonParam "@data" document ] conn
/// Commands to count documents
[<RequireQualifiedAccess>]
module Count =
/// Count all documents in a table
[<CompiledName "All">]
let all tableName conn =
Custom.scalar (Query.Count.all tableName) [] toCount conn
/// Count matching documents using a comparison on a JSON field
[<CompiledName "ByField">]
let byField tableName fieldName op (value: obj) conn =
Custom.scalar (Query.Count.byField tableName fieldName op) [ fieldParam value ] toCount conn
/// Commands to determine if documents exist
[<RequireQualifiedAccess>]
module Exists =
/// Determine if a document exists for the given ID
[<CompiledName "ById">]
let byId tableName (docId: 'TKey) conn =
Custom.scalar (Query.Exists.byId tableName) [ idParam docId ] toExists conn
/// Determine if a document exists using a comparison on a JSON field
[<CompiledName "ByField">]
let byField tableName fieldName op (value: obj) conn =
Custom.scalar (Query.Exists.byField tableName fieldName op) [ fieldParam value ] toExists conn
/// Commands to retrieve documents
[<RequireQualifiedAccess>]
module Find =
/// Retrieve all documents in the given table
[<CompiledName "FSharpAll">]
let all<'TDoc> tableName conn =
Custom.list<'TDoc> (Query.selectFromTable tableName) [] fromData<'TDoc> conn
/// Retrieve all documents in the given table
let All<'TDoc>(tableName, conn) =
Custom.List(Query.selectFromTable tableName, [], fromData<'TDoc>, conn)
/// Retrieve a document by its ID (returns None if not found)
[<CompiledName "FSharpById">]
let byId<'TKey, 'TDoc> tableName (docId: 'TKey) conn =
Custom.single<'TDoc> (Query.Find.byId tableName) [ idParam docId ] fromData<'TDoc> conn
/// Retrieve a document by its ID (returns null if not found)
let ById<'TKey, 'TDoc when 'TDoc: null>(tableName, docId: 'TKey, conn) =
Custom.Single<'TDoc>(Query.Find.byId tableName, [ idParam docId ], fromData<'TDoc>, conn)
/// Retrieve documents via a comparison on a JSON field
[<CompiledName "FSharpByField">]
let byField<'TDoc> tableName fieldName op (value: obj) conn =
Custom.list<'TDoc> (Query.Find.byField tableName fieldName op) [ fieldParam value ] fromData<'TDoc> conn
/// Retrieve documents via a comparison on a JSON field
let ByField<'TDoc>(tableName, fieldName, op, value: obj, conn) =
Custom.List<'TDoc>(Query.Find.byField tableName fieldName op, [ fieldParam value ], fromData<'TDoc>, conn)
/// Retrieve documents via a comparison on a JSON field, returning only the first result
[<CompiledName "FSharpFirstByField">]
let firstByField<'TDoc> tableName fieldName op (value: obj) conn =
Custom.single
$"{Query.Find.byField tableName fieldName op} LIMIT 1" [ fieldParam value ] fromData<'TDoc> conn
/// Retrieve documents via a comparison on a JSON field, returning only the first result
let FirstByField<'TDoc when 'TDoc: null>(tableName, fieldName, op, value: obj, conn) =
Custom.Single(
$"{Query.Find.byField tableName fieldName op} LIMIT 1", [ fieldParam value ], fromData<'TDoc>, conn)
/// Commands to update documents
[<RequireQualifiedAccess>]
module Update =
/// Update an entire document by its ID
[<CompiledName "ById">]
let byId tableName (docId: 'TKey) (document: 'TDoc) conn =
Custom.nonQuery (Query.update tableName) [ idParam docId; jsonParam "@data" document ] conn
/// Update an entire document by its ID, using the provided function to obtain the ID from the document
[<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
let ByFunc(tableName, idFunc: System.Func<'TDoc, 'TKey>, document: 'TDoc, conn) =
byFunc tableName idFunc.Invoke document conn
/// Commands to patch (partially update) documents
[<RequireQualifiedAccess>]
module Patch =
/// Patch a document by its ID
[<CompiledName "ById">]
let byId tableName (docId: 'TKey) (patch: 'TPatch) conn =
Custom.nonQuery (Query.Patch.byId tableName) [ idParam docId; jsonParam "@data" patch ] conn
/// Patch documents using a comparison on a JSON field
[<CompiledName "ByField">]
let byField tableName fieldName op (value: obj) (patch: 'TPatch) (conn: SqliteConnection) =
Custom.nonQuery
(Query.Patch.byField tableName fieldName op) [ fieldParam value; jsonParam "@data" patch ] conn
/// Commands to delete documents
[<RequireQualifiedAccess>]
module Delete =
/// Delete a document by its ID
[<CompiledName "ById">]
let byId tableName (docId: 'TKey) conn =
Custom.nonQuery (Query.Delete.byId tableName) [ idParam docId ] conn
/// Delete documents by matching a comparison on a JSON field
[<CompiledName "ByField">]
let byField tableName fieldName op (value: obj) conn =
Custom.nonQuery (Query.Delete.byField tableName fieldName op) [ fieldParam value ] conn
/// Commands to execute custom SQL queries
[<RequireQualifiedAccess>]
module Custom =
/// Execute a query that returns a list of results
[<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
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)
[<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)
let Single<'TDoc when 'TDoc: null>(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
[<CompiledName "NonQuery">]
let nonQuery query parameters =
use conn = Configuration.dbConn ()
WithConn.Custom.nonQuery query parameters conn
/// Execute a query that returns a scalar value
[<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
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)
/// Functions to create tables and indexes
[<RequireQualifiedAccess>]
module Definition =
/// Create a document table
[<CompiledName "EnsureTable">]
let ensureTable name =
use conn = Configuration.dbConn ()
WithConn.Definition.ensureTable name conn
/// Create an index on a document table
[<CompiledName "EnsureFieldIndex">]
let ensureFieldIndex tableName indexName fields =
use conn = Configuration.dbConn ()
WithConn.Definition.ensureFieldIndex tableName indexName fields conn
/// Document insert/save functions
[<AutoOpen>]
module Document =
/// Insert a new document
[<CompiledName "Insert">]
let insert<'TDoc> tableName (document: 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.insert tableName document conn
/// Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
[<CompiledName "Save">]
let save<'TDoc> tableName (document: 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.save tableName document conn
/// Commands to count documents
[<RequireQualifiedAccess>]
module Count =
/// Count all documents in a table
[<CompiledName "All">]
let all tableName =
use conn = Configuration.dbConn ()
WithConn.Count.all tableName conn
/// Count matching documents using a comparison on a JSON field
[<CompiledName "ByField">]
let byField tableName fieldName op (value: obj) =
use conn = Configuration.dbConn ()
WithConn.Count.byField tableName fieldName op value conn
/// Commands to determine if documents exist
[<RequireQualifiedAccess>]
module Exists =
/// Determine if a document exists for the given ID
[<CompiledName "ById">]
let byId tableName (docId: 'TKey) =
use conn = Configuration.dbConn ()
WithConn.Exists.byId tableName docId conn
/// Determine if a document exists using a comparison on a JSON field
[<CompiledName "ByField">]
let byField tableName fieldName op (value: obj) =
use conn = Configuration.dbConn ()
WithConn.Exists.byField tableName fieldName op value conn
/// Commands to determine if documents exist
[<RequireQualifiedAccess>]
module Find =
/// Retrieve all documents in the given table
[<CompiledName "FSharpAll">]
let all<'TDoc> tableName =
use conn = Configuration.dbConn ()
WithConn.Find.all<'TDoc> tableName conn
/// Retrieve all documents in the given table
let All<'TDoc> tableName =
use conn = Configuration.dbConn ()
WithConn.Find.All<'TDoc>(tableName, conn)
/// Retrieve a document by its ID (returns None if not found)
[<CompiledName "FSharpById">]
let byId<'TKey, 'TDoc> tableName docId =
use conn = Configuration.dbConn ()
WithConn.Find.byId<'TKey, 'TDoc> tableName docId conn
/// Retrieve a document by its ID (returns null if not found)
let ById<'TKey, 'TDoc when 'TDoc: null>(tableName, docId) =
use conn = Configuration.dbConn ()
WithConn.Find.ById<'TKey, 'TDoc>(tableName, docId, conn)
/// Retrieve documents via a comparison on a JSON field
[<CompiledName "FSharpByField">]
let byField<'TDoc> tableName fieldName op value =
use conn = Configuration.dbConn ()
WithConn.Find.byField<'TDoc> tableName fieldName op value conn
/// Retrieve documents via a comparison on a JSON field
let ByField<'TDoc>(tableName, fieldName, op, value) =
use conn = Configuration.dbConn ()
WithConn.Find.ByField<'TDoc>(tableName, fieldName, op, value, conn)
/// Retrieve documents via a comparison on a JSON field, returning only the first result
[<CompiledName "FSharpFirstByField">]
let firstByField<'TDoc> tableName fieldName op value =
use conn = Configuration.dbConn ()
WithConn.Find.firstByField<'TDoc> tableName fieldName op value conn
/// Retrieve documents via a comparison on a JSON field, returning only the first result
let FirstByField<'TDoc when 'TDoc: null>(tableName, fieldName, op, value) =
use conn = Configuration.dbConn ()
WithConn.Find.FirstByField<'TDoc>(tableName, fieldName, op, value, conn)
/// Commands to update documents
[<RequireQualifiedAccess>]
module Update =
/// Update an entire document by its ID
[<CompiledName "ById">]
let byId tableName (docId: 'TKey) (document: 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Update.byId tableName docId document conn
/// Update an entire document by its ID, using the provided function to obtain the ID from the document
[<CompiledName "FSharpByFunc">]
let byFunc tableName (idFunc: 'TDoc -> 'TKey) (document: 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Update.byFunc tableName idFunc document conn
/// Update an entire document by its ID, using the provided function to obtain the ID from the document
let ByFunc(tableName, idFunc: System.Func<'TDoc, 'TKey>, document: 'TDoc) =
use conn = Configuration.dbConn ()
WithConn.Update.ByFunc(tableName, idFunc, document, conn)
/// Commands to patch (partially update) documents
[<RequireQualifiedAccess>]
module Patch =
/// Patch a document by its ID
[<CompiledName "ById">]
let byId tableName (docId: 'TKey) (patch: 'TPatch) =
use conn = Configuration.dbConn ()
WithConn.Patch.byId tableName docId patch conn
/// Patch documents using a comparison on a JSON field in the WHERE clause
[<CompiledName "ByField">]
let byField tableName fieldName op (value: obj) (patch: 'TPatch) =
use conn = Configuration.dbConn ()
WithConn.Patch.byField tableName fieldName op value patch conn
/// Commands to delete documents
[<RequireQualifiedAccess>]
module Delete =
/// Delete a document by its ID
[<CompiledName "ById">]
let byId tableName (docId: 'TKey) =
use conn = Configuration.dbConn ()
WithConn.Delete.byId tableName docId conn
/// Delete documents by matching a comparison on a JSON field
[<CompiledName "ByField">]
let byField tableName fieldName op (value: obj) =
use conn = Configuration.dbConn ()
WithConn.Delete.byField tableName fieldName op value conn

101
src/Sqlite/README.md Normal file
View File

@@ -0,0 +1,101 @@
# BitBadger.Documents.Sqlite
This package provides a lightweight document library backed by [SQLite](https://www.sqlite.org). It also provides streamlined functions for traditional ADO.NET functionality where relational data is required. Both C# and F# have first-class implementations.
## Features
- Select, insert, update, save (upsert), delete, count, and check existence of documents, and create tables and indexes for these documents
- Address documents via ID or via comparison on any field
- Access documents as your domain models (<abbr title="Plain Old CLR Objects">POCO</abbr>s)
- Use `Task`-based async for all data access functions
- Use building blocks for more complex queries
## Getting Started
Once the package is installed, the library needs a connection string. Once it has been obtained / constructed, provide it to the library:
```csharp
// C#
using BitBadger.Documents.Sqlite;
//...
Sqlite.Configuration.UseConnectionString("connection-string");
// A new, open connection to the database can be obtained via
// Sqlite.Configuration.DbConn()
```
```fsharp
// F#
open BitBadger.Documents.Sqlite
// ...
Configuration.useConnectionString "connection-string"
// A new, open connection to the database can be obtained via
// Configuration.dbConn ()
```
By default, the library uses a `System.Text.Json`-based serializer configured to use the `FSharp.SystemTextJson` converter. To provide a different serializer (different options, more converters, etc.), construct it to implement `IDocumentSerializer` and provide it via `Configuration.useSerializer`. If custom serialization makes the serialized Id field not be `Id`, that will also need to be configured.
## Using
Retrieve all customers:
```csharp
// C#; parameter is table name
// Find.All type signature is Func<string, Task<List<TDoc>>>
var customers = await Find.All("customer");
```
```fsharp
// F#
// Find.all type signature is string -> Task<'TDoc list>
let! customers = Find.all<Customer> "customer"
```
Select a customer by ID:
```csharp
// C#; parameters are table name and ID
// Find.ById type signature is Func<string, TKey, Task<TDoc?>>
var customer = await Find.ById<string, Customer>("customer", "123");
```
```fsharp
// F#
// Find.byId type signature is string -> 'TKey -> Task<'TDoc option>
let! customer = Find.byId<string, Customer> "customer" "123"
```
_(keys are treated as strings in the database)_
Count customers in Atlanta:
```csharp
// C#; parameters are table name, field, operator, and value
// Count.ByField type signature is Func<string, string, Op, object, Task<long>>
var customerCount = await Count.ByField("customer", "City", Op.EQ, "Atlanta");
```
```fsharp
// F#
// Count.byField type signature is string -> string -> Op -> obj -> Task<int64>
let! customerCount = Count.byField "customer" "City" EQ "Atlanta"
```
Delete customers in Chicago: _(no offense, Second City; just an example...)_
```csharp
// C#; parameters are same as above, except return is void
// Delete.ByField type signature is Func<string, string, Op, object, Task>
await Delete.ByField("customer", "City", Op.EQ, "Chicago");
```
```fsharp
// F#
// Delete.byField type signature is string -> string -> Op -> obj -> Task<unit>
do! Delete.byField "customer" "City" EQ "Chicago"
```
## More Information
The [project site](https://bitbadger.solutions/open-source/relational-documents/) has full details on how to use this library.