diff --git a/.gitignore b/.gitignore index d15f8e6..0c35d68 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ -# Created by https://www.toptal.com/developers/gitignore/api/java,gradle,intellij -# Edit at https://www.toptal.com/developers/gitignore?templates=java,gradle,intellij +# Created by https://www.toptal.com/developers/gitignore/api/java,gradle,intellij,visualstudio +# Edit at https://www.toptal.com/developers/gitignore?templates=java,gradle,intellij,visualstudio ### Intellij ### # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider @@ -132,4 +132,404 @@ gradle-app.setting ### Gradle Patch ### **/build/ -# End of https://www.toptal.com/developers/gitignore/api/java,gradle,intellij +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/java,gradle,intellij,visualstudio diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/GetCustomerInfoCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/GetCustomerInfoCommand.cs new file mode 100644 index 0000000..0348e66 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/GetCustomerInfoCommand.cs @@ -0,0 +1,31 @@ +using System.CommandLine; + +namespace ScalarDbClusterSample.Commands; + +public static class GetCustomerInfoCommand +{ + private const string Name = "GetCustomerInfo"; + private const string Description = "Get customer information"; + + private const string ArgName = "id"; + private const string ArgDescription = "customer ID"; + + public static Command Create() + { + var customerIdArg = new Argument(ArgName, ArgDescription); + var getCustomerInfoCommand = new Command(Name, Description) + { + customerIdArg + }; + + getCustomerInfoCommand.SetHandler(async customerId => + { + using var sample = new Sample(); + var customerInfo = await sample.GetCustomerInfo(customerId); + + Console.WriteLine(customerInfo); + }, customerIdArg); + + return getCustomerInfoCommand; + } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/GetOrderCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/GetOrderCommand.cs new file mode 100644 index 0000000..9301772 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/GetOrderCommand.cs @@ -0,0 +1,31 @@ +using System.CommandLine; + +namespace ScalarDbClusterSample.Commands; + +public static class GetOrderCommand +{ + private const string Name = "GetOrder"; + private const string Description = "Get order information by order ID"; + + private const string ArgName = "id"; + private const string ArgDescription = "order ID"; + + public static Command Create() + { + var orderIdArg = new Argument(ArgName, ArgDescription); + var getOrderCommand = new Command(Name, Description) + { + orderIdArg + }; + + getOrderCommand.SetHandler(async orderId => + { + using var sample = new Sample(); + var order = await sample.GetOrderByOrderId(orderId); + + Console.WriteLine(order); + }, orderIdArg); + + return getOrderCommand; + } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/GetOrdersCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/GetOrdersCommand.cs new file mode 100644 index 0000000..4464971 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/GetOrdersCommand.cs @@ -0,0 +1,31 @@ +using System.CommandLine; + +namespace ScalarDbClusterSample.Commands; + +public static class GetOrdersCommand +{ + private const string Name = "GetOrders"; + private const string Description = "Get information about orders by customer ID"; + + private const string ArgName = "customer_id"; + private const string ArgDescription = "customer ID"; + + public static Command Create() + { + var customerIdArg = new Argument(ArgName, ArgDescription); + var getOrdersCommand = new Command(Name, Description) + { + customerIdArg + }; + + getOrdersCommand.SetHandler(async customerId => + { + using var sample = new Sample(); + var orders = await sample.GetOrdersByCustomerId(customerId); + + Console.WriteLine(orders); + }, customerIdArg); + + return getOrdersCommand; + } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/LoadInitialDataCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/LoadInitialDataCommand.cs new file mode 100644 index 0000000..60e7392 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/LoadInitialDataCommand.cs @@ -0,0 +1,45 @@ +using System.CommandLine; +using System.Diagnostics; +using ScalarDB.Client.Exceptions; + +namespace ScalarDbClusterSample.Commands; + +public static class LoadInitialDataCommand +{ + private const string Name = "LoadInitialData"; + private const string Description = "Load initial data"; + + public static Command Create() + { + var loadInitialDataCommand = new Command(Name, Description); + loadInitialDataCommand.SetHandler(async () => + { + using var sample = new Sample(); + await sample.CreateTables(); + + IllegalArgumentException? lastException = null; + var attempts = 10; + while (attempts-- > 0) + { + try + { + await sample.LoadInitialData(); + return; + } + catch (IllegalArgumentException ex) + { + // there's can be a lag until ScalarDB Cluster recognize namespaces and tables created + // in some databases like Cassandra, so if this command was called for the first time + // the first attempts can fail with 'The namespace does not exist' error + lastException = ex; + await Task.Delay(TimeSpan.FromSeconds(1)); + } + } + + Debug.Assert(lastException != null); + throw lastException; + }); + + return loadInitialDataCommand; + } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/PlaceOrderCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/PlaceOrderCommand.cs new file mode 100644 index 0000000..74c6e9b --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/PlaceOrderCommand.cs @@ -0,0 +1,54 @@ +using System.CommandLine; + +namespace ScalarDbClusterSample.Commands; + +public static class PlaceOrderCommand +{ + private const string Name = "PlaceOrder"; + private const string Description = "Place an order"; + + private const string ArgName1 = "customer_id"; + private const string ArgDescription1 = "customer ID"; + private const string ArgName2 = "orders"; + private const string ArgDescription2 = "orders. The format is \":,:,...\""; + + public static Command Create() + { + var customerIdArg = new Argument(ArgName1, ArgDescription1); + var ordersArg = new Argument>( + name: ArgName2, + parse: arg => + { + var argStr = arg.Tokens.First().Value; + var orders = argStr + .Split(',') + .Select(s => s.Split(':')) + .ToDictionary( + s => Int32.Parse(s[0]), + s => Int32.Parse(s[1]) + ); + + return orders; + }, + description: ArgDescription2) + { + Arity = ArgumentArity.ExactlyOne + }; + + var placeOrderCommand = new Command(Name, Description) + { + customerIdArg, + ordersArg + }; + + placeOrderCommand.SetHandler(async (customerId, orders) => + { + using var sample = new Sample(); + var order = await sample.PlaceOrder(customerId, orders); + + Console.WriteLine(order); + }, customerIdArg, ordersArg); + + return placeOrderCommand; + } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/RepaymentCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/RepaymentCommand.cs new file mode 100644 index 0000000..e1d56c5 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/RepaymentCommand.cs @@ -0,0 +1,33 @@ +using System.CommandLine; + +namespace ScalarDbClusterSample.Commands; + +public static class RepaymentCommand +{ + private const string Name = "Repayment"; + private const string Description = "Repayment"; + + private const string ArgName1 = "customer_id"; + private const string ArgDescription1 = "customer ID"; + private const string ArgName2 = "amount"; + private const string ArgDescription2 = "amount of the money for repayment"; + + public static Command Create() + { + var customerIdArg = new Argument(ArgName1, ArgDescription1); + var amountArg = new Argument(ArgName2, ArgDescription2); + var repaymentCommand = new Command(Name, Description) + { + customerIdArg, + amountArg + }; + + repaymentCommand.SetHandler(async (customerId, amount) => + { + using var sample = new Sample(); + await sample.Repayment(customerId, amount); + }, customerIdArg, amountArg); + + return repaymentCommand; + } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/Program.cs b/scalardb-dotnet-samples/scalardb-cluster-sample/Program.cs new file mode 100644 index 0000000..dc1208f --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/Program.cs @@ -0,0 +1,14 @@ +using System.CommandLine; +using ScalarDbClusterSample.Commands; + +var rootCommand = new RootCommand("Sample application for ScalarDB Cluster .NET Client SDK") + { + LoadInitialDataCommand.Create(), + GetCustomerInfoCommand.Create(), + GetOrderCommand.Create(), + GetOrdersCommand.Create(), + PlaceOrderCommand.Create(), + RepaymentCommand.Create() + }; + +await rootCommand.InvokeAsync(args); diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/Sample.cs b/scalardb-dotnet-samples/scalardb-cluster-sample/Sample.cs new file mode 100644 index 0000000..73ce934 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/Sample.cs @@ -0,0 +1,475 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; +using Microsoft.Extensions.Logging; +using ScalarDB.Client; +using ScalarDB.Client.Builders; +using ScalarDB.Client.Builders.Admin; +using ScalarDB.Client.Core; +using ScalarDB.Client.Exceptions; + +namespace ScalarDbClusterSample; + +public class Sample: IDisposable +{ + private readonly TransactionFactory _factory; + private readonly IDistributedTransactionManager _manager; + + public Sample() + { + var loggerFactory = LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Warning); + builder.AddSimpleConsole(options => { options.TimestampFormat = "HH:mm:ss "; }); + }); + + _factory = TransactionFactory.Create("scalardb-options.json", loggerFactory); + _manager = _factory.GetTransactionManager(); + } + + public async Task CreateTables() + { + using var admin = _factory.GetTransactionAdmin(); + + var customersTableMetadata = + new TableMetadataBuilder() + .AddPartitionKey("customer_id", DataType.Int) + .AddColumn("name", DataType.Text) + .AddColumn("credit_limit", DataType.Int) + .AddColumn("credit_total", DataType.Int) + .Build(); + + var ordersTableMetadata = + new TableMetadataBuilder() + .AddSecondaryIndex("order_id", DataType.Text) + .AddPartitionKey("customer_id", DataType.Int) + .AddClusteringKey("timestamp", DataType.Bigint) + .Build(); + + var statementsTableMetadata = + new TableMetadataBuilder() + .AddPartitionKey("order_id", DataType.Text) + .AddClusteringKey("item_id", DataType.Int) + .AddColumn("count", DataType.Int) + .Build(); + + var itemsTableMetadata = + new TableMetadataBuilder() + .AddPartitionKey("item_id", DataType.Int) + .AddColumn("name", DataType.Text) + .AddColumn("price", DataType.Int) + .Build(); + + await admin.CreateCoordinatorTablesAsync(true); + await admin.CreateNamespaceAsync("sample", true); + + await admin.CreateTableAsync("sample", "customers", customersTableMetadata, true); + await admin.CreateTableAsync("sample", "orders", ordersTableMetadata, true); + await admin.CreateTableAsync("sample", "statements", statementsTableMetadata, true); + await admin.CreateTableAsync("sample", "items", itemsTableMetadata, true); + } + + public async Task LoadInitialData() + { + var transaction = await _manager.BeginAsync(); + try + { + await LoadCustomerIfNotExists(1, "Yamada Taro", 10000, 0); + await LoadCustomerIfNotExists(2, "Yamada Hanako", 10000, 0); + await LoadCustomerIfNotExists(3, "Suzuki Ichiro", 10000, 0); + await LoadItemIfNotExists(1, "Apple", 1000); + await LoadItemIfNotExists(2, "Orange", 2000); + await LoadItemIfNotExists(3, "Grape", 2500); + await LoadItemIfNotExists(4, "Mango", 5000); + await LoadItemIfNotExists(5, "Melon", 3000); + + await transaction.CommitAsync(); + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await transaction.RollbackAsync(); + throw; + } + + return; + + async Task LoadCustomerIfNotExists(int customerId, string name, + int creditLimit, int creditTotal) + { + var customer = + await transaction.GetAsync( + new GetBuilder() + .SetNamespaceName("sample") + .SetTableName("customers") + .AddPartitionKey("customer_id", customerId) + .Build() + ); + + if (customer is not null) + return; + + await transaction.InsertAsync( + new InsertBuilder() + .SetNamespaceName("sample") + .SetTableName("customers") + .AddPartitionKey("customer_id", customerId) + .AddColumn("name", name) + .AddColumn("credit_limit", creditLimit) + .AddColumn("credit_total", creditTotal) + .Build() + ); + } + + async Task LoadItemIfNotExists(int itemId, string name, int price) + { + var item = + await transaction.GetAsync( + new GetBuilder() + .SetNamespaceName("sample") + .SetTableName("items") + .AddPartitionKey("item_id", itemId) + .Build() + ); + + if (item is not null) + return; + + await transaction.InsertAsync( + new InsertBuilder() + .SetNamespaceName("sample") + .SetTableName("items") + .AddPartitionKey("item_id", itemId) + .AddColumn("name", name) + .AddColumn("price", price) + .Build() + ); + } + } + + public async Task GetCustomerInfo(int customerId) + { + var transaction = await _manager.BeginAsync(); + try + { + // Retrieve the customer info for the specified customer ID from the customers table + var customer = + await transaction.GetAsync( + new GetBuilder() + .SetNamespaceName("sample") + .SetTableName("customers") + .AddPartitionKey("customer_id", customerId) + .Build() + ); + + if (customer is null) + { + // If the customer info the specified customer ID doesn't exist, throw an exception + throw new Exception($"Customer not found (id: {customerId})"); + } + + // Commit the transaction (even when the transaction is read-only, we need to commit) + await transaction.CommitAsync(); + + return new JsonObject + { + { "id", customerId }, + { "name", customer.GetValue("name") }, + { "credit_limit", customer.GetValue("credit_limit") }, + { "credit_total", customer.GetValue("credit_total") } + }; + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await transaction.RollbackAsync(); + throw; + } + } + + public async Task PlaceOrder(int customerId, + IReadOnlyDictionary itemCounts) + { + var transaction = await _manager.BeginAsync(); + try + { + var orderId = Guid.NewGuid().ToString(); + + // Insert the order info into the orders table + await transaction.InsertAsync( + new InsertBuilder() + .SetNamespaceName("sample") + .SetTableName("orders") + .AddPartitionKey("customer_id", customerId) + .AddClusteringKey("timestamp", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) + .AddColumn("order_id", orderId) + .Build() + ); + + var amount = 0; + foreach (var (itemId, count) in itemCounts) + { + // Insert the order statement into the statements table + await transaction.InsertAsync( + new InsertBuilder() + .SetNamespaceName("sample") + .SetTableName("statements") + .AddPartitionKey("order_id", orderId) + .AddClusteringKey("item_id", itemId) + .AddColumn("count", count) + .Build() + ); + + // Retrieve the item info from the items table + var item = + await transaction.GetAsync( + new GetBuilder() + .SetNamespaceName("sample") + .SetTableName("items") + .AddPartitionKey("item_id", itemId) + .Build() + ); + if (item is null) + throw new Exception($"Item not found (id: {itemId})"); + + // Calculate the total amount + amount += item.GetValue("price") * count; + } + + // Check if the credit total exceeds the credit limit after payment + var customer = + await transaction.GetAsync( + new GetBuilder() + .SetNamespaceName("sample") + .SetTableName("customers") + .AddPartitionKey("customer_id", customerId) + .Build() + ); + if (customer is null) + throw new Exception($"Customer not found (id: {customerId})"); + + var creditLimit = customer.GetValue("credit_limit"); + var creditTotal = customer.GetValue("credit_total"); + var newCreditTotal = creditTotal + amount; + if (newCreditTotal > creditLimit) + throw new Exception($"Credit limit exceeded ({newCreditTotal} > {creditLimit})"); + + // Update credit_total for the customer + await transaction.UpdateAsync( + new UpdateBuilder() + .SetNamespaceName("sample") + .SetTableName("customers") + .AddPartitionKey("customer_id", customerId) + .AddColumn("credit_total", newCreditTotal) + .Build() + ); + + // Commit the transaction + await transaction.CommitAsync(); + + return new JsonObject + { + { "order_id", orderId } + }; + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await transaction.RollbackAsync(); + throw; + } + } + + public async Task GetOrderByOrderId(string orderId) + { + var transaction = await _manager.BeginAsync(); + try + { + // Get an order JSON for the specified order ID + var orderJson = await getOrder(transaction, orderId); + + // Commit the transaction (even when the transaction is read-only, we need to commit) + await transaction.CommitAsync(); + + return new JsonObject + { + { "order", orderJson } + }; + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await transaction.RollbackAsync(); + throw; + } + } + + public async Task GetOrdersByCustomerId(int customerId) + { + var transaction = await _manager.BeginAsync(); + try + { + // Retrieve the order info for the customer ID from the orders table + var orders = + await transaction.ScanAsync( + new ScanBuilder() + .SetNamespaceName("sample") + .SetTableName("orders") + .AddPartitionKey("customer_id", customerId) + .Build() + ); + + // Make order JSONs for the orders of the customer + var orderJsons = new JsonArray(); + foreach (var order in orders) + orderJsons.Add(await getOrder(transaction, order.GetValue("order_id"))); + + // Commit the transaction (even when the transaction is read-only, we need to commit) + await transaction.CommitAsync(); + + return new JsonObject + { + { "orders", orderJsons } + }; + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await transaction.RollbackAsync(); + throw; + } + } + + public async Task Repayment(int customerId, int amount) + { + var transaction = await _manager.BeginAsync(); + try + { + // Retrieve the customer info for the specified customer ID from the customers table + var customer = + await transaction.GetAsync( + new GetBuilder() + .SetNamespaceName("sample") + .SetTableName("customers") + .AddPartitionKey("customer_id", customerId) + .Build() + ); + if (customer is null) + throw new Exception($"Customer not found (id: {customerId})"); + + var updatedCreditTotal = customer.GetValue("credit_total") - amount; + + // Check if over repayment or not + if (updatedCreditTotal < 0) + throw new Exception($"Over-repayment ({updatedCreditTotal})"); + + // Reduce credit_total for the customer + await transaction.UpdateAsync( + new UpdateBuilder() + .SetNamespaceName("sample") + .SetTableName("customers") + .AddPartitionKey("customer_id", customerId) + .AddColumn("credit_total", updatedCreditTotal) + .Build() + ); + + // Commit the transaction + await transaction.CommitAsync(); + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await transaction.RollbackAsync(); + throw; + } + } + + private static async Task getOrder(IDistributedTransaction transaction, string orderId) + { + // Retrieve the order info for the order ID from the orders table + var order = + await transaction.GetAsync( + new GetBuilder() + .SetNamespaceName("sample") + .SetTableName("orders") + .SetGetType(GetOperationType.GetWithIndex) + .AddPartitionKey("order_id", orderId) + .Build() + ); + if (order is null) + throw new Exception($"Order not found (id: {orderId})"); + + var customerId = order.GetValue("customer_id"); + + // Retrieve the customer info for the specified customer ID from the customers table + var customer = + await transaction.GetAsync( + new GetBuilder() + .SetNamespaceName("sample") + .SetTableName("customers") + .AddPartitionKey("customer_id", customerId) + .Build() + ); + Debug.Assert(customer is not null); + + // Retrieve the order statements for the order ID from the statements table + var statements = + await transaction.ScanAsync( + new ScanBuilder() + .SetNamespaceName("sample") + .SetTableName("statements") + .AddPartitionKey("order_id", orderId) + .Build() + ); + + // Make the statements JSONs + var total = 0; + var statementJsons = new JsonArray(); + + foreach (var statement in statements) + { + var itemId = statement.GetValue("item_id"); + + // Retrieve the item data from the items table + var item = + await transaction.GetAsync( + new GetBuilder() + .SetNamespaceName("sample") + .SetTableName("items") + .AddPartitionKey("item_id", itemId) + .Build() + ); + if (item is null) + throw new Exception($"Item not found (id: {itemId})"); + + var price = item.GetValue("price"); + var count = statement.GetValue("count"); + var totalForStatement = price * count; + + statementJsons.Add( + new JsonObject + { + { "item_id", itemId }, + { "item_name", item.GetValue("name") }, + { "price", price }, + { "count", count }, + { "total", totalForStatement } + } + ); + + total += totalForStatement; + } + + return new JsonObject + { + { "order_id", orderId }, + { "timestamp", order.GetValue("timestamp") }, + { "customer_id", customerId }, + { "customer_name", customer.GetValue("name") }, + { "statements", statementJsons }, + { "total", total } + }; + } + + public void Dispose() + => _manager.Dispose(); +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/ScalarDbClusterSample.csproj b/scalardb-dotnet-samples/scalardb-cluster-sample/ScalarDbClusterSample.csproj new file mode 100644 index 0000000..59bb671 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/ScalarDbClusterSample.csproj @@ -0,0 +1,22 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + Always + + + + diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/ScalarDbClusterSample.sln b/scalardb-dotnet-samples/scalardb-cluster-sample/ScalarDbClusterSample.sln new file mode 100644 index 0000000..ae995bb --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/ScalarDbClusterSample.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ScalarDbClusterSample", "ScalarDbClusterSample.csproj", "{939E9AC1-C42D-4193-82E1-1D1A03034074}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {939E9AC1-C42D-4193-82E1-1D1A03034074}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {939E9AC1-C42D-4193-82E1-1D1A03034074}.Debug|Any CPU.Build.0 = Debug|Any CPU + {939E9AC1-C42D-4193-82E1-1D1A03034074}.Release|Any CPU.ActiveCfg = Release|Any CPU + {939E9AC1-C42D-4193-82E1-1D1A03034074}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/global.json b/scalardb-dotnet-samples/scalardb-cluster-sample/global.json new file mode 100644 index 0000000..18b689d --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "8.0.0", + "rollForward": "latestMinor", + "allowPrerelease": false + } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-sample/scalardb-options.json b/scalardb-dotnet-samples/scalardb-cluster-sample/scalardb-options.json new file mode 100644 index 0000000..dd4c27f --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-sample/scalardb-options.json @@ -0,0 +1,5 @@ +{ + "ScalarDbOptions": { + "Address": "http://localhost:60053" + } +}