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-linq-sample/Commands/GetCustomerInfoCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/GetCustomerInfoCommand.cs new file mode 100644 index 0000000..089cbfe --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/GetCustomerInfoCommand.cs @@ -0,0 +1,31 @@ +using System.CommandLine; + +namespace ScalarDbClusterLinqSample.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(customerId => + { + using var sample = new Sample(); + var customerInfo = sample.GetCustomerInfo(customerId); + + Console.WriteLine(customerInfo); + }, customerIdArg); + + return getCustomerInfoCommand; + } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/GetOrderCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/GetOrderCommand.cs new file mode 100644 index 0000000..865b718 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/GetOrderCommand.cs @@ -0,0 +1,31 @@ +using System.CommandLine; + +namespace ScalarDbClusterLinqSample.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-linq-sample/Commands/GetOrdersCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/GetOrdersCommand.cs new file mode 100644 index 0000000..5d1f29c --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/GetOrdersCommand.cs @@ -0,0 +1,31 @@ +using System.CommandLine; + +namespace ScalarDbClusterLinqSample.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-linq-sample/Commands/LoadInitialDataCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/LoadInitialDataCommand.cs new file mode 100644 index 0000000..e0136f8 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/LoadInitialDataCommand.cs @@ -0,0 +1,45 @@ +using System.CommandLine; +using System.Diagnostics; +using ScalarDB.Client.Exceptions; + +namespace ScalarDbClusterLinqSample.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-linq-sample/Commands/PlaceOrderCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/PlaceOrderCommand.cs new file mode 100644 index 0000000..7a8d85d --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/PlaceOrderCommand.cs @@ -0,0 +1,54 @@ +using System.CommandLine; + +namespace ScalarDbClusterLinqSample.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-linq-sample/Commands/RepaymentCommand.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/RepaymentCommand.cs new file mode 100644 index 0000000..b81518c --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/RepaymentCommand.cs @@ -0,0 +1,33 @@ +using System.CommandLine; + +namespace ScalarDbClusterLinqSample.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-linq-sample/Models/Customer.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Customer.cs new file mode 100644 index 0000000..24d2c6c --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Customer.cs @@ -0,0 +1,21 @@ +using System.ComponentModel.DataAnnotations.Schema; +using ScalarDB.Client.DataAnnotations; + +namespace ScalarDbClusterLinqSample.Models; + +[Table("sample.customers")] +public class Customer +{ + [PartitionKey] + [Column("customer_id", Order = 0)] + public int Id { get; set; } + + [Column("name", Order = 1)] + public string Name { get; set; } = ""; + + [Column("credit_limit", Order = 2)] + public int CreditLimit { get; set; } + + [Column("credit_total", Order = 3)] + public int CreditTotal { get; set; } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Item.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Item.cs new file mode 100644 index 0000000..a5d8bab --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Item.cs @@ -0,0 +1,18 @@ +using System.ComponentModel.DataAnnotations.Schema; +using ScalarDB.Client.DataAnnotations; + +namespace ScalarDbClusterLinqSample.Models; + +[Table("sample.items")] +public class Item +{ + [PartitionKey] + [Column("item_id", Order = 0)] + public int Id { get; set; } + + [Column("name", Order = 1)] + public string Name { get; set; } = ""; + + [Column("price", Order = 2)] + public int Price { get; set; } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Order.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Order.cs new file mode 100644 index 0000000..ca39462 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Order.cs @@ -0,0 +1,20 @@ +using System.ComponentModel.DataAnnotations.Schema; +using ScalarDB.Client.DataAnnotations; + +namespace ScalarDbClusterLinqSample.Models; + +[Table("sample.orders")] +public class Order +{ + [SecondaryIndex] + [Column("order_id", Order = 0)] + public string Id { get; set; } = ""; + + [PartitionKey] + [Column("customer_id", Order = 1)] + public int CustomerId { get; set; } + + [ClusteringKey] + [Column("timestamp", Order = 2)] + public long Timestamp { get; set; } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/SampleDbContext.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/SampleDbContext.cs new file mode 100644 index 0000000..5e33f48 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/SampleDbContext.cs @@ -0,0 +1,13 @@ +using ScalarDB.Client; + +namespace ScalarDbClusterLinqSample.Models; + +public class SampleDbContext : ScalarDbContext +{ +#nullable disable + public ScalarDbSet Customers { get; set; } + public ScalarDbSet Orders { get; set; } + public ScalarDbSet Statements { get; set; } + public ScalarDbSet Items { get; set; } +#nullable restore +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Statement.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Statement.cs new file mode 100644 index 0000000..a4747f3 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Models/Statement.cs @@ -0,0 +1,19 @@ +using System.ComponentModel.DataAnnotations.Schema; +using ScalarDB.Client.DataAnnotations; + +namespace ScalarDbClusterLinqSample.Models; + +[Table("sample.statements")] +public class Statement +{ + [PartitionKey] + [Column("order_id", Order = 0)] + public string OrderId { get; set; } = ""; + + [ClusteringKey] + [Column("item_id", Order = 1)] + public int ItemId { get; set; } + + [Column("count", Order = 2)] + public int Count { get; set; } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Program.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Program.cs new file mode 100644 index 0000000..f10041f --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Program.cs @@ -0,0 +1,14 @@ +using System.CommandLine; +using ScalarDbClusterLinqSample.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-linq-sample/Sample.cs b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Sample.cs new file mode 100644 index 0000000..d4b6ed0 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Sample.cs @@ -0,0 +1,314 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; +using Microsoft.Extensions.Logging; +using ScalarDB.Client; +using ScalarDB.Client.Exceptions; +using ScalarDB.Client.Extensions; +using ScalarDbClusterLinqSample.Models; + +namespace ScalarDbClusterLinqSample; + +public class Sample: IDisposable +{ + private const string ConfigFileName = "scalardb-options.json"; + + private readonly SampleDbContext _db = + ScalarDbContext.Create(ConfigFileName, getLoggerFactory()); + + public static async Task CreateTables() + { + using var admin = TransactionFactory.Create(ConfigFileName, getLoggerFactory()) + .GetTransactionAdmin(); + + await admin.CreateCoordinatorTablesAsync(true); + await admin.CreateNamespaceAsync(true); + + await admin.CreateTableAsync(true); + await admin.CreateTableAsync(true); + await admin.CreateTableAsync(true); + await admin.CreateTableAsync(true); + } + + public async Task LoadInitialData() + { + Customer[] customers = + [ + new() { Id = 1, Name = "Yamada Taro", CreditLimit = 10000, CreditTotal = 0 }, + new() { Id = 2, Name = "Yamada Hanako", CreditLimit = 10000, CreditTotal = 0 }, + new() { Id = 3, Name = "Suzuki Ichiro", CreditLimit = 10000, CreditTotal = 0 } + ]; + + Item[] items = + [ + new() { Id = 1, Name = "Apple", Price = 1000 }, + new() { Id = 2, Name = "Orange", Price = 2000 }, + new() { Id = 3, Name = "Grape", Price = 2500 }, + new() { Id = 4, Name = "Mango", Price = 5000 }, + new() { Id = 5, Name = "Melon", Price = 3000 } + ]; + + await _db.BeginTransactionAsync(); + try + { + foreach (var customer in customers) + { + if (_db.Customers.FirstOrDefault(c => c.Id == customer.Id) is not null) + continue; + + await _db.Customers.AddAsync(customer); + } + + foreach (var item in items) + { + if (_db.Items.FirstOrDefault(i => i.Id == item.Id) is not null) + continue; + + await _db.Items.AddAsync(item); + } + + await _db.CommitTransactionAsync(); + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await _db.RollbackTransactionAsync(); + throw; + } + } + + public JsonObject GetCustomerInfo(int customerId) + { + // Retrieve the customer info for the specified customer ID from the customers table + var customer = _db.Customers.FirstOrDefault(c => c.Id == customerId); + 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})"); + } + + return new JsonObject + { + { "id", customer.Id }, + { "name", customer.Name }, + { "credit_limit", customer.CreditLimit }, + { "credit_total", customer.CreditTotal } + }; + } + + public async Task PlaceOrder(int customerId, + IReadOnlyDictionary itemCounts) + { + await _db.BeginTransactionAsync(); + try + { + var orderId = Guid.NewGuid().ToString(); + + // Insert the order info into the orders table + await _db.Orders.AddAsync( + new() + { + Id = orderId, + CustomerId = customerId, + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + } + ); + + var amount = 0; + foreach (var (itemId, count) in itemCounts) + { + // Insert the order statement into the statements table + await _db.Statements.AddAsync( + new() + { + OrderId = orderId, + ItemId = itemId, + Count = count + } + ); + + // Retrieve the item info from the items table + var item = _db.Items.FirstOrDefault(i => i.Id == itemId); + if (item is null) + throw new Exception($"Item not found (id: {itemId})"); + + // Calculate the total amount + amount += item.Price * count; + } + + // Check if the credit total exceeds the credit limit after payment + var customer = _db.Customers.FirstOrDefault(c => c.Id == customerId); + if (customer is null) + throw new Exception($"Customer not found (id: {customerId})"); + + customer.CreditTotal += amount; + if (customer.CreditTotal > customer.CreditLimit) + throw new Exception($"Credit limit exceeded ({customer.CreditTotal} > {customer.CreditLimit})"); + + // Update credit_total for the customer + await _db.UpdateAsync(customer); + + // Commit the transaction + await _db.CommitTransactionAsync(); + + return new JsonObject + { + { "order_id", orderId } + }; + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await _db.RollbackTransactionAsync(); + throw; + } + } + + public async Task GetOrderByOrderId(string orderId) + { + await _db.BeginTransactionAsync(); + try + { + // Get an order JSON for the specified order ID + var orderJson = getOrder(orderId); + + // Commit the transaction (even when the transaction is read-only, we need to commit) + await _db.CommitTransactionAsync(); + + return new JsonObject + { + { "order", orderJson } + }; + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await _db.RollbackTransactionAsync(); + throw; + } + } + + public async Task GetOrdersByCustomerId(int customerId) + { + await _db.BeginTransactionAsync(); + try + { + // Retrieve the order info for the customer ID from the orders table + var orderIds = from order in _db.Orders + where order.CustomerId == customerId + select order.Id; + + // Make order JSONs for the orders of the customer + var orderJsons = new JsonArray(); + foreach (var orderId in orderIds) + orderJsons.Add(getOrder(orderId)); + + await _db.CommitTransactionAsync(); + + return new JsonObject + { + { "orders", orderJsons } + }; + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await _db.RollbackTransactionAsync(); + throw; + } + } + + public async Task Repayment(int customerId, int amount) + { + await _db.BeginTransactionAsync(); + try + { + // Retrieve the customer info for the specified customer ID from the customers table + var customer = _db.Customers.FirstOrDefault(c => c.Id == customerId); + if (customer is null) + throw new Exception($"Customer not found (id: {customerId})"); + + customer.CreditTotal -= amount; + + // Check if over repayment or not + if (customer.CreditTotal < 0) + throw new Exception($"Over-repayment ({customer.CreditTotal})"); + + // Reduce credit_total for the customer + await _db.UpdateAsync(customer); + + // Commit the transaction + await _db.CommitTransactionAsync(); + } + catch (TransactionException) + { + // If an error occurs, rollback the transaction + await _db.RollbackTransactionAsync(); + throw; + } + } + + private JsonObject getOrder(string orderId) + { + // Retrieve the order info for the order ID from the orders table + var order = _db.Orders.FirstOrDefault(o => o.Id == orderId); + if (order is null) + throw new Exception($"Order not found (id: {orderId})"); + + // Retrieve the customer info for the specified customer ID from the customers table + var customer = _db.Customers.FirstOrDefault(c => c.Id == order.CustomerId); + Debug.Assert(customer is not null); + + // Retrieve the order statements for the order ID + var statements = from statement in _db.Statements + join item in _db.Items on statement.ItemId equals item.Id + where statement.OrderId == orderId + select new + { + ItemId = item.Id, + ItemName = item.Name, + Price = item.Price, + Count = statement.Count, + Total = item.Price * statement.Count + }; + + // Make the statements JSONs + var total = 0; + var statementJsons = new JsonArray(); + + foreach (var statement in statements) + { + statementJsons.Add( + new JsonObject + { + { "item_id", statement.ItemId }, + { "item_name", statement.ItemName }, + { "price", statement.Price }, + { "count", statement.Count }, + { "total", statement.Total } + } + ); + + total += statement.Total; + } + + return new JsonObject + { + { "order_id", order.Id }, + { "timestamp", order.Timestamp }, + { "customer_id", customer.Id }, + { "customer_name", customer.Name }, + { "statements", statementJsons }, + { "total", total } + }; + } + + private static ILoggerFactory getLoggerFactory() + => LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Warning); + builder.AddSimpleConsole(options => { options.TimestampFormat = "HH:mm:ss "; }); + }); + + public void Dispose() + => _db.Dispose(); +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-linq-sample/ScalarDbClusterLinqSample.csproj b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/ScalarDbClusterLinqSample.csproj new file mode 100644 index 0000000..d8fcb15 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/ScalarDbClusterLinqSample.csproj @@ -0,0 +1,23 @@ + + + + Exe + net8.0 + enable + enable + ScalarDbClusterLinqSample + + + + + + + + + + + Always + + + + diff --git a/scalardb-dotnet-samples/scalardb-cluster-linq-sample/ScalarDbClusterLinqSample.sln b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/ScalarDbClusterLinqSample.sln new file mode 100644 index 0000000..fb5a796 --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/ScalarDbClusterLinqSample.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ScalarDbClusterLinqSample", "ScalarDbClusterLinqSample.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-linq-sample/global.json b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/global.json new file mode 100644 index 0000000..18b689d --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "8.0.0", + "rollForward": "latestMinor", + "allowPrerelease": false + } +} diff --git a/scalardb-dotnet-samples/scalardb-cluster-linq-sample/scalardb-options.json b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/scalardb-options.json new file mode 100644 index 0000000..dd4c27f --- /dev/null +++ b/scalardb-dotnet-samples/scalardb-cluster-linq-sample/scalardb-options.json @@ -0,0 +1,5 @@ +{ + "ScalarDbOptions": { + "Address": "http://localhost:60053" + } +}