Loading…

BitBadger.Documents
Basic Usage

Overview

There are several categories of operations that can be accomplished against documents.

Insert and Save were the only two that don't mention criteria. For the others, “some criteria” can be defined a few different ways:

Finally, Find also has FirstBy* implementations for all supported criteria types.

Saving Documents

The library provides three different ways to save data. The first equates to a SQL INSERT statement, and adds a single document to the repository.

// C#, All
    var room = new Room(/* ... */);
    // Parameters are table name and document
    await Document.Insert("room", room);
// F#, All
    let room = { Room.empty with (* ... *) }
    do! insert "room" room

The second is Save; and inserts the data it if does not exist and replaces the document if it does exist (what some call an “upsert”). It utilizes the ON CONFLICT syntax to ensure an atomic statement. Its parameters are the same as those for Insert.

The third equates to a SQL UPDATE statement. Update applies to a full document and is usually used by ID, while Patch is used for partial updates and may be done by field comparison, JSON containment, or JSON Path match. For a few examples, let's begin with a query that may back the “edit hotel” page. This page lets the user update nearly all the details for the hotel, so updating the entire document would be appropriate.

// C#, All
    var hotel = await Document.Find.ById<Hotel>("hotel", hotelId);
    if (!(hotel is null))
    {
        // update hotel properties from the posted form
        await Update.ById("hotel", hotel.Id, hotel);
    }
// F#, All
    match! Find.byId<Hotel> "hotel" hotelId with
    | Some hotel ->
        do! Update.byId "hotel" hotel.Id updated
                { hotel with (* properties from posted form *) }
    | None -> ()

For the next example, suppose we are upgrading our hotel, and need to take rooms 221-240 out of service*. We can utilize a patch via JSON Path** to accomplish this.

// C#, PostgreSQL
    await Patch.ByJsonPath("room",
        "$ ? (@.HotelId == \"abc\" && (@.RoomNumber >= 221 && @.RoomNumber <= 240)",
        new { InService = false });
// F#, PostgreSQL
    do! Patch.byJsonPath "room"
            "$ ? (@.HotelId == \"abc\" && (@.RoomNumber >= 221 && @.RoomNumber <= 240)"
            {| InService = false |};

* - we are ignoring the current reservations, end date, etc. This is very naïve example!

** - For SQLite, this will require a custom query; it is presented below, but custom queries are fully explained in the Advanced Usage section.

// C#, SQLite
    await Custom.NonQuery(
        $"UPDATE room SET data = json_patch(data, json(@data)) WHERE data ->> 'RoomNumber' BETWEEN 221 AND 240",
        new[] { Parameters.Json("@data", new { InService = false }) }); 

There is an Update.ByFunc variant that takes an ID extraction function run against the document instead of its ID. This is detailed in the Advanced Usage section.

Finding Documents

Functions to find documents start with Find.. There are variants to find all documents in a table, find by ID, find by JSON field comparison, find by JSON containment, or find by JSON Path. The hotel update example above utilizes an ID lookup; the descriptions of JSON containment and JSON Path show examples of the criteria used to retrieve using those techniques.

Find methods and functions are generic; specifying the return type is crucial. Additionally, ById will need the type of the key being passed. In C#, ById and the FirstBy* methods will return TDoc?, with the value if it was found or null if it was not; All and other By* methods return List<TDoc> (from System.Collections.Generic). In F#, byId and the firstBy* functions will return 'TDoc option; all and other by* functions return 'TDoc list.

Deleting Documents

Functions to delete documents start with Delete.. Document deletion is supported by ID, JSON field comparison, JSON containment, or JSON Path match. The pattern is the same as for finding or partially updating. (There is no library method provided to delete all documents, though deleting by JSON field comparison where a non-existent field is null would accomplish this.)

Counting Documents

Functions to count documents start with Count.. Documents may be counted by a table in its entirety, by JSON field comparison, by JSON containment, or by JSON Path match. (Counting by ID is an existence check!)

Document Existence

Functions to check for existence start with Exists.. Documents may be checked for existence by ID, JSON field comparison, JSON containment, or JSON Path match.

What / How Cross-Reference

The table below shows which commands are available for each access method. (X = supported for both, P = PostgreSQL only)

Operation All ById ByField ByContains ByJsonPath FirstByField FirstByContains FirstByJsonPath
Count X X P P
Exists X X P P
Find X X X P P X P P
Patch X X P P
RemoveFields X X P P
Delete X X P P

Insert, Save, and Update.* operate on single documents.