diff --git a/.github/workflows/ado-net-tests.yml b/.github/workflows/ado-net-tests.yml
new file mode 100644
index 00000000..9092004f
--- /dev/null
+++ b/.github/workflows/ado-net-tests.yml
@@ -0,0 +1,30 @@
+on:
+ push:
+ branches: [ main ]
+ pull_request:
+permissions:
+ contents: read
+ pull-requests: write
+name: ADO.NET Tests
+jobs:
+ units:
+ strategy:
+ matrix:
+ dotnet-version: ['8.0.x', '9.0.x']
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ runs-on: ${{ matrix.os }}
+ steps:
+ - name: Install dotnet
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: ${{ matrix.dotnet-version }}
+ - name: Checkout code
+ uses: actions/checkout@v4
+ - name: spanner-ado-net-tests
+ working-directory: drivers/spanner-ado-net/spanner-ado-net-tests
+ run: dotnet test --verbosity normal
+ shell: bash
+ - name: spanner-ado-net-specification-tests
+ working-directory: drivers/spanner-ado-net/spanner-ado-net-specification-tests
+ run: dotnet test --verbosity normal
+ shell: bash
diff --git a/drivers/spanner-ado-net/.gitignore b/drivers/spanner-ado-net/.gitignore
new file mode 100644
index 00000000..808112cd
--- /dev/null
+++ b/drivers/spanner-ado-net/.gitignore
@@ -0,0 +1,4 @@
+.idea
+obj
+bin
+*DotSettings.user
diff --git a/drivers/spanner-ado-net/LICENSE b/drivers/spanner-ado-net/LICENSE
new file mode 100644
index 00000000..d6456956
--- /dev/null
+++ b/drivers/spanner-ado-net/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/drivers/spanner-ado-net/README.md b/drivers/spanner-ado-net/README.md
new file mode 100644
index 00000000..fbcfda13
--- /dev/null
+++ b/drivers/spanner-ado-net/README.md
@@ -0,0 +1,5 @@
+# Spanner ADO.NET Data Provider
+
+ADO.NET Data Provider for Spanner.
+
+__ALPHA: Not for production use__
diff --git a/drivers/spanner-ado-net/global.json b/drivers/spanner-ado-net/global.json
new file mode 100644
index 00000000..2ddda36c
--- /dev/null
+++ b/drivers/spanner-ado-net/global.json
@@ -0,0 +1,7 @@
+{
+ "sdk": {
+ "version": "8.0.0",
+ "rollForward": "latestMinor",
+ "allowPrerelease": false
+ }
+}
\ No newline at end of file
diff --git a/drivers/spanner-ado-net/spanner-ado-net-benchmarks/README.md b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/README.md
new file mode 100644
index 00000000..e7015b23
--- /dev/null
+++ b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/README.md
@@ -0,0 +1,5 @@
+# Spanner ADO.NET Data Provider Benchmarks
+
+Benchmarks for the ADO.NET Data Provider for Spanner.
+
+__ALPHA: Not for production use__
diff --git a/drivers/spanner-ado-net/spanner-ado-net-benchmarks/deploy.txt b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/deploy.txt
new file mode 100644
index 00000000..b08e5498
--- /dev/null
+++ b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/deploy.txt
@@ -0,0 +1,46 @@
+
+gcloud run deploy spannerlib-dotnet-benchmark-tpcc \
+ --region=europe-north1 \
+ --no-allow-unauthenticated --no-cpu-throttling \
+ --min-instances=1 --max-instances=1 \
+ --cpu=4 --memory=2Gi \
+ --set-env-vars=NUM_WAREHOUSES=100,TRANSACTIONS_PER_SECOND=50,NUM_CLIENTS=50 \
+ --base-image dotnet8 \
+ --source .
+
+gcloud run deploy spannerlib-dotnet-benchmark-tpcc \
+ --region=europe-north1 \
+ --no-allow-unauthenticated --no-cpu-throttling \
+ --min-instances=1 --max-instances=1 \
+ --cpu=4 --memory=2Gi \
+ --set-env-vars=NUM_WAREHOUSES=100,TRANSACTIONS_PER_SECOND=50,NUM_CLIENTS=50,RETRY_ABORTS_INTERNALLY=false \
+ --base-image dotnet8 \
+ --source .
+
+
+gcloud run deploy spannerlib-dotnet-benchmark-tpcc \
+ --region=europe-north1 \
+ --no-allow-unauthenticated --no-cpu-throttling \
+ --min-instances=1 --max-instances=1 \
+ --cpu=4 --memory=2Gi \
+ --set-env-vars=NUM_WAREHOUSES=100,CLIENT_TYPE=ClientLib,TRANSACTIONS_PER_SECOND=50,NUM_CLIENTS=50 \
+ --base-image dotnet8 \
+ --source .
+
+gcloud run deploy spannerlib-dotnet-benchmark-tpcc \
+ --region=europe-north1 \
+ --no-allow-unauthenticated --no-cpu-throttling \
+ --min-instances=1 --max-instances=1 \
+ --cpu=4 --memory=2Gi \
+ --set-env-vars=NUM_WAREHOUSES=100,CLIENT_TYPE=NativeSpannerLib,TRANSACTIONS_PER_SECOND=50,NUM_CLIENTS=50 \
+ --base-image dotnet8 \
+ --source .
+
+gcloud run deploy spannerlib-dotnet-benchmark-tpcc \
+ --region=europe-north1 \
+ --no-allow-unauthenticated --no-cpu-throttling \
+ --min-instances=1 --max-instances=1 \
+ --cpu=4 --memory=2Gi \
+ --set-env-vars=NUM_WAREHOUSES=100,CLIENT_TYPE=NativeSpannerLib,TRANSACTIONS_PER_SECOND=50,NUM_CLIENTS=50,RETRY_ABORTS_INTERNALLY=false \
+ --base-image dotnet8 \
+ --source .
diff --git a/drivers/spanner-ado-net/spanner-ado-net-benchmarks/spanner-ado-net-benchmarks.csproj b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/spanner-ado-net-benchmarks.csproj
new file mode 100644
index 00000000..1c8e0a3d
--- /dev/null
+++ b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/spanner-ado-net-benchmarks.csproj
@@ -0,0 +1,19 @@
+
+
+
+ Exe
+ net8.0
+ Google.Cloud.Spanner.DataProvider.Benchmarks
+ enable
+ enable
+ Google.Cloud.Spanner.DataProvider.Benchmarks
+ default
+
+
+
+
+
+
+
+
+
diff --git a/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/LastNameGenerator.cs b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/LastNameGenerator.cs
new file mode 100644
index 00000000..2179eb61
--- /dev/null
+++ b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/LastNameGenerator.cs
@@ -0,0 +1,22 @@
+namespace Google.Cloud.Spanner.DataProvider.Benchmarks.tpcc;
+
+public static class LastNameGenerator
+{
+ private static readonly string[] Parts = ["BAR", "OUGHT", "ABLE", "PRI", "PRES", "ESE", "ANTI", "CALLY", "ATION", "EING"];
+
+ public static string GenerateLastName(long rowIndex) {
+ int row;
+ if (rowIndex < 1000L)
+ {
+ row = (int) rowIndex;
+ }
+ else
+ {
+ row = Random.Shared.Next(1000);
+ }
+ return Parts[row / 100] +
+ Parts[row / 10 % 10] +
+ Parts[row % 10];
+ }
+
+}
\ No newline at end of file
diff --git a/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/Program.cs b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/Program.cs
new file mode 100644
index 00000000..62e0d7d1
--- /dev/null
+++ b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/Program.cs
@@ -0,0 +1,158 @@
+using System.Collections.Concurrent;
+using System.Data.Common;
+using System.Diagnostics;
+using Google.Cloud.Spanner.Admin.Database.V1;
+using Google.Cloud.Spanner.DataProvider.Benchmarks.tpcc.loader;
+using Microsoft.AspNetCore.Builder;
+
+namespace Google.Cloud.Spanner.DataProvider.Benchmarks.tpcc;
+
+public static class Program
+{
+ enum ClientType
+ {
+ SpannerLib,
+ NativeSpannerLib,
+ ClientLib,
+ }
+
+ public static async Task Main(string[] args)
+ {
+ var cancellationTokenSource = new CancellationTokenSource();
+ var builder = WebApplication.CreateBuilder(args);
+ var port = Environment.GetEnvironmentVariable("PORT") ?? "8080";
+ var url = $"http://0.0.0.0:{port}";
+ var app = builder.Build();
+ app.MapGet("/", () => { });
+ var webapp = app.RunAsync(url);
+
+ var logWaitTime = int.Parse(Environment.GetEnvironmentVariable("LOG_WAIT_TIME") ?? "10");
+ var database = Environment.GetEnvironmentVariable("DATABASE") ?? "projects/appdev-soda-spanner-staging/instances/knut-test-ycsb/databases/dotnet-tpcc";
+ var retryAbortsInternally = bool.Parse(Environment.GetEnvironmentVariable("RETRY_ABORTS_INTERNALLY") ?? "true");
+ var numWarehouses = int.Parse(Environment.GetEnvironmentVariable("NUM_WAREHOUSES") ?? "10");
+ var numClients = int.Parse(Environment.GetEnvironmentVariable("NUM_CLIENTS") ?? "10");
+ var targetTps = int.Parse(Environment.GetEnvironmentVariable("TRANSACTIONS_PER_SECOND") ?? "0");
+ var clientTypeName = Environment.GetEnvironmentVariable("CLIENT_TYPE") ?? "SpannerLib";
+ if (!Enum.TryParse(clientTypeName, out ClientType clientType))
+ {
+ throw new ArgumentException($"Unknown client type: {clientTypeName}");
+ }
+
+ var connectionString = $"Data Source={database}";
+ if (!retryAbortsInternally)
+ {
+ connectionString += ";retryAbortsInternally=false";
+ }
+ await using (var connection = new SpannerConnection())
+ {
+ connection.ConnectionString = connectionString;
+ await connection.OpenAsync(cancellationTokenSource.Token);
+
+ Console.WriteLine("Creating schema...");
+ await SchemaUtil.CreateSchemaAsync(connection, DatabaseDialect.Postgresql, cancellationTokenSource.Token);
+
+ Console.WriteLine("Loading data...");
+ var loader = new DataLoader(connection, numWarehouses);
+ await loader.LoadAsync(cancellationTokenSource.Token);
+ }
+
+ Console.WriteLine("Running benchmark...");
+ var stats = new Stats();
+
+ if (targetTps > 0)
+ {
+ var maxWaitTime = 2 * 1000 / targetTps;
+ Console.WriteLine($"Clients: {numClients}");
+ Console.WriteLine($"Transactions per second: {targetTps}");
+ Console.WriteLine($"Max wait time: {maxWaitTime}");
+ var runners = new BlockingCollection();
+ for (var client = 0; client < numClients; client++)
+ {
+ runners.Add(await CreateRunnerAsync(clientType, connectionString, stats, numWarehouses, cancellationTokenSource), cancellationTokenSource.Token);
+ }
+ var lastLogTime = DateTime.UtcNow;
+ while (!cancellationTokenSource.IsCancellationRequested)
+ {
+ var randomWaitTime = Random.Shared.Next(0, maxWaitTime);
+ var stopwatch = Stopwatch.StartNew();
+ if (runners.TryTake(out var runner, 20_000, cancellationTokenSource.Token))
+ {
+ var source = new CancellationTokenSource();
+ source.CancelAfter(TimeSpan.FromSeconds(10));
+ var token = source.Token;
+ stats.RegisterTransactionStarted();
+ var task = runner!.RunTransactionAsync(token);
+ _ = task.ContinueWith(_ =>
+ {
+ stats.RegisterTransactionCompleted();
+ runners.Add(runner, cancellationTokenSource.Token);
+ task.Dispose();
+ }, TaskContinuationOptions.ExecuteSynchronously);
+ }
+ else
+ {
+ await Console.Error.WriteLineAsync("No runner available");
+ }
+ randomWaitTime -= (int) stopwatch.ElapsedMilliseconds;
+ if (randomWaitTime > 0)
+ {
+ await Task.Delay(TimeSpan.FromMilliseconds(randomWaitTime), cancellationTokenSource.Token);
+ }
+ if ((DateTime.UtcNow - lastLogTime).TotalSeconds >= logWaitTime)
+ {
+ Console.WriteLine($"Num available runners: {runners.Count}");
+ Console.WriteLine($"Thread pool size: {ThreadPool.ThreadCount}");
+ stats.LogStats();
+ lastLogTime = DateTime.UtcNow;
+ }
+ }
+ }
+ else
+ {
+ var tasks = new List();
+ for (var client = 0; client < numClients; client++)
+ {
+ var runner = await CreateRunnerAsync(clientType, connectionString, stats, numWarehouses, cancellationTokenSource);
+ tasks.Add(runner.RunAsync(cancellationTokenSource.Token));
+ }
+ while (!cancellationTokenSource.Token.IsCancellationRequested)
+ {
+ await Task.Delay(TimeSpan.FromSeconds(logWaitTime), cancellationTokenSource.Token);
+ stats.LogStats();
+ }
+ await Task.WhenAll(tasks);
+ }
+
+ await app.StopAsync(cancellationTokenSource.Token);
+ await webapp;
+ }
+
+ private static async Task CreateRunnerAsync(
+ ClientType clientType,
+ string connectionString,
+ Stats stats,
+ int numWarehouses,
+ CancellationTokenSource cancellationTokenSource)
+ {
+ DbConnection connection;
+ if (clientType == ClientType.SpannerLib)
+ {
+ connection = new SpannerConnection();
+ }
+ else if (clientType == ClientType.NativeSpannerLib)
+ {
+ connection = new SpannerConnection {UseNativeLibrary = true};
+ }
+ else if (clientType == ClientType.ClientLib)
+ {
+ connection = new Google.Cloud.Spanner.Data.SpannerConnection();
+ }
+ else
+ {
+ throw new ArgumentException($"Unknown client type: {clientType}");
+ }
+ connection.ConnectionString = connectionString;
+ await connection.OpenAsync(cancellationTokenSource.Token);
+ return new TpccRunner(stats, connection, numWarehouses);
+ }
+}
\ No newline at end of file
diff --git a/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/RowNotFoundException.cs b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/RowNotFoundException.cs
new file mode 100644
index 00000000..f1b3530b
--- /dev/null
+++ b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/RowNotFoundException.cs
@@ -0,0 +1,5 @@
+using System.Data.Common;
+
+namespace Google.Cloud.Spanner.DataProvider.Benchmarks.tpcc;
+
+public class RowNotFoundException(string message) : DbException(message);
\ No newline at end of file
diff --git a/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/SchemaDefinition.cs b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/SchemaDefinition.cs
new file mode 100644
index 00000000..dff383ea
--- /dev/null
+++ b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/SchemaDefinition.cs
@@ -0,0 +1,200 @@
+namespace Google.Cloud.Spanner.DataProvider.Benchmarks.tpcc;
+
+public static class SchemaDefinition
+{
+ public const string CreateTablesPostgreSql = @"
+START BATCH DDL;
+
+CREATE TABLE IF NOT EXISTS warehouse (
+ w_id int not null,
+ w_name varchar(10),
+ w_street_1 varchar(20),
+ w_street_2 varchar(20),
+ w_city varchar(20),
+ w_state varchar(2),
+ w_zip varchar(9),
+ w_tax decimal,
+ w_ytd decimal,
+ primary key (w_id)
+);
+
+create table IF NOT EXISTS district (
+ d_id int not null,
+ w_id int not null,
+ d_name varchar(10),
+ d_street_1 varchar(20),
+ d_street_2 varchar(20),
+ d_city varchar(20),
+ d_state varchar(2),
+ d_zip varchar(9),
+ d_tax decimal,
+ d_ytd decimal,
+ d_next_o_id int,
+ primary key (w_id, d_id)
+);
+
+-- CUSTOMER TABLE
+
+create table IF NOT EXISTS customer (
+ c_id int not null,
+ d_id int not null,
+ w_id int not null,
+ c_first varchar(16),
+ c_middle varchar(2),
+ c_last varchar(16),
+ c_street_1 varchar(20),
+ c_street_2 varchar(20),
+ c_city varchar(20),
+ c_state varchar(2),
+ c_zip varchar(9),
+ c_phone varchar(16),
+ c_since timestamptz,
+ c_credit varchar(2),
+ c_credit_lim bigint,
+ c_discount decimal,
+ c_balance decimal,
+ c_ytd_payment decimal,
+ c_payment_cnt int,
+ c_delivery_cnt int,
+ c_data text,
+ PRIMARY KEY(w_id, d_id, c_id)
+);
+
+-- HISTORY TABLE
+
+create table IF NOT EXISTS history (
+ c_id int,
+ d_id int,
+ w_id int,
+ h_d_id int,
+ h_w_id int,
+ h_date timestamptz,
+ h_amount decimal,
+ h_data varchar(24),
+ PRIMARY KEY(c_id, d_id, w_id, h_d_id, h_w_id, h_date)
+);
+
+create table IF NOT EXISTS orders (
+ o_id int not null,
+ d_id int not null,
+ w_id int not null,
+ c_id int not null,
+ o_entry_d timestamptz,
+ o_carrier_id int,
+ o_ol_cnt int,
+ o_all_local int,
+ PRIMARY KEY(w_id, d_id, c_id, o_id)
+);
+
+-- NEW_ORDER table
+
+create table IF NOT EXISTS new_orders (
+ o_id int not null,
+ c_id int not null,
+ d_id int not null,
+ w_id int not null,
+ PRIMARY KEY(w_id, d_id, o_id, c_id)
+);
+
+create table IF NOT EXISTS order_line (
+ o_id int not null,
+ c_id int not null,
+ d_id int not null,
+ w_id int not null,
+ ol_number int not null,
+ ol_i_id int,
+ ol_supply_w_id int,
+ ol_delivery_d timestamptz,
+ ol_quantity int,
+ ol_amount decimal,
+ ol_dist_info varchar(24),
+ PRIMARY KEY(w_id, d_id, o_id, c_id, ol_number)
+);
+
+-- STOCK table
+
+create table IF NOT EXISTS stock (
+ s_i_id int not null,
+ w_id int not null,
+ s_quantity int,
+ s_dist_01 varchar(24),
+ s_dist_02 varchar(24),
+ s_dist_03 varchar(24),
+ s_dist_04 varchar(24),
+ s_dist_05 varchar(24),
+ s_dist_06 varchar(24),
+ s_dist_07 varchar(24),
+ s_dist_08 varchar(24),
+ s_dist_09 varchar(24),
+ s_dist_10 varchar(24),
+ s_ytd decimal,
+ s_order_cnt int,
+ s_remote_cnt int,
+ s_data varchar(50),
+ PRIMARY KEY(w_id, s_i_id)
+);
+
+create table IF NOT EXISTS item (
+ i_id int not null,
+ i_im_id int,
+ i_name varchar(24),
+ i_price decimal,
+ i_data varchar(50),
+ PRIMARY KEY(i_id)
+);
+
+CREATE INDEX idx_customer ON customer (w_id,d_id,c_last,c_first);
+CREATE INDEX idx_orders ON orders (w_id,d_id,o_id);
+CREATE INDEX fkey_stock_2 ON stock (s_i_id);
+CREATE INDEX fkey_order_line_2 ON order_line (ol_supply_w_id,ol_i_id);
+CREATE INDEX fkey_history_1 ON history (w_id,d_id,c_id);
+CREATE INDEX fkey_history_2 ON history (h_w_id,h_d_id );
+
+ALTER TABLE new_orders ADD CONSTRAINT fkey_new_orders_1_ FOREIGN KEY(w_id,d_id,c_id,o_id) REFERENCES orders(w_id,d_id,c_id,o_id);
+ALTER TABLE orders ADD CONSTRAINT fkey_orders_1_ FOREIGN KEY(w_id,d_id,c_id) REFERENCES customer(w_id,d_id,c_id);
+ALTER TABLE customer ADD CONSTRAINT fkey_customer_1_ FOREIGN KEY(w_id,d_id) REFERENCES district(w_id,d_id);
+ALTER TABLE history ADD CONSTRAINT fkey_history_1_ FOREIGN KEY(w_id,d_id,c_id) REFERENCES customer(w_id,d_id,c_id);
+ALTER TABLE history ADD CONSTRAINT fkey_history_2_ FOREIGN KEY(h_w_id,h_d_id) REFERENCES district(w_id,d_id);
+ALTER TABLE district ADD CONSTRAINT fkey_district_1_ FOREIGN KEY(w_id) REFERENCES warehouse(w_id);
+ALTER TABLE order_line ADD CONSTRAINT fkey_order_line_1_ FOREIGN KEY(w_id,d_id,c_id,o_id) REFERENCES orders(w_id,d_id,c_id,o_id);
+ALTER TABLE order_line ADD CONSTRAINT fkey_order_line_2_ FOREIGN KEY(ol_supply_w_id,ol_i_id) REFERENCES stock(w_id,s_i_id);
+ALTER TABLE stock ADD CONSTRAINT fkey_stock_1_ FOREIGN KEY(w_id) REFERENCES warehouse(w_id);
+ALTER TABLE stock ADD CONSTRAINT fkey_stock_2_ FOREIGN KEY(s_i_id) REFERENCES item(i_id);
+
+RUN BATCH;
+";
+
+ public const string DropTables = @"
+start batch ddl;
+
+drop index if exists fkey_history_2;
+drop index if exists fkey_history_1;
+drop index if exists fkey_order_line_2;
+drop index if exists fkey_stock_2;
+drop index if exists idx_orders;
+drop index if exists idx_customer;
+
+ALTER TABLE new_orders DROP CONSTRAINT fkey_new_orders_1_;
+ALTER TABLE orders DROP CONSTRAINT fkey_orders_1_;
+ALTER TABLE customer DROP CONSTRAINT fkey_customer_1_;
+ALTER TABLE history DROP CONSTRAINT fkey_history_1_;
+ALTER TABLE history DROP CONSTRAINT fkey_history_2_;
+ALTER TABLE district DROP CONSTRAINT fkey_district_1_;
+ALTER TABLE order_line DROP CONSTRAINT fkey_order_line_1_;
+ALTER TABLE order_line DROP CONSTRAINT fkey_order_line_2_;
+ALTER TABLE stock DROP CONSTRAINT fkey_stock_1_;
+ALTER TABLE stock DROP CONSTRAINT fkey_stock_2_;
+
+drop table if exists new_orders;
+drop table if exists order_line;
+drop table if exists history;
+drop table if exists orders;
+drop table if exists stock;
+drop table if exists customer;
+drop table if exists district;
+drop table if exists warehouse;
+drop table if exists item;
+
+run batch;
+";
+}
\ No newline at end of file
diff --git a/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/SchemaUtil.cs b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/SchemaUtil.cs
new file mode 100644
index 00000000..49acdd8e
--- /dev/null
+++ b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/SchemaUtil.cs
@@ -0,0 +1,47 @@
+using Google.Cloud.Spanner.Admin.Database.V1;
+
+namespace Google.Cloud.Spanner.DataProvider.Benchmarks.tpcc;
+
+static class SchemaUtil
+{
+ internal static async Task CreateSchemaAsync(SpannerConnection connection, DatabaseDialect dialect, CancellationToken cancellationToken)
+ {
+ await using var cmd = connection.CreateCommand();
+ cmd.CommandText = "select count(1) "
+ + "from information_schema.tables "
+ + "where "
+ + (dialect == DatabaseDialect.Postgresql ? "table_schema='public' and " : "table_schema='' and ")
+ + "table_name in ('warehouse', 'district', 'customer', 'history', 'orders', 'new_orders', 'order_line', 'stock', 'item')";
+ var count = await cmd.ExecuteScalarAsync(cancellationToken);
+ if (count is long and 9)
+ {
+ return;
+ }
+
+ var commands = SchemaDefinition.CreateTablesPostgreSql.Split(";");
+ foreach (var command in commands)
+ {
+ if (command.Trim() == "")
+ {
+ continue;
+ }
+ cmd.CommandText = command;
+ await cmd.ExecuteNonQueryAsync(cancellationToken);
+ }
+ }
+
+ internal static async Task DropSchemaAsync(SpannerConnection connection, CancellationToken cancellationToken)
+ {
+ await using var cmd = connection.CreateCommand();
+ var commands = SchemaDefinition.DropTables.Split(";");
+ foreach (var command in commands)
+ {
+ if (command.Trim() == "")
+ {
+ continue;
+ }
+ cmd.CommandText = command;
+ await cmd.ExecuteNonQueryAsync(cancellationToken);
+ }
+ }
+}
\ No newline at end of file
diff --git a/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/Stats.cs b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/Stats.cs
new file mode 100644
index 00000000..56ab5e10
--- /dev/null
+++ b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/Stats.cs
@@ -0,0 +1,97 @@
+namespace Google.Cloud.Spanner.DataProvider.Benchmarks.tpcc;
+
+internal class Stats
+{
+ private readonly DateTime _startTime;
+ private ulong _numTransactions;
+ private ulong _numTransactionsStarted;
+ private ulong _numTransactionsCompleted;
+ private ulong _numFailedTransactions;
+ private ulong _numNewOrderTransactions;
+ private ulong _numPaymentTransactions;
+ private ulong _numOrderStatusTransactions;
+ private ulong _numDeliveryTransactions;
+ private ulong _numStockLevelTransactions;
+ private Exception? _lastException;
+
+ private ulong _totalMillis;
+
+ internal Stats()
+ {
+ _startTime = DateTime.UtcNow;
+ }
+
+ internal void RegisterTransactionStarted()
+ {
+ Interlocked.Increment(ref _numTransactionsStarted);
+ }
+
+ internal void RegisterTransactionCompleted()
+ {
+ Interlocked.Increment(ref _numTransactionsCompleted);
+ }
+
+ internal void RegisterTransaction(TpccRunner.TransactionType transactionType, TimeSpan duration)
+ {
+ Interlocked.Increment(ref _numTransactions);
+ Interlocked.Add(ref _totalMillis, (ulong) duration.TotalMilliseconds);
+ switch (transactionType)
+ {
+ case TpccRunner.TransactionType.NewOrder:
+ Interlocked.Increment(ref _numNewOrderTransactions);
+ break;
+ case TpccRunner.TransactionType.Payment:
+ Interlocked.Increment(ref _numPaymentTransactions);
+ break;
+ case TpccRunner.TransactionType.OrderStatus:
+ Interlocked.Increment(ref _numOrderStatusTransactions);
+ break;
+ case TpccRunner.TransactionType.Delivery:
+ Interlocked.Increment(ref _numDeliveryTransactions);
+ break;
+ case TpccRunner.TransactionType.StockLevel:
+ Interlocked.Increment(ref _numStockLevelTransactions);
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(transactionType), transactionType, null);
+ }
+ }
+
+ internal void RegisterFailedTransaction(TpccRunner.TransactionType transactionType, TimeSpan duration, Exception error)
+ {
+ Interlocked.Increment(ref _numFailedTransactions);
+ lock (this)
+ {
+ _lastException = error;
+ }
+ }
+
+ internal void LogStats()
+ {
+ lock (this)
+ {
+ if (_lastException != null)
+ {
+ Console.Error.WriteLine(_lastException);
+ _lastException = null;
+ }
+ }
+ Console.Write(ToString());
+ }
+
+ public override string ToString()
+ {
+ return $" Total duration: {DateTime.UtcNow - _startTime}{Environment.NewLine}" +
+ $"Transactions/sec: {Interlocked.Read(ref _numTransactions) / (DateTime.UtcNow - _startTime).TotalSeconds}{Environment.NewLine}" +
+ $" Total: {Interlocked.Read(ref _numTransactions)}{Environment.NewLine}" +
+ $" Avg: {Interlocked.Read(ref _totalMillis) / Interlocked.Read(ref _numTransactions)}{Environment.NewLine}" +
+ $" Started: {Interlocked.Read(ref _numTransactionsStarted)}{Environment.NewLine}" +
+ $" Completed: {Interlocked.Read(ref _numTransactionsCompleted)}{Environment.NewLine}" +
+ $" Failed: {Interlocked.Read(ref _numFailedTransactions)}{Environment.NewLine}" +
+ $" Num new order: {Interlocked.Read(ref _numNewOrderTransactions)}{Environment.NewLine}" +
+ $" Num payment: {Interlocked.Read(ref _numPaymentTransactions)}{Environment.NewLine}" +
+ $"Num order status: {Interlocked.Read(ref _numOrderStatusTransactions)}{Environment.NewLine}" +
+ $" Num delivery: {Interlocked.Read(ref _numDeliveryTransactions)}{Environment.NewLine}" +
+ $" Num stock level: {Interlocked.Read(ref _numStockLevelTransactions)}{Environment.NewLine}";
+ }
+}
\ No newline at end of file
diff --git a/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/TpccRunner.cs b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/TpccRunner.cs
new file mode 100644
index 00000000..bf753df6
--- /dev/null
+++ b/drivers/spanner-ado-net/spanner-ado-net-benchmarks/tpcc/TpccRunner.cs
@@ -0,0 +1,861 @@
+// Copyright 2025 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+using System.Data;
+using System.Data.Common;
+using System.Diagnostics;
+using Google.Cloud.Spanner.Data;
+using Google.Cloud.Spanner.DataProvider.Benchmarks.tpcc.loader;
+using Google.Cloud.Spanner.V1;
+using Google.Rpc;
+using SpannerException = Google.Cloud.SpannerLib.SpannerException;
+
+namespace Google.Cloud.Spanner.DataProvider.Benchmarks.tpcc;
+
+internal class TpccRunner
+{
+ internal enum TransactionType
+ {
+ Unknown,
+ NewOrder,
+ Payment,
+ OrderStatus,
+ Delivery,
+ StockLevel,
+ }
+
+ private readonly Stats _stats;
+ private readonly DbConnection _connection;
+ private readonly int _numWarehouses;
+ private readonly int _numDistrictsPerWarehouse;
+ private readonly int _numCustomersPerDistrict;
+ private readonly int _numItems;
+ private readonly bool _isClientLib;
+
+ private DbTransaction? _currentTransaction;
+
+ internal TpccRunner(
+ Stats stats,
+ DbConnection connection,
+ int numWarehouses,
+ int numDistrictsPerWarehouse = 10,
+ int numCustomersPerDistrict = 3000,
+ int numItems = 100_000)
+ {
+ _stats = stats;
+ _connection = connection;
+ _numWarehouses = numWarehouses;
+ _numDistrictsPerWarehouse = numDistrictsPerWarehouse;
+ _numCustomersPerDistrict = numCustomersPerDistrict;
+ _numItems = numItems;
+ _isClientLib = connection is Data.SpannerConnection;
+ }
+
+ internal async Task RunAsync(CancellationToken cancellationToken)
+ {
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ await RunTransactionAsync(cancellationToken);
+ }
+ }
+
+ internal async Task RunTransactionAsync(CancellationToken cancellationToken)
+ {
+ var watch = Stopwatch.StartNew();
+ var transaction = Random.Shared.Next(23);
+ var transactionType = TransactionType.Unknown;
+ var attempts = 0;
+ while (true)
+ {
+ attempts++;
+ try
+ {
+ if (transaction < 10)
+ {
+ transactionType = TransactionType.NewOrder;
+ await NewOrderAsync(cancellationToken);
+ }
+ else if (transaction < 20)
+ {
+ transactionType = TransactionType.Payment;
+ await PaymentAsync(cancellationToken);
+ }
+ else if (transaction < 21)
+ {
+ transactionType = TransactionType.OrderStatus;
+ await OrderStatusAsync(cancellationToken);
+ }
+ else if (transaction < 22)
+ {
+ transactionType = TransactionType.Delivery;
+ await DeliveryAsync(cancellationToken);
+ }
+ else if (transaction < 23)
+ {
+ transactionType = TransactionType.StockLevel;
+ await StockLevelAsync(cancellationToken);
+ }
+ else
+ {
+ throw new ArgumentException($"Invalid transaction type {transaction}");
+ }
+
+ _stats.RegisterTransaction(transactionType, watch.Elapsed);
+ break;
+ }
+ catch (Exception exception)
+ {
+ await SilentRollbackTransactionAsync(cancellationToken);
+ if (attempts < 10)
+ {
+ if (exception is SpannerException { Code: Code.Aborted })
+ {
+ continue;
+ }
+
+ if (exception is Data.SpannerException { ErrorCode: ErrorCode.Aborted })
+ {
+ continue;
+ }
+ }
+ else
+ {
+ await Console.Error.WriteLineAsync($"Giving up after {attempts} attempts");
+ }
+
+ _stats.RegisterFailedTransaction(transactionType, watch.Elapsed, exception);
+ break;
+ }
+ finally
+ {
+ if (_currentTransaction != null)
+ {
+ await Console.Error.WriteLineAsync("Transaction still open!");
+ await _currentTransaction.DisposeAsync();
+ _currentTransaction = null;
+ }
+ }
+ }
+ }
+
+ private async Task NewOrderAsync(CancellationToken cancellationToken)
+ {
+ var warehouseId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numWarehouses));
+ var districtId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numDistrictsPerWarehouse));
+ var customerId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numCustomersPerDistrict));
+
+ var orderLineCount = Random.Shared.Next(5, 16);
+ var itemIds = new long[orderLineCount];
+ var supplyWarehouses = new long[orderLineCount];
+ var quantities = new int[orderLineCount];
+ var rollback = Random.Shared.Next(100);
+ var allLocal = 1;
+
+ for (var line = 0; line < orderLineCount; line++)
+ {
+ if (rollback == 1 && line == orderLineCount - 1)
+ {
+ itemIds[line] = DataLoader.ReverseBitsUnsigned(long.MaxValue);
+ }
+ else
+ {
+ // TODO: Make sure that the chosen item IDs are unique.
+ itemIds[line] = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numItems));
+ }
+
+ if (Random.Shared.Next(100) == 50)
+ {
+ supplyWarehouses[line] = GetOtherWarehouseId(warehouseId);
+ allLocal = 0;
+ }
+ else
+ {
+ supplyWarehouses[line] = warehouseId;
+ }
+
+ quantities[line] = Random.Shared.Next(1, 10);
+ }
+
+ await BeginTransactionAsync("new_order", cancellationToken);
+
+ // TODO: These queries can run in parallel.
+ var row = await ExecuteRowAsync(
+ "SELECT c_discount, c_last, c_credit, w_tax " +
+ "FROM customer c, warehouse w " +
+ "WHERE w.w_id = $1 AND c.w_id = w.w_id AND c.d_id = $2 AND c.c_id = $3 " +
+ "FOR UPDATE", cancellationToken,
+ warehouseId, districtId, customerId);
+ var discount = ToDecimal(row[0]);
+ var last = (string)row[1];
+ var credit = (string)row[2];
+ var warehouseTax = ToDecimal(row[3]);
+
+ row = await ExecuteRowAsync(
+ "SELECT d_next_o_id, d_tax " +
+ "FROM district " +
+ "WHERE w_id = $1 AND d_id = $2 FOR UPDATE", cancellationToken,
+ warehouseId, districtId);
+ var districtNextOrderId = row[0] is DBNull ? 0L : (long)row[0];
+ var districtTax = ToDecimal(row[1]);
+
+ object batch = _isClientLib ? (_currentTransaction as Data.SpannerTransaction)!.CreateBatchDmlCommand() : _connection.CreateBatch();
+ CreateBatchCommand(
+ batch,
+ "UPDATE district SET d_next_o_id = $1 WHERE d_id = $2 AND w_id= $3",
+ districtNextOrderId + 1L, districtId, warehouseId);
+ CreateBatchCommand(
+ batch,
+ "INSERT INTO orders (o_id, d_id, w_id, c_id, o_entry_d, o_ol_cnt, o_all_local) " +
+ "VALUES ($1,$2,$3,$4,CURRENT_TIMESTAMP,$5,$6)",
+ districtNextOrderId, districtId, warehouseId, customerId, orderLineCount, allLocal);
+ CreateBatchCommand(
+ batch,
+ "INSERT INTO new_orders (o_id, c_id, d_id, w_id) VALUES ($1,$2,$3,$4)",
+ districtNextOrderId, customerId, districtId, warehouseId);
+
+ for (var line = 0; line < orderLineCount; line++)
+ {
+ var orderLineSupplyWarehouseId = supplyWarehouses[line];
+ var orderLineItemId = itemIds[line];
+ var orderLineQuantity = quantities[line];
+ try
+ {
+ row = await ExecuteRowAsync(
+ "SELECT i_price, i_name, i_data FROM item WHERE i_id = $1",
+ cancellationToken,
+ orderLineItemId);
+ }
+ catch (RowNotFoundException)
+ {
+ // TODO: Record deliberate rollback
+ await RollbackTransactionAsync(cancellationToken);
+ return;
+ }
+
+ var itemPrice = ToDecimal(row[0]);
+ var itemName = (string)row[1];
+ var itemData = (string)row[2];
+
+ row = await ExecuteRowAsync(
+ "SELECT s_quantity, s_data, s_dist_01, s_dist_02, s_dist_03, s_dist_04, s_dist_05, s_dist_06, s_dist_07, s_dist_08, s_dist_09, s_dist_10 " +
+ "FROM stock " +
+ "WHERE s_i_id = $1 AND w_id= $2 FOR UPDATE",
+ cancellationToken,
+ orderLineItemId, orderLineSupplyWarehouseId);
+ var stockQuantity = (long)row[0];
+ var stockData = (string)row[1];
+ var stockDistrict = new string[10];
+ for (int i = 2; i < stockDistrict.Length + 2; i++)
+ {
+ stockDistrict[i - 2] = (string)row[i];
+ }
+
+ var orderLineDistrictInfo =
+ stockDistrict[(int)(DataLoader.ReverseBitsUnsigned((ulong)districtId) % stockDistrict.Length)];
+ if (stockQuantity > orderLineQuantity)
+ {
+ stockQuantity = stockQuantity - orderLineQuantity;
+ }
+ else
+ {
+ stockQuantity = stockQuantity - orderLineQuantity + 91;
+ }
+
+ CreateBatchCommand(batch, "UPDATE stock SET s_quantity=$1 WHERE s_i_id=$2 AND w_id=$3",
+ stockQuantity, orderLineItemId, orderLineSupplyWarehouseId);
+
+ var totalTax = 1m + warehouseTax + districtTax;
+ var discountFactor = 1m - discount;
+ var orderLineAmount = orderLineQuantity * itemPrice * totalTax * discountFactor;
+ CreateBatchCommand(batch,
+ "INSERT INTO order_line (o_id, c_id, d_id, w_id, ol_number, ol_i_id, ol_supply_w_id, ol_quantity, ol_amount, ol_dist_info) " +
+ "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
+ districtNextOrderId,
+ customerId,
+ districtId,
+ warehouseId,
+ line,
+ orderLineItemId,
+ orderLineSupplyWarehouseId,
+ orderLineQuantity,
+ orderLineAmount,
+ orderLineDistrictInfo);
+ }
+
+ if (batch is Data.SpannerBatchCommand spannerBatchCommand)
+ {
+ await spannerBatchCommand.ExecuteNonQueryAsync(cancellationToken);
+ }
+ else if (batch is DbBatch dbBatch)
+ {
+ await dbBatch.ExecuteNonQueryAsync(cancellationToken);
+ }
+ else
+ {
+ throw new NotSupportedException("Batch type not supported");
+ }
+ await CommitTransactionAsync(cancellationToken);
+ }
+
+ private async Task PaymentAsync(CancellationToken cancellationToken)
+ {
+ var warehouseId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numWarehouses));
+ var districtId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numDistrictsPerWarehouse));
+ var customerId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numCustomersPerDistrict));
+ var amount = Random.Shared.Next(1, 500000) / 100m;
+
+ long customerWarehouseId;
+ long customerDistrictId;
+ var lastName = LastNameGenerator.GenerateLastName(long.MaxValue);
+ bool byName;
+ object[] row;
+ if (Random.Shared.Next(100) < 60)
+ {
+ byName = true;
+ }
+ else
+ {
+ byName = false;
+ }
+ if (Random.Shared.Next(100) < 85)
+ {
+ customerWarehouseId = warehouseId;
+ customerDistrictId = districtId;
+ }
+ else
+ {
+ customerWarehouseId = GetOtherWarehouseId(warehouseId);
+ customerDistrictId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numDistrictsPerWarehouse));
+ }
+ await BeginTransactionAsync("payment", cancellationToken);
+ await ExecuteNonQueryAsync("UPDATE warehouse SET w_ytd = w_ytd + $1 WHERE w_id = $2",
+ cancellationToken, amount, warehouseId);
+
+ row = await ExecuteRowAsync(
+ "SELECT w_street_1, w_street_2, w_city, w_state, w_zip, w_name "
+ + "FROM warehouse "
+ + "WHERE w_id = $1",
+ cancellationToken, warehouseId);
+ var warehouseStreet1 = (string) row[0];
+ var warehouseStreet2 = (string) row[1];
+ var warehouseCity = (string) row[2];
+ var warehouseState = (string) row[3];
+ var warehouseZip = (string) row[4];
+ var warehouseName = (string) row[5];
+
+ await ExecuteNonQueryAsync(
+ "UPDATE district SET d_ytd = d_ytd + $1 WHERE w_id = $2 AND d_id= $3",
+ cancellationToken, amount, warehouseId, districtId);
+
+ row = await ExecuteRowAsync(
+ "SELECT d_street_1, d_street_2, d_city, d_state, d_zip, d_name "
+ + "FROM district "
+ + "WHERE w_id = $1 AND d_id = $2",
+ cancellationToken, warehouseId, districtId);
+ var districtStreet1 = (string) row[0];
+ var districtStreet2 = (string) row[1];
+ var districtCity = (string) row[2];
+ var districtState = (string) row[3];
+ var districtZip = (string) row[4];
+ var districtName = (string) row[5];
+
+ if (byName)
+ {
+ row = await ExecuteRowAsync(
+ "SELECT count(c_id) namecnt "
+ + "FROM customer "
+ + "WHERE w_id = $1 AND d_id= $2 AND c_last=$3",
+ cancellationToken, customerWarehouseId, customerDistrictId, lastName);
+ var nameCount = (int) (long) row[0];
+ if (nameCount % 2 == 0)
+ {
+ nameCount++;
+ }
+ var resultSet = await ExecuteQueryAsync(
+ "SELECT c_id "
+ + "FROM customer "
+ + "WHERE w_id=$1 AND d_id=$2 AND c_last=$3 "
+ + "ORDER BY c_first",
+ cancellationToken, customerWarehouseId, customerDistrictId, lastName);
+ for (var counter = 0; counter < Math.Min(nameCount, resultSet.Count); counter++)
+ {
+ customerId = (long) resultSet[counter][0];
+ }
+ }
+ row = await ExecuteRowAsync(
+ "SELECT c_first, c_middle, c_last, c_street_1, c_street_2, c_city, c_state, c_zip, c_phone, c_credit, c_credit_lim, c_discount, c_balance, c_ytd_payment, c_since "
+ + "FROM customer "
+ + "WHERE w_id=$1 AND d_id=$2 AND c_id=$3 FOR UPDATE",
+ cancellationToken, customerWarehouseId, customerDistrictId, customerId);
+ var firstName = (string) row[0];
+ var middleName = (string) row[1];
+ lastName = (string) row[2];
+ var street1 = (string) row[3];
+ var street2 = (string) row[4];
+ var city = (string) row[5];
+ var state = (string) row[6];
+ var zip = (string) row[7];
+ var phone = (string) row[8];
+ var credit = (string) row[9];
+ var creditLimit = (long) row[10];
+ var discount = ToDecimal(row[11]);
+ var balance = ToDecimal(row[12]);
+ var ytdPayment = ToDecimal(row[13]);
+ var since = (DateTime) row[14];
+
+ // TODO: Use batching from here
+ balance = balance - amount;
+ ytdPayment = ytdPayment + amount;
+ if ("BC".Equals(credit))
+ {
+ row = await ExecuteRowAsync(
+ "SELECT c_data FROM customer WHERE w_id=$1 AND d_id=$2 AND c_id=$3",
+ cancellationToken, customerWarehouseId, customerDistrictId, customerId);
+ var customerData = (string)row[0];
+ var newCustomerData =
+ $"| {customerId} {customerDistrictId} {customerWarehouseId} {districtId} {warehouseId} {amount} {DateTime.Now} {customerData}";
+ if (newCustomerData.Length > 500)
+ {
+ newCustomerData = newCustomerData.Substring(0, 500);
+ }
+ await ExecuteNonQueryAsync(
+ "UPDATE customer "
+ + "SET c_balance=$1, c_ytd_payment=$2, c_data=$3 "
+ + "WHERE w_id = $4 AND d_id=$5 AND c_id=$6",
+ cancellationToken,
+ balance,
+ ytdPayment,
+ newCustomerData,
+ customerWarehouseId,
+ customerDistrictId,
+ customerId
+ );
+ }
+ else
+ {
+ await ExecuteNonQueryAsync(
+ "UPDATE customer "
+ + "SET c_balance=$1, c_ytd_payment=$2 "
+ + "WHERE w_id = $3 AND d_id=$4 AND c_id=$5",
+ cancellationToken, balance, ytdPayment, customerWarehouseId, customerDistrictId, customerId);
+ }
+
+ var data = $"{warehouseName} {districtName}";
+ if (data.Length > 24)
+ {
+ data = data.Substring(0, 24);
+ }
+ await ExecuteNonQueryAsync(
+ "INSERT INTO history (d_id, w_id, c_id, h_d_id, h_w_id, h_date, h_amount, h_data) " +
+ "VALUES ($1,$2,$3,$4,$5,CURRENT_TIMESTAMP,$6,$7)",
+ cancellationToken,
+ customerDistrictId,
+ customerWarehouseId,
+ customerId,
+ districtId,
+ warehouseId,
+ amount,
+ data);
+
+ await CommitTransactionAsync(cancellationToken);
+ }
+
+ private async Task OrderStatusAsync(CancellationToken cancellationToken)
+ {
+ var warehouseId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numWarehouses));
+ var districtId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numDistrictsPerWarehouse));
+ var customerId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numCustomersPerDistrict));
+
+ var lastName = LastNameGenerator.GenerateLastName(long.MaxValue);
+ object[] row;
+ var byName = Random.Shared.Next(100) < 60;
+
+ decimal balance;
+ string first, middle, last;
+
+ await BeginTransactionAsync("order_status", cancellationToken);
+ if (byName)
+ {
+ row = await ExecuteRowAsync(
+ "SELECT count(c_id) namecnt "
+ + "FROM customer "
+ + "WHERE w_id=$1 AND d_id=$2 AND c_last=$3",
+ cancellationToken, warehouseId, districtId, lastName);
+ int nameCount = (int) (long) row[0];
+ if (nameCount % 2 == 0)
+ {
+ nameCount++;
+ }
+ var resultSet = await ExecuteQueryAsync(
+ "SELECT c_balance, c_first, c_middle, c_id "
+ + "FROM customer WHERE w_id = $1 AND d_id=$2 AND c_last=$3 "
+ + "ORDER BY c_first",
+ cancellationToken, warehouseId, districtId, lastName);
+ for (int counter = 0; counter < Math.Min(nameCount, resultSet.Count); counter++)
+ {
+ balance = ToDecimal(resultSet[counter][0]);
+ first = (string) resultSet[counter][1];
+ middle = (string) resultSet[counter][2];
+ customerId = (long) resultSet[counter][3];
+ }
+ }
+ else
+ {
+ row = await ExecuteRowAsync(
+ "SELECT c_balance, c_first, c_middle, c_last "
+ + "FROM customer "
+ + "WHERE w_id = $1 AND d_id=$2 AND c_id=$3",
+ cancellationToken, warehouseId, districtId, customerId);
+ balance = ToDecimal(row[0]);
+ first = (string) row[1];
+ middle = (string) row[2];
+ last = (string) row[3];
+ }
+
+ var maybeRow = await ExecuteRowAsync(false,
+ "SELECT o_id, o_carrier_id, o_entry_d "
+ + "FROM orders "
+ + "WHERE w_id = $1 AND d_id = $2 AND c_id = $3 "
+ + "ORDER BY o_id DESC",
+ cancellationToken, warehouseId, districtId, customerId);
+ var orderId = maybeRow == null ? 0L : (long) maybeRow[0];
+
+ long item_id, supply_warehouse_id, quantity;
+ decimal amount;
+ DateTime? delivery_date;
+ var results = await ExecuteQueryAsync(
+ "SELECT ol_i_id, ol_supply_w_id, ol_quantity, ol_amount, ol_delivery_d "
+ + "FROM order_line "
+ + "WHERE w_id = $1 AND d_id = $2 AND o_id = $3",
+ cancellationToken, warehouseId, districtId, orderId);
+ for (var counter = 0; counter < results.Count; counter++)
+ {
+ item_id = (long) results[counter][0]; // item_id
+ supply_warehouse_id = (long) results[counter][1]; // supply_warehouse_id
+ quantity = (long) results[counter][2]; // quantity
+ amount = ToDecimal(results[counter][3]); // amount
+ delivery_date = results[counter][4] is DBNull ? null : (DateTime) results[counter][4]; // delivery_date
+ }
+ await CommitTransactionAsync(cancellationToken);
+ }
+
+ private async Task DeliveryAsync(CancellationToken cancellationToken)
+ {
+ var warehouseId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numWarehouses));
+ var carrierId = Random.Shared.Next(10);
+
+ await BeginTransactionAsync("delivery", cancellationToken);
+
+ for (var district = 0L; district < _numDistrictsPerWarehouse; district++)
+ {
+ var districtId = DataLoader.ReverseBitsUnsigned((ulong)district);
+ var row = await ExecuteRowAsync(false,
+ "SELECT o_id, c_id "
+ + "FROM new_orders "
+ + "WHERE d_id = $1 AND w_id = $2 "
+ + "ORDER BY o_id ASC "
+ + "LIMIT 1 FOR UPDATE",
+ cancellationToken, districtId, warehouseId);
+ if (row != null)
+ {
+ var newOrderId = (long)row[0];
+ var customerId = (long)row[1];
+ await ExecuteNonQueryAsync(
+ "DELETE "
+ + "FROM new_orders "
+ + "WHERE o_id = $1 AND c_id = $2 AND d_id = $3 AND w_id = $4",
+ cancellationToken, newOrderId, customerId, districtId, warehouseId);
+ row = await ExecuteRowAsync(
+ "SELECT c_id FROM orders WHERE o_id = $1 AND d_id = $2 AND w_id = $3",
+ cancellationToken, newOrderId, districtId, warehouseId);
+ await ExecuteNonQueryAsync(
+ "UPDATE orders "
+ + "SET o_carrier_id = $1 "
+ + "WHERE o_id = $2 AND c_id = $3 AND d_id = $4 AND w_id = $5",
+ cancellationToken, carrierId, newOrderId, customerId, districtId, warehouseId);
+ await ExecuteNonQueryAsync(
+ "UPDATE order_line "
+ + "SET ol_delivery_d = CURRENT_TIMESTAMP "
+ + "WHERE o_id = $1 AND c_id = $2 AND d_id = $3 AND w_id = $4",
+ cancellationToken, newOrderId, customerId, districtId, warehouseId);
+ row = await ExecuteRowAsync(
+ "SELECT SUM(ol_amount) sm "
+ + "FROM order_line "
+ + "WHERE o_id = $1 AND c_id = $2 AND d_id = $3 AND w_id = $4",
+ cancellationToken, newOrderId, customerId, districtId, warehouseId);
+ var sumOrderLineAmount = ToDecimal(row[0]);
+ await ExecuteNonQueryAsync(
+ "UPDATE customer "
+ + "SET c_balance = c_balance + $1, c_delivery_cnt = c_delivery_cnt + 1 "
+ + "WHERE c_id = $2 AND d_id = $3 AND w_id = $4",
+ cancellationToken, sumOrderLineAmount, customerId, districtId, warehouseId);
+ }
+ }
+ await CommitTransactionAsync(cancellationToken);
+ }
+
+ private async Task StockLevelAsync(CancellationToken cancellationToken)
+ {
+ var warehouseId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numWarehouses));
+ var districtId = DataLoader.ReverseBitsUnsigned((ulong)Random.Shared.Next(_numDistrictsPerWarehouse));
+ var level = Random.Shared.Next(10, 21);
+
+ await BeginTransactionAsync("stock_level", cancellationToken);
+ String stockLevelQueries = "case1";
+ Object[] row;
+
+ row = await ExecuteRowAsync(
+ "SELECT d_next_o_id FROM district WHERE d_id = $1 AND w_id= $2",
+ cancellationToken, districtId, warehouseId);
+ var nextOrderId = row[0] is DBNull ? 0L : (long) row[0];
+ var resultSet =
+ await ExecuteQueryAsync(
+ "SELECT COUNT(DISTINCT (s_i_id)) "
+ + "FROM order_line ol, stock s "
+ + "WHERE ol.w_id = $1 "
+ + "AND ol.d_id = $2 "
+ + "AND ol.o_id < $3 "
+ + "AND ol.o_id >= $4 "
+ + "AND s.w_id= $5 "
+ + "AND s_i_id=ol_i_id "
+ + "AND s_quantity < $6",
+ cancellationToken,
+ warehouseId, districtId, nextOrderId, nextOrderId - 20, warehouseId, level);
+ for (var counter = 0; counter < resultSet.Count; counter++) {
+ var orderLineItemId = (long) resultSet[counter][0];
+ row = await ExecuteRowAsync(
+ "SELECT count(1) FROM stock "
+ + "WHERE w_id = $1 AND s_i_id = $2 "
+ + "AND s_quantity < $3",
+ cancellationToken, warehouseId, orderLineItemId, level);
+ var stockCount = (long) row[0];
+ }
+
+ await CommitTransactionAsync(cancellationToken);
+ }
+
+ private decimal ToDecimal(object value)
+ {
+ return _isClientLib ? ((PgNumeric) value).ToDecimal(LossOfPrecisionHandling.Truncate) : (decimal) value;
+ }
+
+ private async Task BeginTransactionAsync(string tag, CancellationToken cancellationToken = default)
+ {
+ if (_connection is Data.SpannerConnection spannerConnection)
+ {
+ _currentTransaction = await spannerConnection.BeginTransactionAsync(
+ SpannerTransactionCreationOptions.ReadWrite.WithIsolationLevel(IsolationLevel.RepeatableRead),
+ new SpannerTransactionOptions
+ {
+ Tag = tag,
+ },
+ cancellationToken);
+ }
+ else if (_connection is SpannerConnection connection)
+ {
+ _currentTransaction = await connection.BeginTransactionAsync(IsolationLevel.RepeatableRead, cancellationToken);
+ await ExecuteNonQueryAsync($"set local transaction_tag = '{tag}'", cancellationToken);
+ }
+ }
+
+ private async Task CommitTransactionAsync(CancellationToken cancellationToken = default)
+ {
+ if (_currentTransaction != null)
+ {
+ await _currentTransaction.CommitAsync(cancellationToken);
+ await _currentTransaction.DisposeAsync();
+ _currentTransaction = null;
+ }
+ }
+
+ private async Task SilentRollbackTransactionAsync(CancellationToken cancellationToken = default)
+ {
+ try
+ {
+ if (_currentTransaction != null)
+ {
+ await RollbackTransactionAsync(cancellationToken);
+ }
+ else
+ {
+ await ExecuteNonQueryAsync("rollback", cancellationToken);
+ }
+ }
+ catch (Exception)
+ {
+ if (_currentTransaction != null)
+ {
+ await _currentTransaction.DisposeAsync();
+ _currentTransaction = null;
+ }
+ }
+ }
+
+ private async Task RollbackTransactionAsync(CancellationToken cancellationToken = default)
+ {
+ if (_currentTransaction != null)
+ {
+ await _currentTransaction.RollbackAsync(cancellationToken);
+ await _currentTransaction.DisposeAsync();
+ _currentTransaction = null;
+ }
+ }
+
+ private void CreateBatchCommand(object batch, string commandText, params object[] parameters)
+ {
+ if (batch is Data.SpannerBatchCommand command)
+ {
+ CreateBatchCommand(command, commandText, parameters);
+ }
+ else if (batch is DbBatch dbBatch)
+ {
+ CreateBatchCommand(dbBatch, commandText, parameters);
+ }
+ else
+ {
+ throw new ArgumentException("unknown batch type");
+ }
+ }
+
+ private void CreateBatchCommand(Data.SpannerBatchCommand batch, string commandText, params object[] parameters)
+ {
+ var paramCollection = new Data.SpannerParameterCollection();
+ for (var i=0; i < parameters.Length; i++)
+ {
+ var value = parameters[i];
+ if (value is decimal d)
+ {
+ value = PgNumeric.FromDecimal(d);
+ }
+ paramCollection.Add(new Data.SpannerParameter {ParameterName = $"p{i+1}", Value = value});
+ }
+ batch.Add(commandText, paramCollection);
+ }
+
+ private void CreateBatchCommand(DbBatch batch, string commandText, params object[] parameters)
+ {
+ var batchCommand = batch.CreateBatchCommand();
+ batchCommand.CommandText = commandText;
+ for (var i = 0; i < parameters.Length; i++)
+ {
+ CreateParameter(batchCommand, $"p{i+1}", parameters[i]);
+ }
+ batch.BatchCommands.Add(batchCommand);
+ }
+
+ private void CreateParameter(DbBatchCommand cmd, string parameterName, object parameterValue)
+ {
+ var parameter = cmd.CreateParameter();
+ parameter.ParameterName = parameterName;
+ parameter.Value = parameterValue;
+ cmd.Parameters.Add(parameter);
+ }
+
+ private async Task ExecuteNonQueryAsync(string commandText,
+ CancellationToken cancellationToken, params object[] parameters)
+ {
+ using var command = CreateCommand(commandText, parameters);
+ await command.ExecuteNonQueryAsync(cancellationToken);
+ }
+
+ private Task