App in C# (.NET)

This page contains a detailed description of the code of a test app that uses the C# (.NET) SDK YDB.

Note

The article is being updated.

Initializing a database connection

To interact with YDB, create an instance of the driver, client, and session:

  • The YDB driver lets the app and YDB interact at the transport layer. The driver must exist throughout the YDB access lifecycle and be initialized before creating a client or session.
  • The YDB client runs on top of the YDB driver and enables the handling of entities and transactions.
  • The YDB session contains information about executed transactions and prepared queries, and is part of the YDB client context.

App code snippet for driver initialization:

  1. public static async Task Run(
  2. string endpoint,
  3. string database,
  4. ICredentialsProvider credentialsProvider)
  5. {
  6. var config = new DriverConfig(
  7. endpoint: endpoint,
  8. database: database,
  9. credentials: credentialsProvider
  10. );
  11. using var driver = new Driver(
  12. config: config
  13. );
  14. await driver.Initialize();
  15. }

C# (.NET) - 图1

App code snippet for creating a session:

  1. using var tableClient = new TableClient(driver, new TableClientConfig());

C# (.NET) - 图2

Creating tables

Creating tables to be used in operations on a test app. This step results in the creation of DB tables of the series directory data model:

  • Series
  • Seasons
  • Episodes

Once the tables are created, the method for getting information about data schema objects is called and the result of its execution is output.

To create tables, use the session.ExecuteSchemeQuery method with a DDL (Data Definition Language) YQL query.

  1. var response = await tableClient.SessionExec(async session =>
  2. {
  3. return await session.ExecuteSchemeQuery(@"
  4. CREATE TABLE series (
  5. series_id Uint64,
  6. title Utf8,
  7. series_info Utf8,
  8. release_date Date,
  9. PRIMARY KEY (series_id)
  10. );
  11. CREATE TABLE seasons (
  12. series_id Uint64,
  13. season_id Uint64,
  14. title Utf8,
  15. first_aired Date,
  16. last_aired Date,
  17. PRIMARY KEY (series_id, season_id)
  18. );
  19. CREATE TABLE episodes (
  20. series_id Uint64,
  21. season_id Uint64,
  22. episode_id Uint64,
  23. title Utf8,
  24. air_date Date,
  25. PRIMARY KEY (series_id, season_id, episode_id)
  26. );
  27. ");
  28. });
  29. response.Status.EnsureSuccess();

C# (.NET) - 图3

Adding data

Adding data to the created tables using an UPSERT statement of YQL. A data update request is sent within a single request to the server with transaction auto-commit mode enabled.

Code snippet for inserting and updating data:

  1. var response = await tableClient.SessionExec(async session =>
  2. {
  3. var query = @"
  4. DECLARE $id AS Uint64;
  5. DECLARE $title AS Utf8;
  6. DECLARE $release_date AS Date;
  7. UPSERT INTO series (series_id, title, release_date) VALUES
  8. ($id, $title, $release_date);
  9. ";
  10. return await session.ExecuteDataQuery(
  11. query: query,
  12. txControl: TxControl.BeginSerializableRW().Commit(),
  13. parameters: new Dictionary<string, YdbValue>
  14. {
  15. { "$id", YdbValue.MakeUint64(1) },
  16. { "$title", YdbValue.MakeUtf8("NewTitle") },
  17. { "$release_date", YdbValue.MakeDate(DateTime.UtcNow) }
  18. }
  19. );
  20. });
  21. response.Status.EnsureSuccess();

C# (.NET) - 图4

PRAGMA TablePathPrefix adds a specified prefix to the database table paths. It uses standard file system path concatenation: i.e., it supports parent folder referencing and requires no trailing slash. For example:

  1. PRAGMA TablePathPrefix = "/cluster/database";
  2. SELECT * FROM episodes;

C# (.NET) - 图5

For more information about PRAGMA YQL, see the YQL documentation.

Retrieving data with a Select

Retrieving data using a SELECT statement in YQL. Handling the retrieved data selection in the app.

To execute YQL queries, use the Session.executeDataQuery() method. The SDK lets you explicitly control the execution of transactions and configure the transaction execution mode using the TxControl class. In the code snippet below, a transaction with the SerializableRW mode and an automatic commit after executing the request is used. The values of the request parameters are passed in the form of a dictionary name-value in the parameters argument.

  1. var response = await tableClient.SessionExec(async session =>
  2. {
  3. var query = @"
  4. DECLARE $id AS Uint64;
  5. SELECT
  6. series_id,
  7. title,
  8. release_date
  9. FROM series
  10. WHERE series_id = $id;
  11. ";
  12. return await session.ExecuteDataQuery(
  13. query: query,
  14. txControl: TxControl.BeginSerializableRW().Commit(),
  15. parameters: new Dictionary<string, YdbValue>
  16. {
  17. { "$id", YdbValue.MakeUint64(id) }
  18. },
  19. );
  20. });
  21. response.Status.EnsureSuccess();
  22. var queryResponse = (ExecuteDataQueryResponse)response;
  23. var resultSet = queryResponse.Result.ResultSets[0];

C# (.NET) - 图6

Processing execution results

The result of query execution (resultset) consists of an organized set of rows. Example of processing the query execution result:

  1. foreach (var row in resultSet.Rows)
  2. {
  3. Console.WriteLine($"> Series, " +
  4. $"series_id: {(ulong?)row["series_id"]}, " +
  5. $"title: {(string?)row["title"]}, " +
  6. $"release_date: {(DateTime?)row["release_date"]}");
  7. }

C# (.NET) - 图7

Scan queries

Making a scan query that results in a data stream. Streaming lets you read an unlimited number of rows and amount of data.

  1. public void executeScanQuery()
  2. {
  3. var scanStream = TableClient.ExecuteScanQuery(@$"
  4. SELECT series_id, season_id, COUNT(*) AS episodes_count
  5. FROM episodes
  6. GROUP BY series_id, season_id
  7. ORDER BY series_id, season_id;
  8. ");
  9. while (await scanStream.Next())
  10. {
  11. scanStream.Response.EnsureSuccess();
  12. var resultSet = scanStream.Response.Result.ResultSetPart;
  13. if (resultSet != null)
  14. {
  15. foreach (var row in resultSet.Rows)
  16. {
  17. Console.WriteLine($"> ScanQuery, " +
  18. $"series_id: {(ulong?)row["series_id"]}, " +
  19. $"season_id: {(ulong?)row["season_id"]}, " +
  20. $"episodes_count: {(ulong)row["episodes_count"]}");
  21. }
  22. }
  23. }
  24. }

C# (.NET) - 图8