Compare commits

..

No commits in common. "toward-1.0" and "main" have entirely different histories.

7 changed files with 571 additions and 745 deletions

File diff suppressed because it is too large Load Diff

View File

@ -6,6 +6,7 @@ open Microsoft.Extensions.Logging
open Newtonsoft.Json.Linq
open RethinkDb.Driver
open RethinkDb.Driver.Net
open System.Threading.Tasks
/// Parameters for the RethinkDB configuration
type DataConfigParameter =
@ -19,7 +20,7 @@ type DataConfigParameter =
/// Connection builder function
module private ConnectionBuilder =
let build (builder: Connection.Builder) block =
let build (builder : Connection.Builder) block =
match block with
| Hostname x -> builder.Hostname x
| Port x -> builder.Port x
@ -38,41 +39,29 @@ type DataConfig =
{ Parameters = [] }
/// Build the connection from the given parameters
member private this.BuildConnection() =
member private this.BuildConnection () =
this.Parameters
|> Seq.fold ConnectionBuilder.build (RethinkDB.R.Connection())
|> Seq.fold ConnectionBuilder.build (RethinkDB.R.Connection ())
/// Create a RethinkDB connection (task async)
member this.CreateConnection() = backgroundTask {
let! conn = this.BuildConnection().ConnectAsync()
return conn :> IConnection
}
/// Create a RethinkDB connection, logging the connection settings (task async)
member this.CreateConnection(log: ILogger) = backgroundTask {
let builder = this.BuildConnection()
if not (isNull log) then log.LogInformation $"Connecting to {this.EffectiveUri}"
let! conn = builder.ConnectAsync()
return conn :> IConnection
}
/// Create a RethinkDB connection (F# async)
member this.CreateAsyncConnection() =
this.CreateConnection() |> Async.AwaitTask
/// Create a RethinkDB connection, logging the connection settings (F# async)
member this.CreateAsyncConnection(log: ILogger) =
this.CreateConnection(log) |> Async.AwaitTask
/// Create a RethinkDB connection (sync)
member this.CreateSyncConnection() : IConnection =
this.BuildConnection().Connect()
/// Create a RethinkDB connection
member this.CreateConnection () : IConnection =
(this.BuildConnection ()).Connect ()
/// Create a RethinkDB connection, logging the connection settings (sync)
member this.CreateSyncConnection(log: ILogger) : IConnection =
let builder = this.BuildConnection()
/// Create a RethinkDB connection, logging the connection settings
member this.CreateConnection (log : ILogger) : IConnection =
let builder = this.BuildConnection ()
if not (isNull log) then log.LogInformation $"Connecting to {this.EffectiveUri}"
builder.Connect()
builder.Connect ()
/// Create a RethinkDB connection
member this.CreateConnectionAsync () : Task<Connection> =
(this.BuildConnection ()).ConnectAsync ()
/// Create a RethinkDB connection, logging the connection settings
member this.CreateConnectionAsync (log : ILogger) : Task<Connection> =
let builder = this.BuildConnection ()
if not (isNull log) then log.LogInformation $"Connecting to {this.EffectiveUri}"
builder.ConnectAsync ()
/// The effective hostname
member this.Hostname =
@ -103,7 +92,7 @@ type DataConfig =
seq {
"rethinkdb://"
match this.Parameters |> List.tryPick (fun x -> match x with User _ -> Some x | _ -> None) with
| Some (User(username, _)) -> $"{username}:***pw***@"
| Some (User (username, _)) -> $"{username}:***pw***@"
| _ ->
match this.Parameters |> List.tryPick (fun x -> match x with AuthKey _ -> Some x | _ -> None) with
| Some (AuthKey _) -> "****key****@"
@ -129,14 +118,14 @@ type DataConfig =
static member FromJson json =
let parsed = JObject.Parse json
{ Parameters =
[ match parsed["hostname"] with null -> () | x -> Hostname <| x.Value<string>()
match parsed["port"] with null -> () | x -> Port <| x.Value<int>()
match parsed["auth-key"] with null -> () | x -> AuthKey <| x.Value<string>()
match parsed["timeout"] with null -> () | x -> Timeout <| x.Value<int>()
match parsed["database"] with null -> () | x -> Database <| x.Value<string>()
[ match parsed["hostname"] with null -> () | x -> Hostname <| x.Value<string> ()
match parsed["port"] with null -> () | x -> Port <| x.Value<int> ()
match parsed["auth-key"] with null -> () | x -> AuthKey <| x.Value<string> ()
match parsed["timeout"] with null -> () | x -> Timeout <| x.Value<int> ()
match parsed["database"] with null -> () | x -> Database <| x.Value<string> ()
match parsed["username"], parsed["password"] with
| null, _ | _, null -> ()
| userName, password -> User(userName.Value<string>(), password.Value<string>())
| userName, password -> User (userName.Value<string> (), password.Value<string> ())
]
}
@ -146,12 +135,12 @@ type DataConfig =
static member FromJsonFile = System.IO.File.ReadAllText >> DataConfig.FromJson
/// Parse settings from application configuration
static member FromConfiguration(cfg: IConfigurationSection) =
static member FromConfiguration (cfg : IConfigurationSection) =
{ Parameters =
[ match cfg["hostname"] with null -> () | host -> Hostname host
match cfg["port"] with null -> () | port -> Port(int port)
match cfg["port"] with null -> () | port -> Port (int port)
match cfg["auth-key"] with null -> () | key -> AuthKey key
match cfg["timeout"] with null -> () | time -> Timeout(int time)
match cfg["timeout"] with null -> () | time -> Timeout (int time)
match cfg["database"] with null -> () | db -> Database db
match cfg["username"], cfg["password"] with null, _ | _, null -> () | user -> User user
]
@ -164,7 +153,7 @@ type DataConfig =
/// rethinkdb://authkey@host:port/database?timeout=##
///
/// Scheme and host are required; all other settings optional
static member FromUri(uri: string) =
static member FromUri (uri : string) =
let it = Uri uri
if it.Scheme <> "rethinkdb" then invalidArg "Scheme" $"""URI scheme must be "rethinkdb" (was {it.Scheme})"""
{ Parameters =
@ -173,9 +162,9 @@ type DataConfig =
if it.UserInfo <> "" then
if it.UserInfo.Contains ":" then
let parts = it.UserInfo.Split ':' |> Array.truncate 2
User(parts[0], parts[1])
User (parts[0], parts[1])
else AuthKey it.UserInfo
if it.Segments.Length > 1 then Database it.Segments[1]
if it.Query.Contains "?timeout=" then Timeout(int it.Query[9..])
if it.Query.Contains "?timeout=" then Timeout (int it.Query[9..])
]
}

View File

@ -13,22 +13,20 @@ module private Helpers =
let r = RethinkDB.R
/// Create a Javascript object from a string (used mostly for type inference)
let toJS (js: string) = Javascript js
let toJS (js : string) = Javascript js
// ~~ WRITES ~~
/// Write a ReQL command with a cancellation token, always returning a result
let runWriteResultWithCancel cancelToken (expr: ReqlExpr) = fun conn -> backgroundTask {
return! expr.RunWriteAsync(conn, cancelToken)
}
let runWriteResultWithCancel cancelToken (expr : ReqlExpr) = fun conn ->
expr.RunWriteAsync (conn, cancelToken)
/// Write a ReQL command, always returning a result
let runWriteResult expr = runWriteResultWithCancel CancellationToken.None expr
/// Write a ReQL command with optional arguments and a cancellation token, always returning a result
let runWriteResultWithOptArgsAndCancel args cancelToken (expr: ReqlExpr) = fun conn -> backgroundTask {
return! expr.RunWriteAsync(conn, RunOptArg.create args, cancelToken)
}
let runWriteResultWithOptArgsAndCancel args cancelToken (expr : ReqlExpr) = fun conn ->
expr.RunWriteAsync (conn, RunOptArg.create args, cancelToken)
/// Write a ReQL command with optional arguments, always returning a result
let runWriteResultWithOptArgs args expr = runWriteResultWithOptArgsAndCancel args CancellationToken.None expr
@ -58,7 +56,7 @@ let syncWriteResultWithOptArgs args expr = fun conn ->
asyncWriteResultWithOptArgs args expr conn |> Async.RunSynchronously
/// Raise an exception if a write command encountered an error
let raiseIfWriteError (result: Model.Result) =
let raiseIfWriteError (result : Model.Result) =
match result.Errors with
| 0UL -> result
| _ -> raise <| ReqlRuntimeError result.FirstError
@ -110,14 +108,12 @@ let syncWriteWithOptArgs args expr = fun conn ->
// ~~ Full results (atom / sequence) ~~
/// Run the ReQL command using a cancellation token, returning the result as the type specified
let runResultWithCancel<'T> cancelToken (expr: ReqlExpr) = fun conn -> backgroundTask {
return! expr.RunResultAsync<'T>(conn, cancelToken)
}
let runResultWithCancel<'T> cancelToken (expr : ReqlExpr) = fun conn ->
expr.RunResultAsync<'T> (conn, cancelToken)
/// Run the ReQL command using optional arguments and a cancellation token, returning the result as the type specified
let runResultWithOptArgsAndCancel<'T> args cancelToken (expr: ReqlExpr) = fun conn -> backgroundTask {
return! expr.RunResultAsync<'T>(conn, RunOptArg.create args, cancelToken)
}
let runResultWithOptArgsAndCancel<'T> args cancelToken (expr : ReqlExpr) = fun conn ->
expr.RunResultAsync<'T> (conn, RunOptArg.create args, cancelToken)
/// Run the ReQL command, returning the result as the type specified
let runResult<'T> expr = runResultWithCancel<'T> CancellationToken.None expr
@ -150,41 +146,39 @@ let syncResultWithOptArgs<'T> args expr = fun conn ->
asyncResultWithOptArgs<'T> args expr conn |> Async.RunSynchronously
/// Convert a null item to an option (works for value types as well as reference types)
let nullToOption<'T> (it: 'T) =
let nullToOption<'T> (it : 'T) =
if isNull (box it) then None else Some it
/// Convert a possibly-null result to an option
let asOption (f: IConnection -> Tasks.Task<'T>) conn = backgroundTask {
let asOption (f : IConnection -> Tasks.Task<'T>) conn = backgroundTask {
let! result = f conn
return nullToOption result
}
/// Convert a possibly-null result to an option
let asAsyncOption (f: IConnection -> Async<'T>) conn = async {
let asAsyncOption (f : IConnection -> Async<'T>) conn = async {
let! result = f conn
return nullToOption result
}
/// Convert a possibly-null result to an option
let asSyncOption (f: IConnection -> 'T) conn = nullToOption (f conn)
let asSyncOption (f : IConnection -> 'T) conn = nullToOption (f conn)
/// Ignore the result of a task-based query
let ignoreResult<'T> (f: IConnection -> Tasks.Task<'T>) conn = backgroundTask {
let! _ = f conn
let ignoreResult<'T> (f : IConnection -> Tasks.Task<'T>) conn = task {
let! _ = (f conn).ConfigureAwait false
()
}
// ~~ Cursors / partial results (sequence / partial) ~~
/// Run the ReQL command using a cancellation token, returning a cursor for the type specified
let runCursorWithCancel<'T> cancelToken (expr: ReqlExpr) = fun conn -> backgroundTask {
return! expr.RunCursorAsync<'T>(conn, cancelToken)
}
let runCursorWithCancel<'T> cancelToken (expr : ReqlExpr) = fun conn ->
expr.RunCursorAsync<'T> (conn, cancelToken)
/// Run the ReQL command using optional arguments and a cancellation token, returning a cursor for the type specified
let runCursorWithOptArgsAndCancel<'T> args cancelToken (expr: ReqlExpr) = fun conn -> backgroundTask {
return! expr.RunCursorAsync<'T>(conn, RunOptArg.create args, cancelToken)
}
let runCursorWithOptArgsAndCancel<'T> args cancelToken (expr : ReqlExpr) = fun conn ->
expr.RunCursorAsync<'T> (conn, RunOptArg.create args, cancelToken)
/// Run the ReQL command, returning a cursor for the type specified
let runCursor<'T> expr = runCursorWithCancel<'T> CancellationToken.None expr
@ -217,134 +211,134 @@ let syncCursorWithOptArgs<'T> args expr = fun conn ->
asyncCursorWithOptArgs<'T> args expr conn |> Async.RunSynchronously
/// Convert a cursor to a list (once the cursor has been obtained)
let cursorToList<'T> (cursor: Cursor<'T>) = backgroundTask {
let! hasNext = cursor.MoveNextAsync()
let cursorToList<'T> (cursor : Cursor<'T>) = backgroundTask {
let! hasNext = cursor.MoveNextAsync ()
let mutable hasData = hasNext
let mutable items = []
while hasData do
items <- cursor.Current :: items
let! hasNext = cursor.MoveNextAsync()
let! hasNext = cursor.MoveNextAsync ()
hasData <- hasNext
return items
}
/// Convert a cursor to a list of items
let toList<'T> (f: IConnection -> Task<Cursor<'T>>) = fun conn -> backgroundTask {
let toList<'T> (f : IConnection -> Task<Cursor<'T>>) = fun conn -> backgroundTask {
use! cursor = f conn
return! cursorToList cursor
}
/// Convert a cursor to a list of items
let asyncToList<'T> (f: IConnection -> Async<Cursor<'T>>) = fun conn -> async {
let toListAsync<'T> (f : IConnection -> Async<Cursor<'T>>) = fun conn -> async {
use! cursor = f conn
return! cursorToList<'T> cursor |> Async.AwaitTask
}
/// Convert a cursor to a list of items
let syncToList<'T> (f: IConnection -> Cursor<'T>) = fun conn ->
let toListSync<'T> (f : IConnection -> Cursor<'T>) = fun conn ->
use cursor = f conn
cursorToList cursor |> Async.AwaitTask |> Async.RunSynchronously
/// Apply a connection to the query pipeline (typically the final step)
let withConn<'T> conn (f: IConnection -> 'T) = f conn
let withConn<'T> conn (f : IConnection -> 'T) = f conn
// ~~ QUERY DEFINITION ~~
/// Get documents between a lower bound and an upper bound based on a primary key
let between (lowerKey: obj) (upperKey: obj) (expr: ReqlExpr) =
expr.Between(lowerKey, upperKey)
let between (lowerKey : obj) (upperKey : obj) (expr : ReqlExpr) =
expr.Between (lowerKey, upperKey)
/// Get document between a lower bound and an upper bound, specifying one or more optional arguments
let betweenWithOptArgs (lowerKey: obj) (upperKey: obj) args expr =
let betweenWithOptArgs (lowerKey : obj) (upperKey : obj) args expr =
between lowerKey upperKey expr |> BetweenOptArg.apply args
/// Get documents between a lower bound and an upper bound based on an index
let betweenIndex (lowerKey: obj) (upperKey: obj) index expr =
let betweenIndex (lowerKey : obj) (upperKey : obj) index expr =
betweenWithOptArgs lowerKey upperKey [ Index index ] expr
/// Get a connection builder that can be used to create one RethinkDB connection
let connection () =
r.Connection()
r.Connection ()
/// Count the documents in this query
let count (expr: ReqlExpr) =
expr.Count()
let count (expr : ReqlExpr) =
expr.Count ()
/// Count the documents in this query where the function returns true
let countFunc (f: ReqlExpr -> bool) (expr: ReqlExpr) =
expr.Count(ReqlFunction1(fun row -> f row :> obj))
let countFunc (f : ReqlExpr -> bool) (expr : ReqlExpr) =
expr.Count (ReqlFunction1 (fun row -> f row :> obj))
/// Count the documents in this query where the function returns true
let countJS js (expr: ReqlExpr) =
expr.Count(toJS js)
let countJS js (expr : ReqlExpr) =
expr.Count (toJS js)
/// Reference a database
let db dbName =
match dbName with "" -> r.Db() | _ -> r.Db dbName
match dbName with "" -> r.Db () | _ -> r.Db dbName
/// Create a database
let dbCreate (dbName: string) =
let dbCreate (dbName : string) =
r.DbCreate dbName
/// Drop a database
let dbDrop (dbName: string) =
let dbDrop (dbName : string) =
r.DbDrop dbName
/// Get a list of databases
let dbList () =
r.DbList()
r.DbList ()
/// Delete documents
let delete (expr: ReqlExpr) =
expr.Delete()
let delete (expr : ReqlExpr) =
expr.Delete ()
/// Delete documents, providing optional arguments
let deleteWithOptArgs args (expr: ReqlExpr) =
let deleteWithOptArgs args (expr : ReqlExpr) =
delete expr |> DeleteOptArg.apply args
/// Only retrieve distinct entries from a selection
let distinct (expr: ReqlExpr) =
expr.Distinct()
let distinct (expr : ReqlExpr) =
expr.Distinct ()
/// Only retrieve distinct entries from a selection, based on an index
let distinctWithIndex (index: string) expr =
(distinct expr).OptArg("index", index)
let distinctWithIndex (index : string) expr =
(distinct expr).OptArg ("index", index)
/// EqJoin the left field on the right-hand table using its primary key
let eqJoin (field: string) (table: Table) (expr: ReqlExpr) =
expr.EqJoin(field, table)
let eqJoin (field : string) (table : Table) (expr : ReqlExpr) =
expr.EqJoin (field, table)
/// EqJoin the left function on the right-hand table using its primary key
let eqJoinFunc<'T> (f: ReqlExpr -> 'T) (table: Table) (expr: ReqlExpr) =
expr.EqJoin(ReqlFunction1(fun row -> f row :> obj), table)
let eqJoinFunc<'T> (f : ReqlExpr -> 'T) (table : Table) (expr : ReqlExpr) =
expr.EqJoin (ReqlFunction1 (fun row -> f row :> obj), table)
/// EqJoin the left function on the right-hand table using the specified index
let eqJoinFuncIndex<'T> (f: ReqlExpr -> 'T) table (indexName: string) expr =
(eqJoinFunc f table expr).OptArg("index", indexName)
let eqJoinFuncIndex<'T> (f : ReqlExpr -> 'T) table (indexName : string) expr =
(eqJoinFunc f table expr).OptArg ("index", indexName)
/// EqJoin the left field on the right-hand table using the specified index
let eqJoinIndex field table (indexName: string) expr =
(eqJoin field table expr).OptArg("index", indexName)
let eqJoinIndex field table (indexName : string) expr =
(eqJoin field table expr).OptArg ("index", indexName)
/// EqJoin the left JavaScript on the right-hand table using its primary key
let eqJoinJS js (table: Table) (expr: ReqlExpr) =
expr.EqJoin(toJS js, table)
let eqJoinJS js (table : Table) (expr : ReqlExpr) =
expr.EqJoin (toJS js, table)
/// EqJoin the left JavaScript on the right-hand table using the specified index
let eqJoinJSIndex js table (indexName: string) expr =
(eqJoinJS js table expr).OptArg("index", indexName)
let eqJoinJSIndex js table (indexName : string) expr =
(eqJoinJS js table expr).OptArg ("index", indexName)
/// Filter documents
let filter (filterSpec: obj) (expr: ReqlExpr) =
let filter (filterSpec : obj) (expr : ReqlExpr) =
expr.Filter filterSpec
/// Filter documents, providing optional arguments
let filterWithOptArg (filterSpec: obj) arg expr =
let filterWithOptArg (filterSpec : obj) arg expr =
filter filterSpec expr |> FilterOptArg.apply arg
/// Filter documents using a function
let filterFunc f (expr: ReqlExpr) =
expr.Filter(ReqlFunction1 f)
let filterFunc f (expr : ReqlExpr) =
expr.Filter (ReqlFunction1 f)
/// Filter documents using a function, providing optional arguments
let filterFuncWithOptArg f arg expr =
@ -352,34 +346,34 @@ let filterFuncWithOptArg f arg expr =
/// Filter documents using multiple functions (has the effect of ANDing them)
let filterFuncAll fs expr =
(fs |> List.fold (fun (e: ReqlExpr) f -> filterFunc f e) expr) :?> Filter
(fs |> List.fold (fun (e : ReqlExpr) f -> filterFunc f e) expr) :?> Filter
/// Filter documents using multiple functions (has the effect of ANDing them), providing optional arguments
let filterFuncAllWithOptArg fs arg expr =
filterFuncAll fs expr |> FilterOptArg.apply arg
/// Filter documents using JavaScript
let filterJS js (expr: ReqlExpr) =
expr.Filter(toJS js)
let filterJS js (expr : ReqlExpr) =
expr.Filter (toJS js)
/// Filter documents using JavaScript, providing optional arguments
let filterJSWithOptArg js arg expr =
filterJS js expr |> FilterOptArg.apply arg
/// Get a document by its primary key
let get (documentId: obj) (table: Table) =
let get (documentId : obj) (table : Table) =
table.Get documentId
/// Get all documents matching primary keys
let getAll (ids: obj seq) (table: Table) =
table.GetAll(Array.ofSeq ids)
let getAll (ids : obj seq) (table : Table) =
table.GetAll (Array.ofSeq ids)
/// Get all documents matching keys in the given index
let getAllWithIndex (ids: obj seq) (indexName: string) table =
(getAll ids table).OptArg("index", indexName)
let getAllWithIndex (ids : obj seq) (indexName : string) table =
(getAll ids table).OptArg ("index", indexName)
/// Create an index on the given table
let indexCreate (indexName: string) (table: Table) =
let indexCreate (indexName : string) (table : Table) =
table.IndexCreate indexName
/// Create an index on the given table, including optional arguments
@ -387,171 +381,171 @@ let indexCreateWithOptArgs indexName args table =
indexCreate indexName table |> IndexCreateOptArg.apply args
/// Create an index on the given table using a function
let indexCreateFunc (indexName: string) f (table: Table) =
table.IndexCreate(indexName, ReqlFunction1 f)
let indexCreateFunc (indexName : string) f (table : Table) =
table.IndexCreate (indexName, ReqlFunction1 f)
/// Create an index on the given table using a function, including optional arguments
let indexCreateFuncWithOptArgs indexName f args table =
indexCreateFunc indexName f table |> IndexCreateOptArg.apply args
/// Create an index on the given table using JavaScript
let indexCreateJS (indexName: string) js (table: Table) =
table.IndexCreate(indexName, toJS js)
let indexCreateJS (indexName : string) js (table : Table) =
table.IndexCreate (indexName, toJS js)
/// Create an index on the given table using JavaScript, including optional arguments
let indexCreateJSWithOptArgs indexName js args table =
indexCreateJS indexName js table |> IndexCreateOptArg.apply args
/// Drop an index
let indexDrop (indexName: string) (table: Table) =
let indexDrop (indexName : string) (table : Table) =
table.IndexDrop indexName
/// Get a list of indexes for the given table
let indexList (table: Table) =
table.IndexList()
let indexList (table : Table) =
table.IndexList ()
/// Rename an index (will fail if new name already exists)
let indexRename (oldName: string) (newName: string) (table: Table) =
table.IndexRename(oldName, newName)
let indexRename (oldName : string) (newName : string) (table : Table) =
table.IndexRename (oldName, newName)
/// Rename an index (specifying overwrite action)
let indexRenameWithOptArg oldName newName arg table =
indexRename oldName newName table |> IndexRenameOptArg.apply arg
/// Get the status of specific indexes for the given table
let indexStatus (indexes: string list) (table: Table) =
table.IndexStatus(Array.ofList indexes)
let indexStatus (indexes : string list) (table : Table) =
table.IndexStatus (Array.ofList indexes)
/// Get the status of all indexes for the given table
let indexStatusAll (table: Table) =
table.IndexStatus()
let indexStatusAll (table : Table) =
table.IndexStatus ()
/// Wait for specific indexes on the given table to become ready
let indexWait (indexes: string list) (table: Table) =
table.IndexWait(Array.ofList indexes)
let indexWait (indexes : string list) (table : Table) =
table.IndexWait (Array.ofList indexes)
/// Wait for all indexes on the given table to become ready
let indexWaitAll (table: Table) =
table.IndexWait()
let indexWaitAll (table : Table) =
table.IndexWait ()
/// Create an inner join between two sequences, specifying the join condition with a function
let innerJoinFunc<'T> (otherSeq: obj) (f: ReqlExpr -> ReqlExpr -> 'T) (expr: ReqlExpr) =
expr.InnerJoin(otherSeq, ReqlFunction2(fun f1 f2 -> f f1 f2 :> obj))
let innerJoinFunc<'T> (otherSeq : obj) (f : ReqlExpr -> ReqlExpr -> 'T) (expr : ReqlExpr) =
expr.InnerJoin (otherSeq, ReqlFunction2 (fun f1 f2 -> f f1 f2 :> obj))
/// Create an inner join between two sequences, specifying the join condition with JavaScript
let innerJoinJS (otherSeq: obj) js (expr: ReqlExpr) =
expr.InnerJoin(otherSeq, toJS js)
let innerJoinJS (otherSeq : obj) js (expr : ReqlExpr) =
expr.InnerJoin (otherSeq, toJS js)
/// Insert a single document (use insertMany for multiple)
let insert<'T> (doc: 'T) (table: Table) =
let insert<'T> (doc : 'T) (table : Table) =
table.Insert doc
/// Insert multiple documents
let insertMany<'T> (docs: 'T seq) (table: Table) =
table.Insert(Array.ofSeq docs)
let insertMany<'T> (docs : 'T seq) (table : Table) =
table.Insert (Array.ofSeq docs)
/// Insert a single document, providing optional arguments (use insertManyWithOptArgs for multiple)
let insertWithOptArgs<'T> (doc: 'T) args table =
let insertWithOptArgs<'T> (doc : 'T) args table =
insert doc table |> InsertOptArg.apply args
/// Insert multiple documents, providing optional arguments
let insertManyWithOptArgs<'T> (docs: 'T seq) args table =
let insertManyWithOptArgs<'T> (docs : 'T seq) args table =
insertMany docs table |> InsertOptArg.apply args
/// Test whether a sequence is empty
let isEmpty (expr: ReqlExpr) =
expr.IsEmpty()
let isEmpty (expr : ReqlExpr) =
expr.IsEmpty ()
/// End a sequence after a given number of elements
let limit (n: int) (expr: ReqlExpr) =
let limit (n : int) (expr : ReqlExpr) =
expr.Limit n
/// Map the results using a function
let mapFunc f (expr: ReqlExpr) =
expr.Map(ReqlFunction1 f)
let mapFunc f (expr : ReqlExpr) =
expr.Map (ReqlFunction1 f)
/// Map the results using a JavaScript function
let mapJS js (expr: ReqlExpr) =
expr.Map(toJS js)
let mapJS js (expr : ReqlExpr) =
expr.Map (toJS js)
/// Merge the current query with given document
let merge (doc: obj) (expr: ReqlExpr) =
let merge (doc : obj) (expr : ReqlExpr) =
expr.Merge doc
/// Merge the current query with the results of a function
let mergeFunc f (expr: ReqlExpr) =
expr.Merge(ReqlFunction1 f)
let mergeFunc f (expr : ReqlExpr) =
expr.Merge (ReqlFunction1 f)
/// Merge the current query with the results of a JavaScript function
let mergeJS js (expr: ReqlExpr) =
expr.Merge(toJS js)
let mergeJS js (expr : ReqlExpr) =
expr.Merge (toJS js)
/// Retrieve the nth element in a sequence
let nth (n: int) (expr: ReqlExpr) =
let nth (n : int) (expr : ReqlExpr) =
expr.Nth n
/// Order a sequence by a given field
let orderBy (field: string) (expr: ReqlExpr) =
let orderBy (field : string) (expr : ReqlExpr) =
expr.OrderBy field
/// Order a sequence in descending order by a given field
let orderByDescending (field: string) (expr: ReqlExpr) =
expr.OrderBy(r.Desc field)
let orderByDescending (field : string) (expr : ReqlExpr) =
expr.OrderBy (r.Desc field)
/// Order a sequence by a given function
let orderByFunc f (expr: ReqlExpr) =
expr.OrderBy(ReqlFunction1 f)
let orderByFunc f (expr : ReqlExpr) =
expr.OrderBy (ReqlFunction1 f)
/// Order a sequence in descending order by a given function
let orderByFuncDescending f (expr: ReqlExpr) =
expr.OrderBy(r.Desc(ReqlFunction1 f))
let orderByFuncDescending f (expr : ReqlExpr) =
expr.OrderBy (r.Desc (ReqlFunction1 f))
/// Order a sequence by a given index
let orderByIndex (index: string) (expr: ReqlExpr) =
let orderByIndex (index : string) (expr : ReqlExpr) =
expr.OrderBy().OptArg("index", index)
/// Order a sequence in descending order by a given index
let orderByIndexDescending (index: string) (expr: ReqlExpr) =
let orderByIndexDescending (index : string) (expr : ReqlExpr) =
expr.OrderBy().OptArg("index", r.Desc index)
/// Order a sequence by a given JavaScript function
let orderByJS js (expr: ReqlExpr) =
expr.OrderBy(toJS js)
let orderByJS js (expr : ReqlExpr) =
expr.OrderBy (toJS js)
/// Order a sequence in descending order by a given JavaScript function
let orderByJSDescending js (expr: ReqlExpr) =
expr.OrderBy(r.Desc(toJS js))
let orderByJSDescending js (expr : ReqlExpr) =
expr.OrderBy (r.Desc (toJS js))
/// Create an outer join between two sequences, specifying the join condition with a function
let outerJoinFunc<'T> (otherSeq: obj) (f: ReqlExpr -> ReqlExpr -> 'T) (expr: ReqlExpr) =
expr.OuterJoin(otherSeq, ReqlFunction2(fun f1 f2 -> f f1 f2 :> obj))
let outerJoinFunc<'T> (otherSeq : obj) (f : ReqlExpr -> ReqlExpr -> 'T) (expr : ReqlExpr) =
expr.OuterJoin (otherSeq, ReqlFunction2 (fun f1 f2 -> f f1 f2 :> obj))
/// Create an outer join between two sequences, specifying the join condition with JavaScript
let outerJoinJS (otherSeq: obj) js (expr: ReqlExpr) =
expr.OuterJoin(otherSeq, toJS js)
let outerJoinJS (otherSeq : obj) js (expr : ReqlExpr) =
expr.OuterJoin (otherSeq, toJS js)
/// Select one or more attributes from an object or sequence
let pluck (fields: string seq) (expr: ReqlExpr) =
expr.Pluck(Array.ofSeq fields)
let pluck (fields : string seq) (expr : ReqlExpr) =
expr.Pluck (Array.ofSeq fields)
/// Replace documents
let replace (replaceSpec: obj) (expr: ReqlExpr) =
let replace (replaceSpec : obj) (expr : ReqlExpr) =
expr.Replace replaceSpec
/// Replace documents, providing optional arguments
let replaceWithOptArgs (replaceSpec: obj) args expr =
let replaceWithOptArgs (replaceSpec : obj) args expr =
replace replaceSpec expr |> ReplaceOptArg.apply args
/// Replace documents using a function
let replaceFunc f (expr: ReqlExpr) =
expr.Replace(ReqlFunction1 f)
let replaceFunc f (expr : ReqlExpr) =
expr.Replace (ReqlFunction1 f)
/// Replace documents using a function, providing optional arguments
let replaceFuncWithOptArgs f args expr =
replaceFunc f expr |> ReplaceOptArg.apply args
/// Replace documents using JavaScript
let replaceJS js (expr: ReqlExpr) =
let replaceJS js (expr : ReqlExpr) =
expr.Replace (toJS js)
/// Replace documents using JavaScript, providing optional arguments
@ -559,83 +553,83 @@ let replaceJSWithOptArgs js args expr =
replaceJS js expr |> ReplaceOptArg.apply args
/// Skip a number of elements from the head of a sequence
let skip (n: int) (expr: ReqlExpr) =
let skip (n : int) (expr : ReqlExpr) =
expr.Skip n
/// Ensure changes to a table are written to permanent storage
let sync (table: Table) =
let sync (table : Table) =
table.Sync ()
/// Return all documents in a table (may be further refined)
let table (tableName: string) (db: Db) =
let table (tableName : string) (db : Db) =
db.Table tableName
/// Return all documents in a table from the default database (may be further refined)
let fromTable (tableName: string) =
let fromTable (tableName : string) =
r.Table tableName
/// Create a table in the given database
let tableCreate (tableName: string) (db: Db) =
let tableCreate (tableName : string) (db : Db) =
db.TableCreate tableName
/// Create a table in the connection-default database
let tableCreateInDefault (tableName: string) =
let tableCreateInDefault (tableName : string) =
r.TableCreate tableName
/// Create a table in the connection-default database, providing optional arguments
let tableCreateInDefaultWithOptArgs (tableName: string) args =
let tableCreateInDefaultWithOptArgs (tableName : string) args =
r.TableCreate tableName |> TableCreateOptArg.apply args
/// Create a table in the given database, providing optional arguments
let tableCreateWithOptArgs (tableName: string) args (db: Db) =
let tableCreateWithOptArgs (tableName : string) args (db : Db) =
db.TableCreate tableName |> TableCreateOptArg.apply args
/// Drop a table in the given database
let tableDrop (tableName: string) (db: Db) =
let tableDrop (tableName : string) (db : Db) =
db.TableDrop tableName
/// Drop a table from the connection-default database
let tableDropFromDefault (tableName: string) =
let tableDropFromDefault (tableName : string) =
r.TableDrop tableName
/// Get a list of tables for the given database
let tableList (db: Db) =
db.TableList()
let tableList (db : Db) =
db.TableList ()
/// Get a list of tables from the connection-default database
let tableListFromDefault () =
r.TableList()
r.TableList ()
/// Update documents
let update (updateSpec: obj) (expr: ReqlExpr) =
let update (updateSpec : obj) (expr : ReqlExpr) =
expr.Update updateSpec
/// Update documents, providing optional arguments
let updateWithOptArgs (updateSpec: obj) args expr =
let updateWithOptArgs (updateSpec : obj) args expr =
update updateSpec expr |> UpdateOptArg.apply args
/// Update documents using a function
let updateFunc f (expr: ReqlExpr) =
expr.Update(ReqlFunction1 f)
let updateFunc f (expr : ReqlExpr) =
expr.Update (ReqlFunction1 f)
/// Update documents using a function, providing optional arguments
let updateFuncWithOptArgs f args expr =
updateFunc f expr |> UpdateOptArg.apply args
/// Update documents using JavaScript
let updateJS js (expr: ReqlExpr) =
expr.Update(toJS js)
let updateJS js (expr : ReqlExpr) =
expr.Update (toJS js)
/// Update documents using JavaScript, providing optional arguments
let updateJSWithOptArgs js args expr =
updateJS js expr |> UpdateOptArg.apply args
/// Exclude fields from the result
let without (columns: string seq) (expr: ReqlExpr) =
expr.Without(Array.ofSeq columns)
let without (columns : string seq) (expr : ReqlExpr) =
expr.Without (Array.ofSeq columns)
/// Merge the right-hand fields into the left-hand document of a sequence
let zip (expr: ReqlExpr) =
let zip (expr : ReqlExpr) =
expr.Zip ()
// ~~ RETRY FUNCTIONS ~~
@ -646,9 +640,7 @@ let withRetry<'T> intervals f =
/// Convert an async function to a task function (Polly does not understand F# Async)
let private asyncFuncToTask<'T> (f : IConnection -> Async<'T>) =
fun conn -> backgroundTask {
return! f conn |> Async.StartAsTask
}
fun conn -> f conn |> Async.StartAsTask
/// Retry, delaying for each the seconds provided (if required)
let withAsyncRetry<'T> intervals f = fun conn ->

View File

@ -159,10 +159,10 @@ val syncCursorWithOptArgs<'T> : RunOptArg list -> ReqlExpr -> (IConnection -> Cu
val toList<'T> : (IConnection -> Task<Cursor<'T>>) -> IConnection -> Task<'T list>
/// Convert a cursor to a list of items
val asyncToList<'T> : (IConnection -> Async<Cursor<'T>>) -> IConnection -> Async<'T list>
val toListAsync<'T> : (IConnection -> Async<Cursor<'T>>) -> IConnection -> Async<'T list>
/// Convert a cursor to a list of items
val syncToList<'T> : (IConnection -> Cursor<'T>) -> IConnection -> 'T list
val toListSync<'T> : (IConnection -> Cursor<'T>) -> IConnection -> 'T list
/// Apply a connection to the query pipeline (typically the final step)
val withConn<'T> : IConnection -> (IConnection -> 'T) -> 'T

View File

@ -28,13 +28,13 @@ type BetweenOptArg =
module BetweenOptArg =
/// Apply a list of optional arguments to a between statement
let apply opts (b: Between) =
let apply opts (b : Between) =
opts
|> List.fold (fun (btw: Between) arg ->
|> List.fold (fun (btw : Between) arg ->
match arg with
| Index idx -> btw.OptArg("index", idx)
| LowerBound typ -> btw.OptArg("lower_bound", typ.reql)
| UpperBound typ -> btw.OptArg("upper_bound", typ.reql))
| Index idx -> btw.OptArg ("index", idx)
| LowerBound typ -> btw.OptArg ("lower_bound", typ.reql)
| UpperBound typ -> btw.OptArg ("upper_bound", typ.reql))
b
@ -75,13 +75,13 @@ type DeleteOptArg =
module DeleteOptArg =
/// Apply a list of optional arguments to a delete statement
let apply opts (d: Delete) =
let apply opts (d : Delete) =
opts
|> List.fold (fun (del: Delete) arg ->
|> List.fold (fun (del : Delete) arg ->
match arg with
| Durability dur -> del.OptArg dur.reql
| ReturnChanges chg -> del.OptArg chg.reql
| IgnoreWriteHook ign -> del.OptArg("ignore_write_hook", ign))
| IgnoreWriteHook ign -> del.OptArg ("ignore_write_hook", ign))
d
@ -95,7 +95,7 @@ type FilterDefaultHandling =
| Error
/// The ReQL value for this default handling
member this.reql = "default", match this with Return -> true :> obj | Skip -> false | Error -> RethinkDB.R.Error()
member this.reql = "default", match this with Return -> true :> obj | Skip -> false | Error -> RethinkDB.R.Error ()
/// Optional arguments for the `filter` statement
@ -106,7 +106,7 @@ type FilterOptArg =
module FilterOptArg =
/// Apply an option argument to the filter statement
let apply arg (f: Filter) =
let apply arg (f : Filter) =
match arg with Default d -> f.OptArg d.reql
@ -124,8 +124,8 @@ type IndexCreateOptArg =
module IndexCreateOptArg =
/// Apply a list of optional arguments to an indexCreate statement
let apply (opts: IndexCreateOptArg list) (ic: IndexCreate) =
opts |> List.fold (fun (idxC: IndexCreate) arg -> idxC.OptArg arg.reql) ic
let apply (opts : IndexCreateOptArg list) (ic : IndexCreate) =
opts |> List.fold (fun (idxC : IndexCreate) arg -> idxC.OptArg arg.reql) ic
/// How to handle an insert conflict
@ -141,7 +141,7 @@ type Conflict =
/// The ReQL for the conflict parameter
member this.reql =
let value: obj =
let value : obj =
match this with
| Error -> "error"
| Replace -> "replace"
@ -159,7 +159,7 @@ type IndexRenameOptArg =
module IndexRenameOptArg =
/// Apply an optional argument to an indexRename statement
let apply opt (ir: IndexRename) =
let apply opt (ir : IndexRename) =
ir.OptArg("overwrite", match opt with FailIfExists -> false | Overwrite -> true)
@ -178,14 +178,14 @@ type InsertOptArg =
module InsertOptArg =
/// Apply a list of optional arguments to an insert statement
let apply (opts: InsertOptArg list) (i: Insert) =
let apply (opts : InsertOptArg list) (i : Insert) =
opts
|> List.fold (fun (ins: Insert) arg ->
|> List.fold (fun (ins : Insert) arg ->
match arg with
| Durability dur -> ins.OptArg dur.reql
| ReturnChanges chg -> ins.OptArg chg.reql
| OnConflict con -> ins.OptArg con.reql
| IgnoreWriteHook ign -> ins.OptArg("ignore_write_hook", ign))
| IgnoreWriteHook ign -> ins.OptArg ("ignore_write_hook", ign))
i
@ -204,14 +204,14 @@ type ReplaceOptArg =
module ReplaceOptArg =
/// Apply a list of optional arguments to a replace statement
let apply opts (r: Replace) =
let apply opts (r : Replace) =
opts
|> List.fold (fun (rep: Replace) arg ->
|> List.fold (fun (rep : Replace) arg ->
match arg with
| Durability dur -> rep.OptArg dur.reql
| ReturnChanges chg -> rep.OptArg chg.reql
| NonAtomic non -> rep.OptArg("non_atomic", non)
| IgnoreWriteHook ign -> rep.OptArg("ignore_write_hook", ign))
| NonAtomic non -> rep.OptArg ("non_atomic", non)
| IgnoreWriteHook ign -> rep.OptArg ("ignore_write_hook", ign))
r
@ -285,7 +285,7 @@ type RunOptArg =
| MaxBatchBytes max -> "max_batch_bytes", max
| MaxBatchSeconds max -> "max_batch_seconds", max
| FirstBatchScaleDownFactor fac -> "first_batch_scaledown_factor", fac
fst pair, RethinkDB.R.Expr(snd pair)
fst pair, RethinkDB.R.Expr (snd pair)
/// Function to support `run` optional arguments
module RunOptArg =
@ -293,8 +293,8 @@ module RunOptArg =
open RethinkDb.Driver.Model
/// Create optional argument for a run command
let create (opts: RunOptArg list) =
let args = OptArgs()
let create (opts : RunOptArg list) =
let args = OptArgs ()
opts |> List.iter (fun arg -> args.Add arg.reql)
args
@ -326,26 +326,26 @@ type TableCreateOptArg =
module TableCreateOptArg =
/// Apply a list of optional arguments to a tableCreate statement
let apply opts (tc: TableCreate) =
let apply opts (tc : TableCreate) =
opts
|> List.fold (fun (tc: TableCreate) arg ->
|> List.fold (fun (tc : TableCreate) arg ->
match arg with
| PrimaryKey pk -> tc.OptArg("primary_key", pk)
| PrimaryKey pk -> tc.OptArg ("primary_key", pk)
| Durability dur -> tc.OptArg dur.reql
| Shards sh -> tc.OptArg("shards", sh)
| Shards sh -> tc.OptArg ("shards", sh)
| Replicas rep ->
match rep with
| Number count -> tc.OptArg("replicas", count)
| Number count -> tc.OptArg ("replicas", count)
| WithTags (primary, all) ->
let (ReplicaTag (firstTag, firstCount)) = List.head all
let replica =
all
|> List.skip 1
|> List.fold (fun (h: Model.MapObject) arg ->
|> List.fold (fun (h : Model.MapObject) arg ->
let (ReplicaTag (tag, count)) = arg
h.With (tag, count))
(RethinkDB.R.HashMap(firstTag, firstCount))
tc.OptArg("replicas", replica).OptArg("primary_replica_tag", primary)
(RethinkDB.R.HashMap (firstTag, firstCount))
tc.OptArg("replicas", replica).OptArg ("primary_replica_tag", primary)
)
tc
@ -365,12 +365,13 @@ type UpdateOptArg =
module UpdateOptArg =
/// Apply a list of optional arguments to an update statement
let apply opts (u: Update) =
let apply opts (u : Update) =
opts
|> List.fold (fun (upd: Update) arg ->
|> List.fold (fun (upd : Update) arg ->
match arg with
| Durability dur -> upd.OptArg dur.reql
| ReturnChanges chg -> upd.OptArg chg.reql
| NonAtomic non -> upd.OptArg("non_atomic", non)
| IgnoreWriteHook ign -> upd.OptArg("ignore_write_hook", ign))
| NonAtomic non -> upd.OptArg ("non_atomic", non)
| IgnoreWriteHook ign -> upd.OptArg ("ignore_write_hook", ign))
u

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<TargetFrameworks>net6.0;netstandard2.0</TargetFrameworks>
<Description>Idiomatic F# extensions on the official RethinkDB C# driver</Description>
<Authors>Daniel J. Summers,Bit Badger Solutions</Authors>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
@ -13,7 +13,8 @@
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<Copyright>See LICENSE</Copyright>
<PackageTags>RethinkDB document F#</PackageTags>
<VersionPrefix>1.0.0</VersionPrefix>
<VersionPrefix>0.9.0</VersionPrefix>
<VersionSuffix>beta-07</VersionSuffix>
<PackageReleaseNotes>
Add URI config option and logging CreateConnection overloads
</PackageReleaseNotes>
@ -31,11 +32,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Polly" Version="8.5.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="RethinkDb.Driver" Version="2.*" />
<PackageReference Update="FSharp.Core" Version="9.0.100" />
<PackageReference Update="FSharp.Core" Version="6.0.3" />
</ItemGroup>
</Project>

View File

@ -7,23 +7,23 @@ open RethinkDb.Driver
open RethinkDb.Driver.Net
/// Create a retry policy that attempts to reconnect to RethinkDB on each retry
let retryPolicy (intervals: float seq) (conn: IConnection) =
let retryPolicy (intervals : float seq) (conn : IConnection) =
Policy
.Handle<ReqlDriverError>()
.WaitAndRetryAsync(
intervals |> Seq.map TimeSpan.FromSeconds,
System.Action<exn, TimeSpan, int, Context>(fun ex _ _ _ ->
System.Action<exn, TimeSpan, int, Context> (fun ex _ _ _ ->
printfn $"Encountered RethinkDB exception: {ex.Message}"
printfn "Reconnecting to RethinkDB..."
(conn :?> Connection).Reconnect false))
/// Create a retry policy that attempts to reconnect to RethinkDB when a synchronous operation encounters an error
let retryPolicySync (intervals: float seq) (conn: IConnection) =
let retryPolicySync (intervals : float seq) (conn : IConnection) =
Policy
.Handle<ReqlDriverError>()
.WaitAndRetry(
intervals |> Seq.map TimeSpan.FromSeconds,
System.Action<exn, TimeSpan, int, Context>(fun ex _ _ _ ->
System.Action<exn, TimeSpan, int, Context> (fun ex _ _ _ ->
printf $"Encountered RethinkDB exception: {ex.Message}"
match ex.Message.Contains "socket" with
| true ->