Client



NTDLS.Katzebase.Api is the .NET client library for Katzebase. Get it from NuGet. The management UI and the migration tools are built on the same library.
  • A KbClient is one connection and one server session. A session has at most one open transaction, and every request made through the client, from any thread, shares it. Use one client per independent unit of work.
  • Every method has an ...Async version that accepts a CancellationToken.
  • Every method accepts an optional timeout; the default is the client's QueryTimeout (30 seconds).


using NTDLS.Katzebase.Api;

using var client = new KbClient("localhost", 6858, "admin", KbClient.HashPassword(""), "MyApplication");

The password is sent as its SHA-256 hash, see KbClient.HashPassword. Disposing the client (or calling Disconnect) ends the session and rolls back any open transaction. The OnConnected, OnDisconnected and OnCommunicationException events report the state of the connection.

Method Returns
Query.Fetch(sql) Every result set, with field names and rows of strings.
Query.Fetch(sql) The rows mapped to a List by field name.
Query.FetchFirst, FetchFirstOrDefault The first row (or default when there are no rows).
Query.FetchSingle, FetchSingleOrDefault The only row; throws when there is more than one.
Query.FetchScalar(sql) The first value of the first row.
Query.ExecuteNonQuery(sql) For statements that don't return rows; the reply's RowCount is the number of affected documents.
Query.ExplainPlan(sql), ExplainOperation(sql) How the query will be executed, including the indexes it will use. ExplainPlan also suggests indexes that would avoid reading every document.


Parameters are passed as an anonymous object, any object, or a dictionary of names to values, and are referenced in the statement with an @ prefix. Values are sent independently of the client's culture: numbers in invariant format, booleans as 1/0, enums as numbers and dates in ISO 8601.
var words = client.Query.Fetch<Word>(
    "SELECT * FROM WordList:Word WHERE LanguageId = @LanguageId AND Text LIKE @Pattern",
    new { LanguageId = 1, Pattern = "Cat%" });

var count = client.Query.FetchScalar<int>("SELECT Count(0) FROM WordList:Word");

Result fields are mapped to writable properties of the same name (not case-sensitive). Values are converted culture-invariantly, and nullable types and enums are supported.

Method Description
Document.Store(schema, document) Stores a document (an object, a JSON object string or a KbDocument) and returns its new id.
Document.StoreMany(schema, documents) Stores a batch of documents in one round trip and one transaction, and returns their ids in order. The fastest way to load data.
Document.Get(schema, id), Get Reads a document by id, or null when it does not exist.
Document.Replace(schema, id, document) Replaces the whole document and updates its indexes.
Document.Delete(schema, id), DeleteMany Deletes documents by id and reports how many were deleted.
Document.List(schema, count), Sample(schema, count) Lists the first documents, or a random sample.

uint id = client.Document.Store("WordList:Word", new { Text = "Cat", LanguageId = 1 });
var word = client.Document.Get<Word>("WordList:Word", id);
client.Document.Replace("WordList:Word", id, new { Text = "Cats", LanguageId = 1 });
client.Document.Delete("WordList:Word", id);


Method Description
Schema.Create, CreateRecursive Creates a schema; CreateRecursive also creates any missing parents.
Schema.Exists, List, Drop, DropIfExists Checks for, lists and drops schemas.
Schema.FieldSample(schema) Returns a sample of the fields used by a schema's documents.
Schema.Attach(schema, folder), Detach(schema, folder) See Attach Schema and Detach Schema.
Schema.Indexes.Create, Exists, Get, List, Rebuild, Drop Manages indexes; set IsUnique on a KbIndex to create a unique key.

client.Schema.CreateRecursive("Sales:Orders");
client.Schema.Indexes.Create("Sales:Orders", new KbIndex("IX_Customer", ["Customer"]));
client.Schema.Indexes.Create("Sales:Orders", new KbIndex("UK_OrderNumber", ["OrderNumber"]) { IsUnique = true });


Transaction.Begin() returns a scope. Disposing the scope rolls the transaction back unless Commit() was called.
using (var transaction = client.Transaction.Begin())
{
    client.Document.StoreMany("Sales:Orders", orders);
    client.Query.ExecuteNonQuery("UPDATE Sales:Customers SET HasOrders = 1 WHERE Id = @Id", new { Id = customerId });
    transaction.Commit();
}

Committing when there is no open transaction throws KbTransactionCancelledException; this happens when the server has already rolled the transaction back, for example after choosing it as a deadlock victim.

Server errors are thrown as the same exception type the server raised, all deriving from KbExceptionBase:
Exception When
KbParserException The statement could not be parsed; LineNumber is the line in the script.
KbObjectNotFoundException A schema, index or document does not exist.
KbDuplicateKeyViolationException A unique key was violated.
KbDeadlockException The transaction was chosen as a deadlock victim and rolled back; retry it.
KbTransactionCancelledException The transaction was cancelled or rolled back.
KbTimeoutException The server did not reply in time.
KbConnectionException The client is not connected, or the connection was lost.
KbProcessingException, KbEngineException Other errors raised while processing the request.


Server.TerminateProcess(processId) terminates another session, like Terminate.



Home
The home page
SQL :: Alter Schema
Creates, alters and drops schemas.
SQL :: Attach Schema
Copies a detached schema (namespace) into the database.
SQL :: Cancel
Cancels (rolls back) the transaction of the given process, leaving the process connected.
SQL :: Declare
Declares a variable for the rest of a script.
SQL :: Detach Schema
Removes a schema (namespace) from the database and moves its files to a folder.
SQL :: DocumentID
Removed: The DocumentID() function is no longer available.
SQL :: DocumentUID
Removed: The DocumentUID() function is no longer available.
SQL :: Expressions
Literals, operators, comments and variables in KBSQL.
SQL :: Insert
Insert creates new documents in a schema.