Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add examples #49

Merged
merged 6 commits into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
- Move examples from [separated repo](https://github.com/ydb-platform/ydb-dotnet-examples)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need changelog for examples

- Adjust .NET and SDK versions

## v0.1.3
- Add static auth
## v0.1.1
Expand Down
35 changes: 35 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# YDB .NET SDK Examples

## Prerequisites
.NET 6

## Running examples

1. Clone repository
```bash
git clone https://github.com/ydb-platform/ydb-dotnet-sdk.git
```

2. Build solution
```bash
cd ydb-dotnet-sdk/examples/src
dotnet build
```

3. Run example
```bash
cd <ExampleName>
dotnet run -e <Endpoint> -d <Database>
```

## Provided examples

### BasicExample
Demonstrates basic operations with YDB, including:
* Driver initialization
* Table client initialization
* Table creation via SchemeQuery (DDL)
* Data queries (OLTP) & transactions (read, modify)
* Interactive transactions
* ReadTable for streaming read of table contents
* ScanQuery for streaming wide queries (OLAP)
81 changes: 81 additions & 0 deletions examples/src/BasicExample/BasicExample.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Ydb.Sdk.Auth;
using Ydb.Sdk.Services.Table;

namespace Ydb.Sdk.Examples;

internal partial class BasicExample : TableExampleBase
{
private BasicExample(TableClient client, string database, string path)
: base(client, database, path)
{
}

public static async Task Run(
string endpoint,
string database,
ICredentialsProvider credentialsProvider,
X509Certificate? customServerCertificate,
string path,
ILoggerFactory loggerFactory)
{
var config = new DriverConfig(
endpoint: endpoint,
database: database,
credentials: credentialsProvider,
customServerCertificate: customServerCertificate
);

await using var driver = await Driver.CreateInitialized(
config: config,
loggerFactory: loggerFactory
);

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

var example = new BasicExample(tableClient, database, path);

await example.SchemeQuery();
await example.FillData();
await example.SimpleSelect(1);
await example.SimpleUpsert(10, "Coming soon", DateTime.UtcNow);
await example.SimpleSelect(10);
await example.InteractiveTx();
await example.ReadTable();
await example.ScanQuery(DateTime.Parse("2007-01-01"));
}

private static ExecuteDataQuerySettings DefaultDataQuerySettings =>
new()
{
// Indicates that client is no longer interested in the result of operation after the
// specified duration starting from the moment when operation arrives at the server.
// Status code TIMEOUT will be returned from server in case when operation result in
// not available in the specified time period. This status code doesn't indicate the result
// of operation, it might be completed or cancelled.
OperationTimeout = TimeSpan.FromSeconds(1),

// Transport timeout from the moment operation was sent to server. It is useful in case
// of possible network issues, to that query doesn't hang forever.
// It is recommended to set this value to a larger value than OperationTimeout to give
// server some time to issue a response.
TransportTimeout = TimeSpan.FromSeconds(5),

// Keep query compilation result in query cache or not. Should be false for ad-hoc queries,
// and true (default) for high-RPS queries.
KeepInQueryCache = false
};

private ExecuteDataQuerySettings DefaultCachedDataQuerySettings
{
get
{
var settings = DefaultDataQuerySettings;
settings.KeepInQueryCache = true;
return settings;
}
}
}
28 changes: 28 additions & 0 deletions examples/src/BasicExample/BasicExample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<AssemblyName>Ydb.Sdk.Examples.BasicExample</AssemblyName>
<RootNamespace>Ydb.Sdk.Examples</RootNamespace>
</PropertyGroup>

<PropertyGroup>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/ydb-platform/ydb-dotnet-examples</RepositoryUrl>
<PackageProjectUrl>https://github.com/ydb-platform/ydb-dotnet-examples</PackageProjectUrl>
<Company>YANDEX LLC</Company>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.8.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="5.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj" />
</ItemGroup>

</Project>
88 changes: 88 additions & 0 deletions examples/src/BasicExample/DataQuery.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Ydb.Sdk.Services.Table;
using Ydb.Sdk.Value;

namespace Ydb.Sdk.Examples;

internal partial class BasicExample
{
private async Task SimpleSelect(ulong id)
{
var response = await Client.SessionExec(async session =>
{
var query = @$"
PRAGMA TablePathPrefix('{BasePath}');
DECLARE $id AS Uint64;
SELECT
series_id,
title,
release_date
FROM series
WHERE series_id = $id;
";
return await session.ExecuteDataQuery(
query: query,
txControl: TxControl.BeginSerializableRW().Commit(),
parameters: new Dictionary<string, YdbValue>
{
{ "$id", YdbValue.MakeUint64(id) }
},
settings: DefaultCachedDataQuerySettings
);
});

response.Status.EnsureSuccess();

var queryResponse = (ExecuteDataQueryResponse)response;
var resultSet = queryResponse.Result.ResultSets[0];

Console.WriteLine($"> SimpleSelect, " +
$"columns: {resultSet.Columns.Count}, " +
$"rows: {resultSet.Rows.Count}, " +
$"truncated: {resultSet.Truncated}");

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

private async Task SimpleUpsert(ulong id, string title, DateTime date)
{
var response = await Client.SessionExec(async session =>
{
var query = @$"
PRAGMA TablePathPrefix('{BasePath}');
DECLARE $id AS Uint64;
DECLARE $title AS Utf8;
DECLARE $release_date AS Date;
UPSERT INTO series (series_id, title, release_date) VALUES
($id, $title, $release_date);
";
return await session.ExecuteDataQuery(
query: query,
txControl: TxControl.BeginSerializableRW().Commit(),
parameters: new Dictionary<string, YdbValue>
{
{ "$id", YdbValue.MakeUint64(id) },
{ "$title", YdbValue.MakeUtf8(title) },
{ "$release_date", YdbValue.MakeDate(date) }
},
settings: DefaultCachedDataQuerySettings
);
});

response.Status.EnsureSuccess();
}
}
Loading
Loading