diff --git a/Cargo.lock b/Cargo.lock index 14f9a0682f9..edcfc1691ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -771,6 +771,16 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "case-conversion-client" +version = "2.0.0" +dependencies = [ + "anyhow", + "env_logger 0.10.2", + "spacetimedb-sdk", + "test-counter", +] + [[package]] name = "cast" version = "0.3.0" @@ -6945,6 +6955,14 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sdk-test-case-conversion" +version = "0.1.0" +dependencies = [ + "log", + "spacetimedb 2.0.0", +] + [[package]] name = "sdk-test-event-table-module" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 0aae96ae403..fbeb08f2f4a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,12 +50,14 @@ members = [ "modules/sdk-test-connect-disconnect", "modules/sdk-test-procedure", "modules/sdk-test-view", + "modules/sdk-test-case-conversion", "modules/sdk-test-event-table", "sdks/rust/tests/test-client", "sdks/rust/tests/test-counter", "sdks/rust/tests/connect_disconnect_client", "sdks/rust/tests/procedure-client", "sdks/rust/tests/view-client", + "sdks/rust/tests/case-conversion-client", "sdks/rust/tests/event-table-client", "tools/ci", "tools/upgrade-version", diff --git a/crates/bindings-typescript/case-conversion-test-client/.gitignore b/crates/bindings-typescript/case-conversion-test-client/.gitignore new file mode 100644 index 00000000000..b9470778764 --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +dist/ diff --git a/crates/bindings-typescript/case-conversion-test-client/README.md b/crates/bindings-typescript/case-conversion-test-client/README.md new file mode 100644 index 00000000000..e3738c1360e --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/README.md @@ -0,0 +1,80 @@ +# Case Conversion Test Client (TypeScript) + +TypeScript SDK test client for the Rust module `sdk-test-case-conversion`. +Tests that the TS SDK correctly handles case-converted names with digit boundaries. + +## What it tests + +- Table accessors: `player1`, `person2`, `person_at_level_2` +- Field names with digit boundaries: `player1Id`, `currentLevel2`, `status3Field` +- Nested structs: `personInfo.ageValue1`, `personInfo.scoreTotal` +- Enum variants: `Player2Status` (`Active1`, `BannedUntil`) +- Explicit reducer names: `banPlayer1` +- Query builder: filters on digit-boundary columns, right semijoins + +## Prerequisites + +1. Build the SpacetimeDB CLI and standalone server: + + ```bash + cargo build -p spacetimedb-cli -p spacetimedb-standalone + ``` + +2. Build the TS SDK (from repo root): + ```bash + cd crates/bindings-typescript && pnpm install && pnpm build + ``` + +## Regenerate bindings + +If the Rust module (`modules/sdk-test-case-conversion`) changes: + +```bash +pnpm run generate +``` + +This runs `spacetime generate` against the module and formats the output. + +## Run via the Rust test harness (recommended) + +From the repo root: + +```bash +cargo test -p spacetimedb-sdk --test test case_conversion_rust_ts_client +``` + +This compiles the Rust module, starts a local server, publishes the module, generates +bindings, builds the TS client, and runs each subcommand (`insert-player`, `insert-person`, +`ban-player`, `query-builder-filter`, `query-builder-join`). + +## Run manually + +1. Start the standalone server: + + ```bash + spacetime start + ``` + +2. Publish the module: + + ```bash + spacetime publish sdk-test-case-conversion \ + --module-path modules/sdk-test-case-conversion --server local + ``` + +3. Generate bindings (if not already done): + + ```bash + cd crates/bindings-typescript/case-conversion-test-client + pnpm run generate + ``` + +4. Build and run a test: + ```bash + pnpm install + pnpm run build + SPACETIME_SDK_TEST_DB_NAME=sdk-test-case-conversion node dist/index.js insert-player + ``` + +Available subcommands: `insert-player`, `insert-person`, `ban-player`, +`query-builder-filter`, `query-builder-join`. diff --git a/crates/bindings-typescript/case-conversion-test-client/package-lock.json b/crates/bindings-typescript/case-conversion-test-client/package-lock.json new file mode 100644 index 00000000000..b9f0f2afba4 --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/package-lock.json @@ -0,0 +1,517 @@ +{ + "name": "case-conversion-test-client", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "case-conversion-test-client", + "version": "1.0.0", + "devDependencies": { + "@types/node": "^20.0.0", + "esbuild": "^0.24.2", + "typescript": "^5.0.0" + } + }, + "../../dist": { + "extraneous": true + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.2.tgz", + "integrity": "sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.2.tgz", + "integrity": "sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.2.tgz", + "integrity": "sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.2.tgz", + "integrity": "sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.2.tgz", + "integrity": "sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.2.tgz", + "integrity": "sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.2.tgz", + "integrity": "sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.2.tgz", + "integrity": "sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.2.tgz", + "integrity": "sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.2.tgz", + "integrity": "sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.2.tgz", + "integrity": "sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.2.tgz", + "integrity": "sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.2.tgz", + "integrity": "sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.2.tgz", + "integrity": "sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.2.tgz", + "integrity": "sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.2.tgz", + "integrity": "sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.2.tgz", + "integrity": "sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.24.2.tgz", + "integrity": "sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.2.tgz", + "integrity": "sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.2.tgz", + "integrity": "sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.2.tgz", + "integrity": "sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.2.tgz", + "integrity": "sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.2.tgz", + "integrity": "sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.2.tgz", + "integrity": "sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.2.tgz", + "integrity": "sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/node": { + "version": "20.19.33", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.33.tgz", + "integrity": "sha512-Rs1bVAIdBs5gbTIKza/tgpMuG1k3U/UMJLWecIMxNdJFDMzcM5LOiLVRYh3PilWEYDIeUDv7bpiHPLPsbydGcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/esbuild": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.2.tgz", + "integrity": "sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.24.2", + "@esbuild/android-arm": "0.24.2", + "@esbuild/android-arm64": "0.24.2", + "@esbuild/android-x64": "0.24.2", + "@esbuild/darwin-arm64": "0.24.2", + "@esbuild/darwin-x64": "0.24.2", + "@esbuild/freebsd-arm64": "0.24.2", + "@esbuild/freebsd-x64": "0.24.2", + "@esbuild/linux-arm": "0.24.2", + "@esbuild/linux-arm64": "0.24.2", + "@esbuild/linux-ia32": "0.24.2", + "@esbuild/linux-loong64": "0.24.2", + "@esbuild/linux-mips64el": "0.24.2", + "@esbuild/linux-ppc64": "0.24.2", + "@esbuild/linux-riscv64": "0.24.2", + "@esbuild/linux-s390x": "0.24.2", + "@esbuild/linux-x64": "0.24.2", + "@esbuild/netbsd-arm64": "0.24.2", + "@esbuild/netbsd-x64": "0.24.2", + "@esbuild/openbsd-arm64": "0.24.2", + "@esbuild/openbsd-x64": "0.24.2", + "@esbuild/sunos-x64": "0.24.2", + "@esbuild/win32-arm64": "0.24.2", + "@esbuild/win32-ia32": "0.24.2", + "@esbuild/win32-x64": "0.24.2" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/crates/bindings-typescript/case-conversion-test-client/package.json b/crates/bindings-typescript/case-conversion-test-client/package.json new file mode 100644 index 00000000000..de8b263bf0b --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/package.json @@ -0,0 +1,23 @@ +{ + "name": "case-conversion-test-client", + "version": "1.0.0", + "type": "module", + "scripts": { + "clean": "rm -rf dist", + "dev": "esbuild src/=index.ts --bundle --platform=node --outfile=dist/main.js --format=esm && node dist/main.js", + "start": "node dist/main.js", + "build": "esbuild src/index.ts --bundle --platform=node --outfile=dist/main.js --format=esm", + "spacetime:generate": "spacetime generate --lang typescript --out-dir src/module_bindings --module-path spacetimedb", + "spacetime:publish:local": "spacetime publish --module-path spacetimedb --server local", + "spacetime:publish": "spacetime publish --module-path spacetimedb --server maincloud", + "generate": "npm run spacetime:generate && prettier --write src/module_bindings" + }, + "dependencies": { + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "typescript": "^5.0.0", + "esbuild": "^0.24.0", + "@types/node": "^20.0.0" + } +} diff --git a/crates/bindings-typescript/case-conversion-test-client/src/index.ts b/crates/bindings-typescript/case-conversion-test-client/src/index.ts new file mode 100644 index 00000000000..8f7567e312f --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/index.ts @@ -0,0 +1,323 @@ +/** + * TypeScript SDK test client for case-conversion with Rust module `sdk-test-case-conversion`. + * + * Tests that: + * - Table accessor names with digits (`player1`, `person2`) work correctly + * - Field names with digit boundaries (`player1Id`, `currentLevel2`, `status3Field`) are converted + * - Nested struct fields (`personInfo.ageValue1`) work + * - Enum variants (`Player2Status`) work + * - Reducers with explicit names (`banPlayer1`) work + * - Query builder filters and joins work with case-converted names + * + * Driven by the Rust test harness via subcommands: + * node dist/index.js insert-player + * node dist/index.js insert-person + * node dist/index.js ban-player + * node dist/index.js query-builder-filter + * node dist/index.js query-builder-join + */ + +import { DbConnection, tables } from './module_bindings/index.js'; + +const LOCALHOST = 'http://localhost:3000'; + +function dbNameOrPanic(): string { + const name = process.env.SPACETIME_SDK_TEST_DB_NAME; + if (!name) { + throw new Error('Failed to read db name from env'); + } + return name; +} + +class TestError extends Error { + constructor(message: string) { + super(message); + this.name = 'TestError'; + } +} + +function assertEqual(expected: T, found: T, label: string): void { + const exp = JSON.stringify(expected); + const fnd = JSON.stringify(found); + if (exp !== fnd) { + throw new TestError(`${label}: expected ${exp} but found ${fnd}`); + } +} + +/** + * Connect to the database and run a callback once connected. + * Returns a promise that resolves when the callback completes. + */ +function connectThen(callback: (db: DbConnection) => void): Promise { + const name = dbNameOrPanic(); + return new Promise((resolve, reject) => { + const conn = DbConnection.builder() + .withDatabaseName(name) + .withUri(LOCALHOST) + .onConnect((ctx, _identity, _token) => { + try { + callback(ctx); + } catch (error) { + ctx.disconnect(); + reject(error); + } + }) + .onConnectError((_ctx, error) => { + reject(error); + }) + .build(); + + // Store resolve/reject so tests can call them when done + (conn as any).__resolve = resolve; + (conn as any).__reject = reject; + }); +} + +/** + * Test: Insert a player via createPlayer1 reducer. + * Verifies table accessor `player1`, field names with digit boundaries + * (`player1Id`, `currentLevel2`, `status3Field`), and enum variant `Active1`. + */ +async function execInsertPlayer(): Promise { + await connectThen(db => { + db.db.player1.onInsert((_ctx, row) => { + try { + assertEqual('Alice', row.playerName, 'playerName'); + assertEqual(5, row.currentLevel2, 'currentLevel2'); + assertEqual('Active1', row.status3Field.tag, 'status3Field tag'); + db.disconnect(); + (db as any).__resolve(); + } catch (error) { + db.disconnect(); + (db as any).__reject(error); + } + }); + + db.subscriptionBuilder() + .onError(_ctx => { + (db as any).__reject(new Error('Subscription errored')); + }) + .onApplied(_ctx => { + db.reducers.createPlayer1({ + player1Name: 'Alice', + start2Level: 5, + }); + }) + .subscribe([tables.player1]); + }); +} + +/** + * Test: Insert a person via addPerson2 reducer. + * Verifies nested struct `personInfo` with digit-boundary fields + * (`ageValue1`, `scoreTotal`), and table accessor `person2`. + */ +async function execInsertPerson(): Promise { + await connectThen(db => { + db.db.person2.onInsert((_ctx, person) => { + try { + assertEqual('Bob', person.firstName, 'firstName'); + assertEqual(25, person.personInfo.ageValue1, 'ageValue1'); + assertEqual(1000, person.personInfo.scoreTotal, 'scoreTotal'); + db.disconnect(); + (db as any).__resolve(); + } catch (error) { + db.disconnect(); + (db as any).__reject(error); + } + }); + + db.db.player1.onInsert((_ctx, player) => { + db.reducers.addPerson2({ + first3Name: 'Bob', + playerRef: player.player1Id, + ageValue: 25, + scoreTotal: 1000, + }); + }); + + db.subscriptionBuilder() + .onError(_ctx => { + (db as any).__reject(new Error('Subscription errored')); + }) + .onApplied(_ctx => { + db.reducers.createPlayer1({ + player1Name: 'PlayerForPerson', + start2Level: 1, + }); + }) + .subscribe([tables.player1, tables.person2]); + }); +} + +/** + * Test: Ban a player via banPlayer1 reducer (explicit name). + * Verifies that reducers with explicit names work, and that updating a player's + * status from `Active1` to `BannedUntil(9999)` is reflected correctly. + */ +async function execBanPlayer(): Promise { + await connectThen(db => { + db.db.player1.onUpdate((_ctx, _old, updated) => { + try { + assertEqual('BannedUntil', updated.status3Field.tag, 'status tag'); + assertEqual(9999, (updated.status3Field as any).value, 'ban value'); + db.disconnect(); + (db as any).__resolve(); + } catch (error) { + db.disconnect(); + (db as any).__reject(error); + } + }); + + db.db.player1.onInsert((_ctx, player) => { + db.reducers.banPlayer1({ + player1Id: player.player1Id, + banUntil6: 9999, + }); + }); + + db.subscriptionBuilder() + .onError(_ctx => { + (db as any).__reject(new Error('Subscription errored')); + }) + .onApplied(_ctx => { + db.reducers.createPlayer1({ + player1Name: 'ToBan', + start2Level: 1, + }); + }) + .subscribe(tables.player1); + }); +} + +/** + * Test: Query builder with a filter on a digit-boundary column. + * Subscribes to player1 rows WHERE currentLevel2 == 5. + */ +async function execQueryBuilderFilter(): Promise { + await connectThen(db => { + db.db.player1.onInsert((_ctx, row) => { + try { + assertEqual(5, row.currentLevel2, 'currentLevel2'); + assertEqual('FilterMatch', row.playerName, 'playerName'); + db.disconnect(); + (db as any).__resolve(); + } catch (error) { + db.disconnect(); + (db as any).__reject(error); + } + }); + + db.subscriptionBuilder() + .onError(_ctx => { + (db as any).__reject(new Error('Subscription errored')); + }) + .onApplied(_ctx => { + // Insert a player at level 3 (should NOT match filter) + db.reducers.createPlayer1({ + player1Name: 'NoMatch', + start2Level: 3, + }); + // Insert a player at level 5 (should match filter) + db.reducers.createPlayer1({ + player1Name: 'FilterMatch', + start2Level: 5, + }); + }) + .subscribe(tables.player1.where(p => p.currentLevel2.eq(5))); + }); +} + +/** + * Test: Query builder with a JOIN between player1 and person2. + * Uses a right semijoin: player1 RIGHT SEMIJOIN person2 ON player1Id = playerRef. + * Verifies digit-boundary column names work in join predicates and + * joined results are received correctly. + */ +async function execQueryBuilderJoin(): Promise { + await connectThen(db => { + db.db.person2.onInsert((_ctx, person) => { + if (person.firstName === 'JoinPerson') { + try { + assertEqual('JoinPerson', person.firstName, 'firstName'); + assertEqual(30, person.personInfo.ageValue1, 'ageValue1'); + assertEqual(500, person.personInfo.scoreTotal, 'scoreTotal'); + db.disconnect(); + (db as any).__resolve(); + } catch (error) { + db.disconnect(); + (db as any).__reject(error); + } + } + }); + + db.db.player1.onInsert((_ctx, player) => { + if (player.playerName === 'JoinedPlayer') { + db.reducers.addPerson2({ + first3Name: 'JoinPerson', + playerRef: player.player1Id, + ageValue: 30, + scoreTotal: 500, + }); + } + }); + + db.subscriptionBuilder() + .onError(_ctx => { + (db as any).__reject(new Error('Subscription errored')); + }) + .onApplied(_ctx => { + db.reducers.createPlayer1({ + player1Name: 'JoinedPlayer', + start2Level: 7, + }); + }) + .subscribe([ + tables.player1.rightSemijoin(tables.person2, (player, person) => + player.player1Id.eq(person.playerRef) + ), + tables.player1, + ]); + }); +} + +async function main(): Promise { + const testName = process.argv[2]; + if (!testName) { + throw new Error( + 'Pass a test name as a command-line argument to the test client' + ); + } + + try { + switch (testName) { + case 'insert-player': + await execInsertPlayer(); + break; + case 'insert-person': + await execInsertPerson(); + break; + case 'ban-player': + await execBanPlayer(); + break; + case 'query-builder-filter': + await execQueryBuilderFilter(); + break; + case 'query-builder-join': + await execQueryBuilderJoin(); + break; + default: + throw new Error(`Unknown test: ${testName}`); + } + console.log(`Test "${testName}" passed`); + process.exit(0); + } catch (error) { + console.error(`Test "${testName}" failed:`, error); + process.exit(1); + } +} + +main().catch(error => { + console.error('Fatal error:', error); + process.exit(1); +}); diff --git a/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/add_person_2_reducer.ts b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/add_person_2_reducer.ts new file mode 100644 index 00000000000..169150e9166 --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/add_person_2_reducer.ts @@ -0,0 +1,18 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default { + first3Name: __t.string(), + playerRef: __t.u32(), + ageValue: __t.u8(), + scoreTotal: __t.u32(), +}; diff --git a/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/ban_player_1_reducer.ts b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/ban_player_1_reducer.ts new file mode 100644 index 00000000000..e23dd65e152 --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/ban_player_1_reducer.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default { + player1Id: __t.u32(), + banUntil6: __t.u32(), +}; diff --git a/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/create_player_1_reducer.ts b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/create_player_1_reducer.ts new file mode 100644 index 00000000000..d37f8951553 --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/create_player_1_reducer.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default { + player1Name: __t.string(), + start2Level: __t.u32(), +}; diff --git a/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/index.ts b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/index.ts new file mode 100644 index 00000000000..9a36ed09b39 --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/index.ts @@ -0,0 +1,166 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +// This was generated using spacetimedb cli version 2.0.1 (commit 1a42a1fd48236f0d0c98a4316a0b172fb73158e2). + +/* eslint-disable */ +/* tslint:disable */ +import { + DbConnectionBuilder as __DbConnectionBuilder, + DbConnectionImpl as __DbConnectionImpl, + SubscriptionBuilderImpl as __SubscriptionBuilderImpl, + TypeBuilder as __TypeBuilder, + Uuid as __Uuid, + convertToAccessorMap as __convertToAccessorMap, + makeQueryBuilder as __makeQueryBuilder, + procedureSchema as __procedureSchema, + procedures as __procedures, + reducerSchema as __reducerSchema, + reducers as __reducers, + schema as __schema, + t as __t, + table as __table, + type AlgebraicTypeType as __AlgebraicTypeType, + type DbConnectionConfig as __DbConnectionConfig, + type ErrorContextInterface as __ErrorContextInterface, + type Event as __Event, + type EventContextInterface as __EventContextInterface, + type Infer as __Infer, + type QueryBuilder as __QueryBuilder, + type ReducerEventContextInterface as __ReducerEventContextInterface, + type RemoteModule as __RemoteModule, + type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, + type SubscriptionHandleImpl as __SubscriptionHandleImpl, +} from 'spacetimedb'; + +// Import all reducer arg schemas +import AddPerson2Reducer from './add_person_2_reducer'; +import BanPlayer1Reducer from './ban_player_1_reducer'; +import CreatePlayer1Reducer from './create_player_1_reducer'; + +// Import all procedure arg schemas + +// Import all table schema definitions +import Person2Row from './person_2_table'; +import PersonAtLevel2Row from './person_at_level_2_table'; +import Player1Row from './player_1_table'; + +/** Type-only namespace exports for generated type groups. */ + +/** The schema information for all tables in this module. This is defined the same was as the tables would have been defined in the server. */ +const tablesSchema = __schema({ + player1: __table( + { + name: 'Player1Canonical', + indexes: [ + { name: 'Player1Id', algorithm: 'btree', columns: ['player1Id'] }, + ], + constraints: [ + { + name: 'Player1Canonical_player_1_id_key', + constraint: 'unique', + columns: ['player1Id'], + }, + ], + }, + Player1Row + ), + person2: __table( + { + name: 'person_2', + indexes: [ + { name: 'Person2Id', algorithm: 'btree', columns: ['person2Id'] }, + { name: 'playerRef', algorithm: 'btree', columns: ['playerRef'] }, + ], + constraints: [ + { + name: 'person_2_person_2_id_key', + constraint: 'unique', + columns: ['person2Id'], + }, + ], + }, + Person2Row + ), + person_at_level_2: __table( + { + name: 'Level2Person', + indexes: [], + constraints: [], + }, + PersonAtLevel2Row + ), +}); + +/** The schema information for all reducers in this module. This is defined the same way as the reducers would have been defined in the server, except the body of the reducer is omitted in code generation. */ +const reducersSchema = __reducers( + __reducerSchema('add_person_2', AddPerson2Reducer), + __reducerSchema('banPlayer1', BanPlayer1Reducer), + __reducerSchema('create_player_1', CreatePlayer1Reducer) +); + +/** The schema information for all procedures in this module. This is defined the same way as the procedures would have been defined in the server. */ +const proceduresSchema = __procedures(); + +/** The remote SpacetimeDB module schema, both runtime and type information. */ +const REMOTE_MODULE = { + versionInfo: { + cliVersion: '2.0.1' as const, + }, + tables: tablesSchema.schemaType.tables, + reducers: reducersSchema.reducersType.reducers, + ...proceduresSchema, +} satisfies __RemoteModule< + typeof tablesSchema.schemaType, + typeof reducersSchema.reducersType, + typeof proceduresSchema +>; + +/** The tables available in this remote SpacetimeDB module. Each table reference doubles as a query builder. */ +export const tables: __QueryBuilder = + __makeQueryBuilder(tablesSchema.schemaType); + +/** The reducers available in this remote SpacetimeDB module. */ +export const reducers = __convertToAccessorMap( + reducersSchema.reducersType.reducers +); + +/** The context type returned in callbacks for all possible events. */ +export type EventContext = __EventContextInterface; +/** The context type returned in callbacks for reducer events. */ +export type ReducerEventContext = __ReducerEventContextInterface< + typeof REMOTE_MODULE +>; +/** The context type returned in callbacks for subscription events. */ +export type SubscriptionEventContext = __SubscriptionEventContextInterface< + typeof REMOTE_MODULE +>; +/** The context type returned in callbacks for error events. */ +export type ErrorContext = __ErrorContextInterface; +/** The subscription handle type to manage active subscriptions created from a {@link SubscriptionBuilder}. */ +export type SubscriptionHandle = __SubscriptionHandleImpl; + +/** Builder class to configure a new subscription to the remote SpacetimeDB instance. */ +export class SubscriptionBuilder extends __SubscriptionBuilderImpl< + typeof REMOTE_MODULE +> {} + +/** Builder class to configure a new database connection to the remote SpacetimeDB instance. */ +export class DbConnectionBuilder extends __DbConnectionBuilder {} + +/** The typed database connection to manage connections to the remote SpacetimeDB instance. This class has type information specific to the generated module. */ +export class DbConnection extends __DbConnectionImpl { + /** Creates a new {@link DbConnectionBuilder} to configure and connect to the remote SpacetimeDB instance. */ + static builder = (): DbConnectionBuilder => { + return new DbConnectionBuilder( + REMOTE_MODULE, + (config: __DbConnectionConfig) => + new DbConnection(config) + ); + }; + + /** Creates a new {@link SubscriptionBuilder} to configure a subscription to the remote SpacetimeDB instance. */ + override subscriptionBuilder = (): SubscriptionBuilder => { + return new SubscriptionBuilder(this); + }; +} diff --git a/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/person_2_table.ts b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/person_2_table.ts new file mode 100644 index 00000000000..9359fb15439 --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/person_2_table.ts @@ -0,0 +1,21 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; +import { Person3Info } from './types'; + +export default __t.row({ + person2Id: __t.u32().primaryKey().name('person_2_id'), + firstName: __t.string().name('first_name'), + playerRef: __t.u32().name('player_ref'), + get personInfo() { + return Person3Info.name('person_info'); + }, +}); diff --git a/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/person_at_level_2_table.ts b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/person_at_level_2_table.ts new file mode 100644 index 00000000000..7f05195c78d --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/person_at_level_2_table.ts @@ -0,0 +1,21 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; +import { Person3Info } from './types'; + +export default __t.row({ + person2Id: __t.u32().name('person_2_id'), + firstName: __t.string().name('first_name'), + playerRef: __t.u32().name('player_ref'), + get personInfo() { + return Person3Info.name('person_info'); + }, +}); diff --git a/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/player_1_table.ts b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/player_1_table.ts new file mode 100644 index 00000000000..fba1e5f12f3 --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/player_1_table.ts @@ -0,0 +1,21 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; +import { Player2Status } from './types'; + +export default __t.row({ + player1Id: __t.u32().primaryKey().name('player_1_id'), + playerName: __t.string().name('player_name'), + currentLevel2: __t.u32().name('current_level_2'), + get status3Field() { + return Player2Status.name('status_3_field'); + }, +}); diff --git a/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/types.ts b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/types.ts new file mode 100644 index 00000000000..d5d9c78378f --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/types.ts @@ -0,0 +1,44 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export const Person2 = __t.object('Person2', { + person2Id: __t.u32(), + firstName: __t.string(), + playerRef: __t.u32(), + get personInfo() { + return Person3Info; + }, +}); +export type Person2 = __Infer; + +export const Person3Info = __t.object('Person3Info', { + ageValue1: __t.u8(), + scoreTotal: __t.u32(), +}); +export type Person3Info = __Infer; + +export const Player1 = __t.object('Player1', { + player1Id: __t.u32(), + playerName: __t.string(), + currentLevel2: __t.u32(), + get status3Field() { + return Player2Status; + }, +}); +export type Player1 = __Infer; + +// The tagged union or sum type for the algebraic type `Player2Status`. +export const Player2Status = __t.enum('Player2Status', { + Active1: __t.unit(), + BannedUntil: __t.u32(), +}); +export type Player2Status = __Infer; diff --git a/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/types/procedures.ts b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/types/procedures.ts new file mode 100644 index 00000000000..b2102264f4d --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/types/procedures.ts @@ -0,0 +1,8 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from 'spacetimedb'; + +// Import all procedure arg schemas diff --git a/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/types/reducers.ts b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/types/reducers.ts new file mode 100644 index 00000000000..31fdb551705 --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/src/module_bindings/types/reducers.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from 'spacetimedb'; + +// Import all reducer arg schemas +import AddPerson2Reducer from '../add_person_2_reducer'; +import BanPlayer1Reducer from '../ban_player_1_reducer'; +import CreatePlayer1Reducer from '../create_player_1_reducer'; + +export type AddPerson2Params = __Infer; +export type BanPlayer1Params = __Infer; +export type CreatePlayer1Params = __Infer; diff --git a/crates/bindings-typescript/case-conversion-test-client/tsconfig.json b/crates/bindings-typescript/case-conversion-test-client/tsconfig.json new file mode 100644 index 00000000000..008f0c53296 --- /dev/null +++ b/crates/bindings-typescript/case-conversion-test-client/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "moduleResolution": "bundler", + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "allowSyntheticDefaultImports": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/crates/bindings-typescript/src/lib/schema.ts b/crates/bindings-typescript/src/lib/schema.ts index 22ff25256d0..fed510ba74f 100644 --- a/crates/bindings-typescript/src/lib/schema.ts +++ b/crates/bindings-typescript/src/lib/schema.ts @@ -91,7 +91,10 @@ export function tableToSchema< type AllowedCol = keyof T['rowType']['row'] & string; return { - sourceName: accName, + // For client,`schama.tableName` will always be there as canonical name. + // For module, if explicit name is not provided via `name`, accessor name will + // be used, it is stored as alias in database, hence works in query builder. + sourceName: schema.tableName || accName, accessorName: accName, columns: schema.rowType.row, // typed as T[i]['rowType']['row'] under TablesToSchema rowType: schema.rowSpacetimeType, diff --git a/crates/codegen/src/rust.rs b/crates/codegen/src/rust.rs index ea28bbc5ccf..bd7a2e147ec 100644 --- a/crates/codegen/src/rust.rs +++ b/crates/codegen/src/rust.rs @@ -671,7 +671,7 @@ pub struct {cols_struct} {{" )?; for element in &product_def.elements { - let field_name = &element.0; + let field_name = &element.0.deref().to_case(Case::Snake); let field_type = type_name(module, &element.1); writeln!( out, @@ -690,7 +690,7 @@ impl __sdk::__query_builder::HasCols for {struct_name} {{ {cols_struct} {{" )?; for element in &product_def.elements { - let field_name = &element.0; + let field_name = &element.0.deref().to_case(Case::Snake); writeln!( out, " {field_name}: __sdk::__query_builder::Col::new(table_name, {field_name:?})," diff --git a/crates/schema/tests/ensure_same_schema.rs b/crates/schema/tests/ensure_same_schema.rs index e6bba12a64f..5ece131360f 100644 --- a/crates/schema/tests/ensure_same_schema.rs +++ b/crates/schema/tests/ensure_same_schema.rs @@ -91,3 +91,9 @@ declare_tests! { fn ensure_same_schema_rust_csharp_benchmarks() { assert_identical_modules("benchmarks", "C#", "cs"); } + +#[test] +#[serial] +fn esure_same_schema_case_conversion() { + assert_identical_modules("sdk-test-case-conversion", "", "ts"); +} diff --git a/modules/sdk-test-case-conversion-ts/package.json b/modules/sdk-test-case-conversion-ts/package.json new file mode 100644 index 00000000000..326c97ec7fc --- /dev/null +++ b/modules/sdk-test-case-conversion-ts/package.json @@ -0,0 +1,17 @@ +{ + "name": "sdk-test-case-conversion-ts", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "build": "cargo build -p spacetimedb-standalone && cargo run -p spacetimedb-cli -- build", + "generate-ts": "cargo build -p spacetimedb-standalone && cargo run -p spacetimedb-cli -- generate --lang typescript --out-dir ts-codegen", + "publish": "cargo run -p spacetimedb-cli -- publish" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "spacetimedb": "workspace:^" + } +} diff --git a/modules/sdk-test-case-conversion-ts/src/index.ts b/modules/sdk-test-case-conversion-ts/src/index.ts new file mode 100644 index 00000000000..7089643b020 --- /dev/null +++ b/modules/sdk-test-case-conversion-ts/src/index.ts @@ -0,0 +1,88 @@ + +import { schema, t, table } from 'spacetimedb/server'; + +const Player2Status = t.enum('Player2Status', { + Active1: t.unit(), + BannedUntil: t.u32(), +}); + +const Person3Info = t.object('Person3Info', { + AgeValue1: t.u8(), + ScoreTotal: t.u32(), +}); + + +const PlayerRow = t.row('PlayerRow', { + Player1Id: t.u32().primaryKey().autoInc(), + player_name: t.string(), + currentLevel2: t.u32(), + status3Field: Player2Status, +}) + +const PersonRow = t.row({ + Person2Id: t.u32().primaryKey().autoInc(), + FirstName: t.string(), + playerRef: t.u32().index(), + personInfo: Person3Info, +}) + +const Player1 = table( + { name: 'Player1Canonical', public: true }, + PlayerRow +); + +const Person2 = table( + { public: true }, + PersonRow +); + +const spacetimedb = schema({ Player1, Person2 }); +export default spacetimedb; + +export const CreatePlayer1 = spacetimedb.reducer( + { Player1Name: t.string(), Start2Level: t.u32() }, + (ctx, { Player1Name, Start2Level }) => { + ctx.db.Player1.insert({ + Player1Id: 0, + player_name: Player1Name, + currentLevel2: Start2Level, + status3Field: { tag: 'Active1' }, + }); + } +); + +export const AddPerson2 = spacetimedb.reducer( + { First3Name: t.string(), playerRef: t.u32(), AgeValue: t.u8(), ScoreTotal: t.u32() }, + (ctx, { First3Name, playerRef, AgeValue, ScoreTotal }) => { + ctx.db.Person2.insert({ + Person2Id: 0, + FirstName: First3Name, + playerRef, + personInfo: { AgeValue1: AgeValue, ScoreTotal }, + }); + } +); + +export const BanPlayer1 = spacetimedb.reducer( + { name: "banPlayer1" }, + { Player1Id: t.u32(), BanUntil6: t.u32() }, + (ctx, { Player1Id, BanUntil6 }) => { + const player = ctx.db.Player1.Player1Id.find(Player1Id); + if (player) { + ctx.db.Player1.Player1Id.update({ + ...player, + status3Field: { tag: 'BannedUntil', value: BanUntil6 }, + }); + } + } +); + + +export const PersonAtLevel2 = spacetimedb.view( + { name: "Level2Person", public: true }, + t.array(Person2.rowType), + (ctx) => { + const person = ctx.from.Player1.where((p) => p.currentLevel2.eq(2)).rightSemijoin(ctx.from.Person2, (player, person) => player.Player1Id.eq(person.playerRef)); + return person + } +); diff --git a/modules/sdk-test-case-conversion-ts/tsconfig.json b/modules/sdk-test-case-conversion-ts/tsconfig.json new file mode 100644 index 00000000000..6283107337e --- /dev/null +++ b/modules/sdk-test-case-conversion-ts/tsconfig.json @@ -0,0 +1,24 @@ + +/* + * This tsconfig is used for TypeScript projects created with `spacetimedb init + * --lang typescript`. You can modify it as needed for your project, although + * some options are required by SpacetimeDB. + */ +{ + "compilerOptions": { + "strict": true, + "skipLibCheck": true, + "moduleResolution": "bundler", + "jsx": "react-jsx", + + /* The following options are required by SpacetimeDB + * and should not be modified + */ + "target": "ESNext", + "lib": ["ES2021", "dom"], + "module": "ESNext", + "isolatedModules": true, + "noEmit": true + }, + "include": ["./**/*"] +} diff --git a/modules/sdk-test-case-conversion/Cargo.toml b/modules/sdk-test-case-conversion/Cargo.toml new file mode 100644 index 00000000000..c65a6d832d6 --- /dev/null +++ b/modules/sdk-test-case-conversion/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "sdk-test-case-conversion" +version = "0.1.0" +edition.workspace = true +license-file = "LICENSE" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +log.workspace = true + +[dependencies.spacetimedb] +workspace = true +features = ["unstable"] diff --git a/modules/sdk-test-case-conversion/src/lib.rs b/modules/sdk-test-case-conversion/src/lib.rs new file mode 100644 index 00000000000..9ab19421df5 --- /dev/null +++ b/modules/sdk-test-case-conversion/src/lib.rs @@ -0,0 +1,77 @@ +#![allow(non_snake_case, non_camel_case_types)] + +use spacetimedb::{reducer, table, view, AnonymousViewContext, Query, ReducerContext, SpacetimeType, Table}; + +#[derive(Clone, PartialEq, Eq, Hash, SpacetimeType)] +pub enum Player2Status { + Active1, + BannedUntil(u32), +} + +#[derive(Clone, SpacetimeType)] +pub struct Person3Info { + pub AgeValue1: u8, + pub ScoreTotal: u32, +} + +#[table(name = "Player1Canonical", accessor = player1, public)] +pub struct Player1 { + #[primary_key] + #[auto_inc] + pub Player1Id: u32, + pub player_name: String, + pub currentLevel2: u32, + pub status3Field: Player2Status, +} + +#[table(accessor = person2, public)] +pub struct Person2 { + #[primary_key] + #[auto_inc] + pub Person2Id: u32, + pub FirstName: String, + #[index(btree)] + pub playerRef: u32, + pub personInfo: Person3Info, +} + +#[reducer] +pub fn CreatePlayer1(ctx: &ReducerContext, Player1Name: String, Start2Level: u32) { + ctx.db.player1().insert(Player1 { + Player1Id: 0, + player_name: Player1Name, + currentLevel2: Start2Level, + status3Field: Player2Status::Active1, + }); +} + +#[reducer] +pub fn AddPerson2(ctx: &ReducerContext, First3Name: String, playerRef: u32, AgeValue: u8, ScoreTotal: u32) { + ctx.db.person2().insert(Person2 { + Person2Id: 0, + FirstName: First3Name, + playerRef, + personInfo: Person3Info { + AgeValue1: AgeValue, + ScoreTotal, + }, + }); +} + +#[reducer(name = "banPlayer1")] +pub fn BanPlayer1(ctx: &ReducerContext, Player1Id: u32, BanUntil6: u32) { + if let Some(player) = ctx.db.player1().Player1Id().find(Player1Id) { + ctx.db.player1().Player1Id().update(Player1 { + status3Field: Player2Status::BannedUntil(BanUntil6), + ..player + }); + } +} + +#[view(name = "Level2Person", accessor = person_at_level_2, public)] +pub fn level2_person(ctx: &AnonymousViewContext) -> impl Query { + ctx.from + .player1() + .r#where(|pl| pl.currentLevel2.eq(2)) + .right_semijoin(ctx.from.person2(), |pl, per| pl.Player1Id.eq(per.playerRef)) +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6fc62ac21a7..1aba4c46c69 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -270,6 +270,12 @@ importers: specifier: workspace:^ version: link:../../crates/bindings-typescript + modules/sdk-test-case-conversion-ts: + dependencies: + spacetimedb: + specifier: workspace:^ + version: link:../../crates/bindings-typescript + modules/sdk-test-connect-disconnect-ts: dependencies: spacetimedb: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 68ba113176a..16900ae8a39 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,6 +1,7 @@ packages: - 'crates/bindings-typescript' - 'crates/bindings-typescript/test-app' + - 'crates/bindings-typescript/case-conversion-test-client' - 'templates/chat-react-ts' - 'templates/react-ts' - 'templates/basic-ts' @@ -19,4 +20,5 @@ packages: - 'modules/sdk-test-connect-disconnect-ts' - 'modules/sdk-test-procedure-ts' - 'modules/sdk-test-ts' + - 'modules/sdk-test-case-conversion-ts' - 'docs' diff --git a/sdks/rust/tests/case-conversion-client/Cargo.toml b/sdks/rust/tests/case-conversion-client/Cargo.toml new file mode 100644 index 00000000000..e8ab09daea0 --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "case-conversion-client" +version.workspace = true +edition.workspace = true +license-file = "LICENSE" + +[dependencies] +spacetimedb-sdk = { path = "../.." } +test-counter = { path = "../test-counter" } +anyhow.workspace = true +env_logger.workspace = true + +[lints] +workspace = true diff --git a/sdks/rust/tests/case-conversion-client/LICENSE b/sdks/rust/tests/case-conversion-client/LICENSE new file mode 100644 index 00000000000..c92cc374645 --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/LICENSE @@ -0,0 +1,731 @@ +SPACETIMEDB BUSINESS SOURCE LICENSE AGREEMENT + +Business Source License 1.1 + +Parameters + +Licensor: Clockwork Laboratories, Inc. +Licensed Work: SpacetimeDB 2.0.0 + The Licensed Work is + (c) 2023 Clockwork Laboratories, Inc. + +Additional Use Grant: You may make use of the Licensed Work provided your + application or service uses the Licensed Work with no + more than one SpacetimeDB instance in production and + provided that you do not use the Licensed Work for a + Database Service. + + A “Database Service” is a commercial offering that + allows third parties (other than your employees and + contractors) to access the functionality of the + Licensed Work by creating tables whose schemas are + controlled by such third parties. + +Change Date: 2031-02-10 + +Change License: GNU Affero General Public License v3.0 with a linking + exception + +For information about alternative licensing arrangements for the Software, +please visit: https://spacetimedb.com + +Notice + +The Business Source License (this document, or the “License”) is not an Open +Source license. However, the Licensed Work will eventually be made available +under an Open Source License, as stated in this License. + +License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. +“Business Source License” is a trademark of MariaDB Corporation Ab. + +----------------------------------------------------------------------------- + +Business Source License 1.1 + +Terms + +The Licensor hereby grants you the right to copy, modify, create derivative +works, redistribute, and make non-production use of the Licensed Work. The +Licensor may make an Additional Use Grant, above, permitting limited +production use. + +Effective on the Change Date, or the fourth anniversary of the first publicly +available distribution of a specific version of the Licensed Work under this +License, whichever comes first, the Licensor hereby grants you rights under +the terms of the Change License, and the rights granted in the paragraph +above terminate. + +If your use of the Licensed Work does not comply with the requirements +currently in effect as described in this License, you must purchase a +commercial license from the Licensor, its affiliated entities, or authorized +resellers, or you must refrain from using the Licensed Work. + +All copies of the original and modified Licensed Work, and derivative works +of the Licensed Work, are subject to this License. This License applies +separately for each version of the Licensed Work and the Change Date may vary +for each version of the Licensed Work released by Licensor. + +You must conspicuously display this License on each original or modified copy +of the Licensed Work. If you receive the Licensed Work in original or +modified form from a third party, the terms and conditions set forth in this +License apply to your use of that work. + +Any use of the Licensed Work in violation of this License will automatically +terminate your rights under this License for the current and all other +versions of the Licensed Work. + +This License does not grant you any right in any trademark or logo of +Licensor or its affiliates (provided that you may use a trademark or logo of +Licensor as expressly required by this License). + +TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON +AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, +EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND +TITLE. + +MariaDB hereby grants you permission to use this License’s text to license +your works, and to refer to it using the trademark “Business Source License”, +as long as you comply with the Covenants of Licensor below. + +Covenants of Licensor + +In consideration of the right to use this License’s text and the “Business +Source License” name and trademark, Licensor covenants to MariaDB, and to all +other recipients of the licensed work to be provided by Licensor: + +1. To specify as the Change License the GPL Version 2.0 or any later version, + or a license that is compatible with GPL Version 2.0 or a later version, + where “compatible” means that software provided under the Change License can + be included in a program with software provided under GPL Version 2.0 or a + later version. Licensor may specify additional Change Licenses without + limitation. + +2. To either: (a) specify an additional grant of rights to use that does not + impose any additional restriction on the right granted in this License, as + the Additional Use Grant; or (b) insert the text “None”. + +3. To specify a Change Date. + +4. Not to modify this License in any other way. + +----------------------------------------------------------------------------- + +Copyright (C) 2023 Clockwork Laboratories, Inc. + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU Affero General Public License, version 3, as published +by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License +along with this program; if not, see . + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with SpacetimeDB (or a modified version of that library), containing parts +covered by the terms of the AGPL v3.0, the licensors of this Program grant +you additional permission to convey the resulting work. + +Additional permission under GNU AGPL version 3 section 13 + +If you modify this Program, or any covered work, by linking or combining it +with SpacetimeDB (or a modified version of that library), containing parts +covered by the terms of the AGPL v3.0, the licensors of this Program grant +you additional permission that, notwithstanding any other provision of this +License, you need not prominently offer all users interacting with your +modified version remotely through a computer network an opportunity to +receive the Corresponding Source of your version from a network server at no +charge, if your version supports such interaction. This permission does not +waive or modify any other obligations or terms of the AGPL v3.0, except for +the specific requirement set forth in section 13. + +A copy of the AGPL v3.0 license is reproduced below. + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + +Copyright © 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, our General +Public Licenses are intended to guarantee your freedom to share and change +all versions of a program--to make sure it remains free software for all its +users. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom +to distribute copies of free software (and charge for them if you wish), that +you receive source code or can get it if you want it, that you can change the +software or use pieces of it in new free programs, and that you know you can +do these things. + +Developers that use our General Public Licenses protect your rights with two +steps: (1) assert copyright on the software, and (2) offer you this License +which gives you legal permission to copy, distribute and/or modify the +software. + +A secondary benefit of defending all users' freedom is that improvements made +in alternate versions of the program, if they receive widespread use, become +available for other developers to incorporate. Many developers of free +software are heartened and encouraged by the resulting cooperation. However, +in the case of software used on network servers, this result may fail to come +about. The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its source +code to the public. + +The GNU Affero General Public License is designed specifically to ensure +that, in such cases, the modified source code becomes available to the +community. It requires the operator of a network server to provide the source +code of the modified version running there to the users of that server. +Therefore, public use of a modified version, on a publicly accessible server, +gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by +Affero, was designed to accomplish similar goals. This is a different +license, not a version of the Affero GPL, but Affero has released a new +version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS +0. Definitions. +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. +Each licensee is addressed as "you". "Licensees" and "recipients" may be +individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a +fashion requiring copyright permission, other than the making of an exact +copy. The resulting work is called a "modified version" of the earlier work +or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the +Program. + +To "propagate" a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under +applicable copyright law, except executing it on a computer or modifying a +private copy. Propagation includes copying, distribution (with or without +modification), making available to the public, and in some countries other +activities as well. + +To "convey" a work means any kind of propagation that enables other parties +to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the +extent that it includes a convenient and prominently visible feature that (1) +displays an appropriate copyright notice, and (2) tells the user that there +is no warranty for the work (except to the extent that warranties are +provided), that licensees may convey the work under this License, and how to +view a copy of this License. If the interface presents a list of user +commands or options, such as a menu, a prominent item in the list meets this +criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making +modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces +specified for a particular programming language, one that is widely used +among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the +work as a whole, that (a) is included in the normal form of packaging a Major +Component, but which is not part of that Major Component, and (b) serves only +to enable use of the work with that Major Component, or to implement a +Standard Interface for which an implementation is available to the public in +source code form. A "Major Component", in this context, means a major +essential component (kernel, window system, and so on) of the specific +operating system (if any) on which the executable work runs, or a compiler +used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the +source code needed to generate, install, and (for an executable work) run the +object code and to modify the work, including scripts to control those +activities. However, it does not include the work's System Libraries, or +general-purpose tools or generally available free programs which are used +unmodified in performing those activities but which are not part of the work. +For example, Corresponding Source includes interface definition files +associated with source files for the work, and the source code for shared +libraries and dynamically linked subprograms that the work is specifically +designed to require, such as by intimate data communication or control flow +between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright +on the Program, and are irrevocable provided the stated conditions are met. +This License explicitly affirms your unlimited permission to run the +unmodified Program. The output from running a covered work is covered by this +License only if the output, given its content, constitutes a covered work. +This License acknowledges your rights of fair use or other equivalent, as +provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make +modifications exclusively for you, or provide you with facilities for running +those works, provided that you comply with the terms of this License in +conveying all material for which you do not control copyright. Those thus +making or running the covered works for you must do so exclusively on your +behalf, under your direction and control, on terms that prohibit them from +making any copies of your copyrighted material outside their relationship +with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes it +unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting or +restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention is +effected by exercising rights under this License with respect to the covered +work, and you disclaim any intention to limit operation or modification of +the work as a means of enforcing, against the work's users, your or third +parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive +it, in any medium, provided that you conspicuously and appropriately publish +on each copy an appropriate copyright notice; keep intact all notices stating +that this License and any non-permissive terms added in accord with section 7 +apply to the code; keep intact all notices of the absence of any warranty; +and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you +may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce +it from the Program, in the form of source code under the terms of section 4, +provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and +giving a relevant date. +b) The work must carry prominent notices stating that it is released under +this License and any conditions added under section 7. This requirement +modifies the requirement in section 4 to "keep intact all notices". +c) You must license the entire work, as a whole, under this License to anyone +who comes into possession of a copy. This License will therefore apply, along +with any applicable section 7 additional terms, to the whole of the work, and +all its parts, regardless of how they are packaged. This License gives no +permission to license the work in any other way, but it does not invalidate +such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate +Legal Notices; however, if the Program has interactive interfaces that do not +display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are +not combined with it such as to form a larger program, in or on a volume of a +storage or distribution medium, is called an "aggregate" if the compilation +and its resulting copyright are not used to limit the access or legal rights +of the compilation's users beyond what the individual works permit. Inclusion +of a covered work in an aggregate does not cause this License to apply to the +other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections +4 and 5, provided that you also convey the machine-readable Corresponding +Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by the Corresponding Source fixed +on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by a written offer, valid for at +least three years and valid for as long as you offer spare parts or customer +support for that product model, to give anyone who possesses the object code +either (1) a copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical medium +customarily used for software interchange, for a price no more than your +reasonable cost of physically performing this conveying of source, or (2) +access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written +offer to provide the Corresponding Source. This alternative is allowed only +occasionally and noncommercially, and only if you received the object code +with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis +or for a charge), and offer equivalent access to the Corresponding Source in +the same way through the same place at no further charge. You need not +require recipients to copy the Corresponding Source along with the object +code. If the place to copy the object code is a network server, the +Corresponding Source may be on a different server (operated by you or a third +party) that supports equivalent copying facilities, provided you maintain +clear directions next to the object code saying where to find the +Corresponding Source. Regardless of what server hosts the Corresponding +Source, you remain obligated to ensure that it is available for as long as +needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you +inform other peers where the object code and Corresponding Source of the work +are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from +the Corresponding Source as a System Library, need not be included in +conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible +personal property which is normally used for personal, family, or household +purposes, or (2) anything designed or sold for incorporation into a dwelling. +In determining whether a product is a consumer product, doubtful cases shall +be resolved in favor of coverage. For a particular product received by a +particular user, "normally used" refers to a typical or common use of that +class of product, regardless of the status of the particular user or of the +way in which the particular user actually uses, or expects or is expected to +use, the product. A product is a consumer product regardless of whether the +product has substantial commercial, industrial or non-consumer uses, unless +such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute +modified versions of a covered work in that User Product from a modified +version of its Corresponding Source. The information must suffice to ensure +that the continued functioning of the modified object code is in no case +prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as part of +a transaction in which the right of possession and use of the User Product is +transferred to the recipient in perpetuity or for a fixed term (regardless of +how the transaction is characterized), the Corresponding Source conveyed +under this section must be accompanied by the Installation Information. But +this requirement does not apply if neither you nor any third party retains +the ability to install modified object code on the User Product (for example, +the work has been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates for +a work that has been modified or installed by the recipient, or for the User +Product in which it has been modified or installed. Access to a network may +be denied when the modification itself materially and adversely affects the +operation of the network or violates the rules and protocols for +communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in +accord with this section must be in a format that is publicly documented (and +with an implementation available to the public in source code form), and must +require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License +by making exceptions from one or more of its conditions. Additional +permissions that are applicable to the entire Program shall be treated as +though they were included in this License, to the extent that they are valid +under applicable law. If additional permissions apply only to part of the +Program, that part may be used separately under those permissions, but the +entire Program remains governed by this License without regard to the +additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate +copyright permission. + +Notwithstanding any other provision of this License, for material you add to +a covered work, you may (if authorized by the copyright holders of that +material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of +sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices displayed +by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring +that modified versions of such material be marked in reasonable ways as +different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors +of the material; or +e) Declining to grant rights under trademark law for use of some trade names, +trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by +anyone who conveys the material (or modified versions of it) with contractual +assumptions of liability to the recipient, for any liability that these +contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is governed +by this License along with a term that is a further restriction, you may +remove that term. If a license document contains a further restriction but +permits relicensing or conveying under this License, you may add to a covered +work material governed by the terms of that license document, provided that +the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must +place, in the relevant source files, a statement of the additional terms that +apply to those files, or a notice indicating where to find the applicable +terms. + +Additional terms, permissive or non-permissive, may be stated in the form of +a separately written license, or stated as exceptions; the above requirements +apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including +any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a +particular copyright holder is reinstated (a) provisionally, unless and until +the copyright holder explicitly and finally terminates your license, and (b) +permanently, if the copyright holder fails to notify you of the violation by +some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated +permanently if the copyright holder notifies you of the violation by some +reasonable means, this is the first time you have received notice of +violation of this License (for any work) from that copyright holder, and you +cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. If +your rights have been terminated and not permanently reinstated, you do not +qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as a +consequence of using peer-to-peer transmission to receive a copy likewise +does not require acceptance. However, nothing other than this License grants +you permission to propagate or modify any covered work. These actions +infringe copyright if you do not accept this License. Therefore, by modifying +or propagating a covered work, you indicate your acceptance of this License +to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a +license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance by +third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered work +results from an entity transaction, each party to that transaction who +receives a copy of the work also receives whatever licenses to the work the +party's predecessor in interest had or could give under the previous +paragraph, plus a right to possession of the Corresponding Source of the work +from the predecessor in interest, if the predecessor has it or can get it +with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under +this License, and you may not initiate litigation (including a cross-claim or +counterclaim in a lawsuit) alleging that any patent claim is infringed by +making, using, selling, offering for sale, or importing the Program or any +portion of it. + +11. Patents. +A "contributor" is a copyright holder who authorizes use under this License +of the Program or a work on which the Program is based. The work thus +licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or +controlled by the contributor, whether already acquired or hereafter +acquired, that would be infringed by some manner, permitted by this License, +of making, using, or selling its contributor version, but do not include +claims that would be infringed only as a consequence of further modification +of the contributor version. For purposes of this definition, "control" +includes the right to grant patent sublicenses in a manner consistent with +the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents +of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent (such +as an express permission to practice a patent or covenant not to sue for +patent infringement). To "grant" such a patent license to a party means to +make such an agreement or commitment not to enforce a patent against the +party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free of +charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either (1) +cause the Corresponding Source to be so available, or (2) arrange to deprive +yourself of the benefit of the patent license for this particular work, or +(3) arrange, in a manner consistent with the requirements of this License, to +extend the patent license to downstream recipients. "Knowingly relying" means +you have actual knowledge that, but for the patent license, your conveying +the covered work in a country, or your recipient's use of the covered work in +a country, would infringe one or more identifiable patents in that country +that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, +you convey, or propagate by procuring conveyance of, a covered work, and +grant a patent license to some of the parties receiving the covered work +authorizing them to use, propagate, modify or convey a specific copy of the +covered work, then the patent license you grant is automatically extended to +all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope +of its coverage, prohibits the exercise of, or is conditioned on the +non-exercise of one or more of the rights that are specifically granted under +this License. You may not convey a covered work if you are a party to an +arrangement with a third party that is in the business of distributing +software, under which you make payment to the third party based on the extent +of your activity of conveying the work, and under which the third party +grants, to any of the parties who would receive the covered work from you, a +discriminatory patent license (a) in connection with copies of the covered +work conveyed by you (or copies made from those copies), or (b) primarily for +and in connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any +implied license or other defenses to infringement that may otherwise be +available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not excuse +you from the conditions of this License. If you cannot convey a covered work +so as to satisfy simultaneously your obligations under this License and any +other pertinent obligations, then as a consequence you may not convey it at +all. For example, if you agree to terms that obligate you to collect a +royalty for further conveying from those to whom you convey the Program, the +only way you could satisfy both those terms and this License would be to +refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users interacting +with it remotely through a computer network (if your version supports such +interaction) an opportunity to receive the Corresponding Source of your +version by providing access to the Corresponding Source from a network server +at no charge, through some standard or customary means of facilitating +copying of software. This Corresponding Source shall include the +Corresponding Source for any work covered by version 3 of the GNU General +Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU General Public License into a single combined work, and to convey the +resulting work. The terms of this License will continue to apply to the part +which is the covered work, but the work with which it is combined will remain +governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the +GNU Affero General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU Affero General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or of any +later version published by the Free Software Foundation. If the Program does +not specify a version number of the GNU Affero General Public License, you +may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the +GNU Affero General Public License can be used, that proxy's public statement +of acceptance of a version permanently authorizes you to choose that version +for the Program. + +Later license versions may give you additional or different permissions. +However, no additional obligations are imposed on any author or copyright +holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE +LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, +EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. +SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY +SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE +PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE +OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR +DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR +A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH +HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above +cannot be given local legal effect according to their terms, reviewing courts +shall apply local law that most closely approximates an absolute waiver of +all civil liability in connection with the Program, unless a warranty or +assumption of liability accompanies a copy of the Program in return for a +fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively state the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + +SpacetimeDB: A database which replaces your server. +Copyright (C) 2023 Clockwork Laboratories, Inc. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, +you should also make sure that it provides a way for users to get its source. +For example, if your program is a web application, its interface could +display a "Source" link that leads users to an archive of the code. There are +many ways you could offer source, and different solutions will be better for +different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if +any, to sign a "copyright disclaimer" for the program, if necessary. For more +information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/sdks/rust/tests/case-conversion-client/src/main.rs b/sdks/rust/tests/case-conversion-client/src/main.rs new file mode 100644 index 00000000000..eab19b8341c --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/main.rs @@ -0,0 +1,404 @@ +#![allow(clippy::disallowed_macros)] + +#[allow(clippy::too_many_arguments)] +#[allow(clippy::large_enum_variant)] +mod module_bindings; + +use module_bindings::*; +use spacetimedb_sdk::error::InternalError; +use spacetimedb_sdk::{DbContext, Table, TableWithPrimaryKey}; +use std::sync::Arc; +use test_counter::TestCounter; + +const LOCALHOST: &str = "http://localhost:3000"; + +fn db_name_or_panic() -> String { + std::env::var("SPACETIME_SDK_TEST_DB_NAME").expect("Failed to read db name from env") +} + +fn exit_on_panic() { + let default_hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |panic_info| { + default_hook(panic_info); + std::process::exit(1); + })); +} + +macro_rules! assert_eq_or_bail { + ($expected:expr, $found:expr) => {{ + let expected = &$expected; + let found = &$found; + if expected != found { + anyhow::bail!( + "Expected {} => {:?} but found {} => {:?}", + stringify!($expected), + expected, + stringify!($found), + found + ); + } + }}; +} + +fn main() { + env_logger::init(); + exit_on_panic(); + + let test = std::env::args() + .nth(1) + .expect("Pass a test name as a command-line argument to the test client"); + + match &*test { + "insert-player" => exec_insert_player(), + "insert-person" => exec_insert_person(), + "ban-player" => exec_ban_player(), + "query-builder-filter" => exec_query_builder_filter(), + "query-builder-join" => exec_query_builder_join(), + "view" => exec_view(), + _ => panic!("Unknown test: {test}"), + } +} + +type ResultRecorder = Box)>; + +fn put_result(result: &mut Option, res: anyhow::Result<()>) { + (result.take().unwrap())(res); +} + +fn reducer_callback_assert_committed( + reducer_name: &'static str, +) -> impl FnOnce(&ReducerEventContext, Result, InternalError>) + Send + 'static { + move |_ctx, outcome| match outcome { + Ok(Ok(())) => (), + Ok(Err(msg)) => panic!("`{reducer_name}` reducer returned error: {msg}"), + Err(internal_error) => panic!("`{reducer_name}` reducer panicked: {internal_error:?}"), + } +} + +fn connect_then( + test_counter: &Arc, + callback: impl FnOnce(&DbConnection) + Send + 'static, +) -> DbConnection { + let connected_result = test_counter.add_test("on_connect"); + let name = db_name_or_panic(); + let conn = DbConnection::builder() + .with_database_name(name) + .with_uri(LOCALHOST) + .on_connect(move |ctx, _, _| { + callback(ctx); + connected_result(Ok(())); + }) + .on_connect_error(|_ctx, error| panic!("Connect errored: {error:?}")) + .build() + .unwrap(); + conn.run_threaded(); + conn +} + +/// Test: Insert a player via CreatePlayer1 reducer using query builder subscription. +/// Verifies that table accessor `player_1()`, field names with digits +/// (`player_1_id`, `current_level_2`, `status_3_field`), and enum variant +/// `Player2Status::Active1` all work correctly through case conversion. +fn exec_insert_player() { + let test_counter = TestCounter::new(); + let mut insert_result = Some(test_counter.add_test("insert_player")); + + connect_then(&test_counter, move |ctx| { + ctx.subscription_builder() + .on_error(|_ctx, error| panic!("Subscription errored: {error:?}")) + .on_applied(move |ctx| { + ctx.db.player_1().on_insert(move |_ctx, row| { + let check = || { + // Verify field names with digit boundaries are correctly case-converted + assert_eq_or_bail!("Alice".to_string(), row.player_name); + assert_eq_or_bail!(5u32, row.current_level_2); + assert_eq_or_bail!(Player2Status::Active1, row.status_3_field); + Ok(()) + }; + put_result(&mut insert_result, check()); + }); + + ctx.reducers() + .create_player_1_then( + "Alice".to_string(), + 5, + reducer_callback_assert_committed("create_player_1"), + ) + .unwrap(); + }) + // Query builder: subscribe to player_1 table (canonical: Player1Canonical) + .add_query(|q| q.from.player_1().build()) + .subscribe(); + }); + + test_counter.wait_for_all(); +} + +/// Test: Insert a person via AddPerson2 reducer using query builder subscription. +/// Verifies nested struct `Person3Info` with digit-boundary fields +/// (`age_value_1`, `score_total`), index on `player_ref`, and +/// table accessor `person_2()`. +fn exec_insert_person() { + let test_counter = TestCounter::new(); + let mut insert_person = Some(test_counter.add_test("insert_person")); + + connect_then(&test_counter, move |ctx| { + ctx.subscription_builder() + .on_error(|_ctx, error| panic!("Subscription errored: {error:?}")) + .on_applied(move |ctx| { + ctx.db.person_2().on_insert(move |_ctx, person| { + let check = || { + assert_eq_or_bail!("Bob".to_string(), person.first_name); + // Verify nested struct field names with digit boundaries + assert_eq_or_bail!(25u8, person.person_info.age_value_1); + assert_eq_or_bail!(1000u32, person.person_info.score_total); + Ok(()) + }; + put_result(&mut insert_person, check()); + }); + + // Insert a player first, then add a person referencing them + ctx.reducers() + .create_player_1_then("PlayerForPerson".to_string(), 1, move |ctx, outcome| match outcome { + Ok(Ok(())) => { + let player = ctx.db.player_1().iter().next().expect("Player should exist"); + ctx.reducers() + .add_person_2_then( + "Bob".to_string(), + player.player_1_id, + 25, + 1000, + reducer_callback_assert_committed("add_person_2"), + ) + .unwrap(); + } + Ok(Err(msg)) => panic!("create_player_1 returned error: {msg}"), + Err(e) => panic!("create_player_1 panicked: {e:?}"), + }) + .unwrap(); + }) + // Query builder: subscribe to both tables + .add_query(|q| q.from.player_1().build()) + .add_query(|q| q.from.person_2().build()) + .subscribe(); + }); + + test_counter.wait_for_all(); +} + +/// Test: Ban a player via BanPlayer1 reducer (which has explicit name `banPlayer1`). +/// Verifies that reducers with explicit names work, and that updating a player's +/// status from `Active1` to `BannedUntil(timestamp)` is reflected correctly. +fn exec_ban_player() { + let test_counter = TestCounter::new(); + let mut update_result = Some(test_counter.add_test("ban_player_update")); + + connect_then(&test_counter, move |ctx| { + ctx.subscription_builder() + .on_error(|_ctx, error| panic!("Subscription errored: {error:?}")) + .on_applied(move |ctx| { + ctx.db.player_1().on_update(move |_ctx, _old, new| { + let check = || { + assert_eq_or_bail!(Player2Status::BannedUntil(9999), new.status_3_field); + Ok(()) + }; + put_result(&mut update_result, check()); + }); + + // Insert a player, then ban them in the reducer callback + ctx.reducers() + .create_player_1_then("ToBan".to_string(), 1, move |ctx, outcome| match outcome { + Ok(Ok(())) => { + let player = ctx.db.player_1().iter().next().expect("Player should exist"); + ctx.reducers() + .ban_player_1_then( + player.player_1_id, + 9999, + reducer_callback_assert_committed("ban_player_1"), + ) + .unwrap(); + } + Ok(Err(msg)) => panic!("create_player_1 returned error: {msg}"), + Err(e) => panic!("create_player_1 panicked: {e:?}"), + }) + .unwrap(); + }) + // Query builder: subscribe to player_1 table + .add_query(|q| q.from.player_1().build()) + .subscribe(); + }); + + test_counter.wait_for_all(); +} + +/// Test: Query builder with a filter on a digit-boundary column. +/// Subscribes to player_1 rows WHERE current_level_2 == 5, verifying that +/// the case-converted column name works correctly in query builder filters. +fn exec_query_builder_filter() { + let test_counter = TestCounter::new(); + let mut insert_match = Some(test_counter.add_test("insert_matching_filter")); + + connect_then(&test_counter, move |ctx| { + ctx.subscription_builder() + .on_error(|_ctx, error| panic!("Subscription errored: {error:?}")) + .on_applied(move |ctx| { + ctx.db.player_1().on_insert(move |_ctx, row| { + let check = || { + // Only level-5 players should come through the filter + assert_eq_or_bail!(5u32, row.current_level_2); + assert_eq_or_bail!("FilterMatch".to_string(), row.player_name); + Ok(()) + }; + put_result(&mut insert_match, check()); + }); + + // Insert a player at level 3 (should NOT match filter) + ctx.reducers() + .create_player_1_then( + "NoMatch".to_string(), + 3, + reducer_callback_assert_committed("create_player_1"), + ) + .unwrap(); + + // Insert a player at level 5 (should match filter) + ctx.reducers() + .create_player_1_then( + "FilterMatch".to_string(), + 5, + reducer_callback_assert_committed("create_player_1"), + ) + .unwrap(); + }) + // Query builder: filter on digit-boundary column current_level_2 + .add_query(|q| q.from.player_1().filter(|p| p.current_level_2.eq(5)).build()) + .subscribe(); + }); + + test_counter.wait_for_all(); +} + +/// Test: Query builder with a JOIN between player_1 and person_2. +/// Uses a right semijoin: person_2 results from player_1 JOIN person_2. +/// This tests that: +/// - Digit-boundary column names work in join predicates +/// - The query builder correctly resolves canonical table names for both tables +/// - Joined results are received correctly through case-converted accessors +/// - The view accessor `person_at_level_2()` returns Person2 rows +fn exec_query_builder_join() { + let test_counter = TestCounter::new(); + let mut join_result = Some(test_counter.add_test("join_insert")); + + connect_then(&test_counter, move |ctx| { + ctx.subscription_builder() + .on_error(|_ctx, error| panic!("Subscription errored: {error:?}")) + .on_applied(move |ctx| { + // Listen for person_2 inserts that come through the join. + // The join is: player_1 RIGHT SEMIJOIN person_2 ON player_1.player_1_id = person_2.player_ref + // This means we see person_2 rows that have a matching player_1 row. + ctx.db.person_2().on_insert(move |_ctx, row| { + // Only care about inserts from our join subscription + if row.first_name == "JoinPerson" { + let check = || { + assert_eq_or_bail!("JoinPerson".to_string(), row.first_name); + assert_eq_or_bail!(30u8, row.person_info.age_value_1); + assert_eq_or_bail!(500u32, row.person_info.score_total); + Ok(()) + }; + put_result(&mut join_result, check()); + } + }); + + // Insert a player first + ctx.reducers() + .create_player_1_then("JoinedPlayer".to_string(), 7, move |ctx, outcome| { + match outcome { + Ok(Ok(())) => { + let player = ctx + .db + .player_1() + .iter() + .find(|p| p.player_name == "JoinedPlayer") + .expect("JoinedPlayer should exist"); + + // Insert a person referencing this player — triggers the join + ctx.reducers() + .add_person_2_then( + "JoinPerson".to_string(), + player.player_1_id, + 30, + 500, + reducer_callback_assert_committed("add_person_2"), + ) + .unwrap(); + } + Ok(Err(msg)) => panic!("create_player_1 returned error: {msg}"), + Err(e) => panic!("create_player_1 panicked: {e:?}"), + } + }) + .unwrap(); + }) + // Query builder: JOIN player_1 with person_2 on player_1_id = player_ref + // player_1 RIGHT SEMIJOIN person_2 means: show person_2 rows that have a matching player_1 + .add_query(|q| { + q.from + .player_1() + .right_semijoin(q.from.person_2(), |player, person| { + player.player_1_id.eq(person.player_ref) + }) + .build() + }) + // Also subscribe to player_1 so reducer callbacks can see inserted players + .add_query(|q| q.from.player_1().build()) + .subscribe(); + }); + + test_counter.wait_for_all(); +} + +/// Query view named Level2Person +fn exec_view() { + let test_counter = TestCounter::new(); + let mut view_result = Some(test_counter.add_test("view_query")); + + connect_then(&test_counter, move |ctx| { + ctx.subscription_builder() + .on_error(|_ctx, error| panic!("Subscription errored: {error:?}")) + .on_applied(move |ctx| { + ctx.db.person_at_level_2().on_insert(move |_ctx, row| { + let check = || { + assert_eq_or_bail!("ViewPerson".to_string(), row.first_name); + assert_eq_or_bail!(20u8, row.person_info.age_value_1); + assert_eq_or_bail!(200u32, row.person_info.score_total); + Ok(()) + }; + put_result(&mut view_result, check()); + }); + + // Insert a player at level 2 + ctx.reducers() + .create_player_1_then( + "Level2Player".to_string(), + 2, + reducer_callback_assert_committed("create_player_1"), + ) + .unwrap(); + + // Insert a person referencing that player — should appear in the view + ctx.reducers() + .add_person_2_then( + "ViewPerson".to_string(), + 1, // player_ref of 1 matches the first inserted player + 20, + 200, + reducer_callback_assert_committed("add_person_2"), + ) + .unwrap(); + }) + // Subscribe to the view which selects people at level 2 + .add_query(|q| q.from.person_at_level_2().build()) + .subscribe(); + }); + + test_counter.wait_for_all(); +} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/add_person_2_reducer.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/add_person_2_reducer.rs new file mode 100644 index 00000000000..0aa0b3462d0 --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/add_person_2_reducer.rs @@ -0,0 +1,93 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub(super) struct AddPerson2Args { + pub first_3_name: String, + pub player_ref: u32, + pub age_value: u8, + pub score_total: u32, +} + +impl From for super::Reducer { + fn from(args: AddPerson2Args) -> Self { + Self::AddPerson2 { + first_3_name: args.first_3_name, + player_ref: args.player_ref, + age_value: args.age_value, + score_total: args.score_total, + } + } +} + +impl __sdk::InModule for AddPerson2Args { + type Module = super::RemoteModule; +} + +#[allow(non_camel_case_types)] +/// Extension trait for access to the reducer `add_person_2`. +/// +/// Implemented for [`super::RemoteReducers`]. +pub trait add_person_2 { + /// Request that the remote module invoke the reducer `add_person_2` to run as soon as possible. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and this method provides no way to listen for its completion status. + /// /// Use [`add_person_2:add_person_2_then`] to run a callback after the reducer completes. + fn add_person_2( + &self, + first_3_name: String, + player_ref: u32, + age_value: u8, + score_total: u32, + ) -> __sdk::Result<()> { + self.add_person_2_then(first_3_name, player_ref, age_value, score_total, |_, _| {}) + } + + /// Request that the remote module invoke the reducer `add_person_2` to run as soon as possible, + /// registering `callback` to run when we are notified that the reducer completed. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and its status can be observed with the `callback`. + fn add_person_2_then( + &self, + first_3_name: String, + player_ref: u32, + age_value: u8, + score_total: u32, + + callback: impl FnOnce(&super::ReducerEventContext, Result, __sdk::InternalError>) + + Send + + 'static, + ) -> __sdk::Result<()>; +} + +impl add_person_2 for super::RemoteReducers { + fn add_person_2_then( + &self, + first_3_name: String, + player_ref: u32, + age_value: u8, + score_total: u32, + + callback: impl FnOnce(&super::ReducerEventContext, Result, __sdk::InternalError>) + + Send + + 'static, + ) -> __sdk::Result<()> { + self.imp.invoke_reducer_with_callback( + AddPerson2Args { + first_3_name, + player_ref, + age_value, + score_total, + }, + callback, + ) + } +} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/ban_player_1_reducer.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/ban_player_1_reducer.rs new file mode 100644 index 00000000000..7ec558af60d --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/ban_player_1_reducer.rs @@ -0,0 +1,77 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub(super) struct BanPlayer1Args { + pub player_1_id: u32, + pub ban_until_6: u32, +} + +impl From for super::Reducer { + fn from(args: BanPlayer1Args) -> Self { + Self::BanPlayer1 { + player_1_id: args.player_1_id, + ban_until_6: args.ban_until_6, + } + } +} + +impl __sdk::InModule for BanPlayer1Args { + type Module = super::RemoteModule; +} + +#[allow(non_camel_case_types)] +/// Extension trait for access to the reducer `banPlayer1`. +/// +/// Implemented for [`super::RemoteReducers`]. +pub trait ban_player_1 { + /// Request that the remote module invoke the reducer `banPlayer1` to run as soon as possible. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and this method provides no way to listen for its completion status. + /// /// Use [`ban_player_1:ban_player_1_then`] to run a callback after the reducer completes. + fn ban_player_1(&self, player_1_id: u32, ban_until_6: u32) -> __sdk::Result<()> { + self.ban_player_1_then(player_1_id, ban_until_6, |_, _| {}) + } + + /// Request that the remote module invoke the reducer `banPlayer1` to run as soon as possible, + /// registering `callback` to run when we are notified that the reducer completed. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and its status can be observed with the `callback`. + fn ban_player_1_then( + &self, + player_1_id: u32, + ban_until_6: u32, + + callback: impl FnOnce(&super::ReducerEventContext, Result, __sdk::InternalError>) + + Send + + 'static, + ) -> __sdk::Result<()>; +} + +impl ban_player_1 for super::RemoteReducers { + fn ban_player_1_then( + &self, + player_1_id: u32, + ban_until_6: u32, + + callback: impl FnOnce(&super::ReducerEventContext, Result, __sdk::InternalError>) + + Send + + 'static, + ) -> __sdk::Result<()> { + self.imp.invoke_reducer_with_callback( + BanPlayer1Args { + player_1_id, + ban_until_6, + }, + callback, + ) + } +} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/create_player_1_reducer.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/create_player_1_reducer.rs new file mode 100644 index 00000000000..def48a5754f --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/create_player_1_reducer.rs @@ -0,0 +1,77 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub(super) struct CreatePlayer1Args { + pub player_1_name: String, + pub start_2_level: u32, +} + +impl From for super::Reducer { + fn from(args: CreatePlayer1Args) -> Self { + Self::CreatePlayer1 { + player_1_name: args.player_1_name, + start_2_level: args.start_2_level, + } + } +} + +impl __sdk::InModule for CreatePlayer1Args { + type Module = super::RemoteModule; +} + +#[allow(non_camel_case_types)] +/// Extension trait for access to the reducer `create_player_1`. +/// +/// Implemented for [`super::RemoteReducers`]. +pub trait create_player_1 { + /// Request that the remote module invoke the reducer `create_player_1` to run as soon as possible. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and this method provides no way to listen for its completion status. + /// /// Use [`create_player_1:create_player_1_then`] to run a callback after the reducer completes. + fn create_player_1(&self, player_1_name: String, start_2_level: u32) -> __sdk::Result<()> { + self.create_player_1_then(player_1_name, start_2_level, |_, _| {}) + } + + /// Request that the remote module invoke the reducer `create_player_1` to run as soon as possible, + /// registering `callback` to run when we are notified that the reducer completed. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and its status can be observed with the `callback`. + fn create_player_1_then( + &self, + player_1_name: String, + start_2_level: u32, + + callback: impl FnOnce(&super::ReducerEventContext, Result, __sdk::InternalError>) + + Send + + 'static, + ) -> __sdk::Result<()>; +} + +impl create_player_1 for super::RemoteReducers { + fn create_player_1_then( + &self, + player_1_name: String, + start_2_level: u32, + + callback: impl FnOnce(&super::ReducerEventContext, Result, __sdk::InternalError>) + + Send + + 'static, + ) -> __sdk::Result<()> { + self.imp.invoke_reducer_with_callback( + CreatePlayer1Args { + player_1_name, + start_2_level, + }, + callback, + ) + } +} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/mod.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/mod.rs new file mode 100644 index 00000000000..4fd6692b0ba --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/mod.rs @@ -0,0 +1,863 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +// This was generated using spacetimedb cli version 2.0.1 (commit e558d542f87c522811ce892cfd1129e4b0a5b97d). + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +pub mod add_person_2_reducer; +pub mod ban_player_1_reducer; +pub mod create_player_1_reducer; +pub mod person_2_table; +pub mod person_2_type; +pub mod person_3_info_type; +pub mod person_at_level_2_table; +pub mod player_1_table; +pub mod player_1_type; +pub mod player_2_status_type; + +pub use add_person_2_reducer::add_person_2; +pub use ban_player_1_reducer::ban_player_1; +pub use create_player_1_reducer::create_player_1; +pub use person_2_table::*; +pub use person_2_type::Person2; +pub use person_3_info_type::Person3Info; +pub use person_at_level_2_table::*; +pub use player_1_table::*; +pub use player_1_type::Player1; +pub use player_2_status_type::Player2Status; + +#[derive(Clone, PartialEq, Debug)] + +/// One of the reducers defined by this module. +/// +/// Contained within a [`__sdk::ReducerEvent`] in [`EventContext`]s for reducer events +/// to indicate which reducer caused the event. + +pub enum Reducer { + AddPerson2 { + first_3_name: String, + player_ref: u32, + age_value: u8, + score_total: u32, + }, + BanPlayer1 { + player_1_id: u32, + ban_until_6: u32, + }, + CreatePlayer1 { + player_1_name: String, + start_2_level: u32, + }, +} + +impl __sdk::InModule for Reducer { + type Module = RemoteModule; +} + +impl __sdk::Reducer for Reducer { + fn reducer_name(&self) -> &'static str { + match self { + Reducer::AddPerson2 { .. } => "add_person_2", + Reducer::BanPlayer1 { .. } => "banPlayer1", + Reducer::CreatePlayer1 { .. } => "create_player_1", + _ => unreachable!(), + } + } + #[allow(clippy::clone_on_copy)] + fn args_bsatn(&self) -> Result, __sats::bsatn::EncodeError> { + match self { + Reducer::AddPerson2 { + first_3_name, + player_ref, + age_value, + score_total, + } => __sats::bsatn::to_vec(&add_person_2_reducer::AddPerson2Args { + first_3_name: first_3_name.clone(), + player_ref: player_ref.clone(), + age_value: age_value.clone(), + score_total: score_total.clone(), + }), + Reducer::BanPlayer1 { + player_1_id, + ban_until_6, + } => __sats::bsatn::to_vec(&ban_player_1_reducer::BanPlayer1Args { + player_1_id: player_1_id.clone(), + ban_until_6: ban_until_6.clone(), + }), + Reducer::CreatePlayer1 { + player_1_name, + start_2_level, + } => __sats::bsatn::to_vec(&create_player_1_reducer::CreatePlayer1Args { + player_1_name: player_1_name.clone(), + start_2_level: start_2_level.clone(), + }), + _ => unreachable!(), + } + } +} + +#[derive(Default)] +#[allow(non_snake_case)] +#[doc(hidden)] +pub struct DbUpdate { + person_2: __sdk::TableUpdate, + person_at_level_2: __sdk::TableUpdate, + player_1: __sdk::TableUpdate, +} + +impl TryFrom<__ws::v2::TransactionUpdate> for DbUpdate { + type Error = __sdk::Error; + fn try_from(raw: __ws::v2::TransactionUpdate) -> Result { + let mut db_update = DbUpdate::default(); + for table_update in __sdk::transaction_update_iter_table_updates(raw) { + match &table_update.table_name[..] { + "person_2" => db_update + .person_2 + .append(person_2_table::parse_table_update(table_update)?), + "Level2Person" => db_update + .person_at_level_2 + .append(person_at_level_2_table::parse_table_update(table_update)?), + "Player1Canonical" => db_update + .player_1 + .append(player_1_table::parse_table_update(table_update)?), + + unknown => { + return Err(__sdk::InternalError::unknown_name("table", unknown, "DatabaseUpdate").into()); + } + } + } + Ok(db_update) + } +} + +impl __sdk::InModule for DbUpdate { + type Module = RemoteModule; +} + +impl __sdk::DbUpdate for DbUpdate { + fn apply_to_client_cache(&self, cache: &mut __sdk::ClientCache) -> AppliedDiff<'_> { + let mut diff = AppliedDiff::default(); + + diff.player_1 = cache + .apply_diff_to_table::("Player1Canonical", &self.player_1) + .with_updates_by_pk(|row| &row.player_1_id); + diff.person_2 = cache + .apply_diff_to_table::("person_2", &self.person_2) + .with_updates_by_pk(|row| &row.person_2_id); + diff.person_at_level_2 = cache.apply_diff_to_table::("Level2Person", &self.person_at_level_2); + + diff + } + fn parse_initial_rows(raw: __ws::v2::QueryRows) -> __sdk::Result { + let mut db_update = DbUpdate::default(); + for table_rows in raw.tables { + match &table_rows.table[..] { + "person_2" => db_update + .person_2 + .append(__sdk::parse_row_list_as_inserts(table_rows.rows)?), + "Level2Person" => db_update + .person_at_level_2 + .append(__sdk::parse_row_list_as_inserts(table_rows.rows)?), + "Player1Canonical" => db_update + .player_1 + .append(__sdk::parse_row_list_as_inserts(table_rows.rows)?), + unknown => { + return Err(__sdk::InternalError::unknown_name("table", unknown, "QueryRows").into()); + } + } + } + Ok(db_update) + } + fn parse_unsubscribe_rows(raw: __ws::v2::QueryRows) -> __sdk::Result { + let mut db_update = DbUpdate::default(); + for table_rows in raw.tables { + match &table_rows.table[..] { + "person_2" => db_update + .person_2 + .append(__sdk::parse_row_list_as_deletes(table_rows.rows)?), + "Level2Person" => db_update + .person_at_level_2 + .append(__sdk::parse_row_list_as_deletes(table_rows.rows)?), + "Player1Canonical" => db_update + .player_1 + .append(__sdk::parse_row_list_as_deletes(table_rows.rows)?), + unknown => { + return Err(__sdk::InternalError::unknown_name("table", unknown, "QueryRows").into()); + } + } + } + Ok(db_update) + } +} + +#[derive(Default)] +#[allow(non_snake_case)] +#[doc(hidden)] +pub struct AppliedDiff<'r> { + person_2: __sdk::TableAppliedDiff<'r, Person2>, + person_at_level_2: __sdk::TableAppliedDiff<'r, Person2>, + player_1: __sdk::TableAppliedDiff<'r, Player1>, + __unused: std::marker::PhantomData<&'r ()>, +} + +impl __sdk::InModule for AppliedDiff<'_> { + type Module = RemoteModule; +} + +impl<'r> __sdk::AppliedDiff<'r> for AppliedDiff<'r> { + fn invoke_row_callbacks(&self, event: &EventContext, callbacks: &mut __sdk::DbCallbacks) { + callbacks.invoke_table_row_callbacks::("person_2", &self.person_2, event); + callbacks.invoke_table_row_callbacks::("Level2Person", &self.person_at_level_2, event); + callbacks.invoke_table_row_callbacks::("Player1Canonical", &self.player_1, event); + } +} + +#[doc(hidden)] +pub struct RemoteModule; + +impl __sdk::InModule for RemoteModule { + type Module = Self; +} + +/// The `reducers` field of [`EventContext`] and [`DbConnection`], +/// with methods provided by extension traits for each reducer defined by the module. +pub struct RemoteReducers { + imp: __sdk::DbContextImpl, +} + +impl __sdk::InModule for RemoteReducers { + type Module = RemoteModule; +} + +/// The `procedures` field of [`DbConnection`] and other [`DbContext`] types, +/// with methods provided by extension traits for each procedure defined by the module. +pub struct RemoteProcedures { + imp: __sdk::DbContextImpl, +} + +impl __sdk::InModule for RemoteProcedures { + type Module = RemoteModule; +} + +/// The `db` field of [`EventContext`] and [`DbConnection`], +/// with methods provided by extension traits for each table defined by the module. +pub struct RemoteTables { + imp: __sdk::DbContextImpl, +} + +impl __sdk::InModule for RemoteTables { + type Module = RemoteModule; +} + +/// A connection to a remote module, including a materialized view of a subset of the database. +/// +/// Connect to a remote module by calling [`DbConnection::builder`] +/// and using the [`__sdk::DbConnectionBuilder`] builder-pattern constructor. +/// +/// You must explicitly advance the connection by calling any one of: +/// +/// - [`DbConnection::frame_tick`]. +/// - [`DbConnection::run_threaded`]. +/// - [`DbConnection::run_async`]. +/// - [`DbConnection::advance_one_message`]. +/// - [`DbConnection::advance_one_message_blocking`]. +/// - [`DbConnection::advance_one_message_async`]. +/// +/// Which of these methods you should call depends on the specific needs of your application, +/// but you must call one of them, or else the connection will never progress. +pub struct DbConnection { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + #[doc(hidden)] + + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + + imp: __sdk::DbContextImpl, +} + +impl __sdk::InModule for DbConnection { + type Module = RemoteModule; +} + +impl __sdk::DbContext for DbConnection { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl DbConnection { + /// Builder-pattern constructor for a connection to a remote module. + /// + /// See [`__sdk::DbConnectionBuilder`] for required and optional configuration for the new connection. + pub fn builder() -> __sdk::DbConnectionBuilder { + __sdk::DbConnectionBuilder::new() + } + + /// If any WebSocket messages are waiting, process one of them. + /// + /// Returns `true` if a message was processed, or `false` if the queue is empty. + /// Callers should invoke this message in a loop until it returns `false` + /// or for as much time is available to process messages. + /// + /// Returns an error if the connection is disconnected. + /// If the disconnection in question was normal, + /// i.e. the result of a call to [`__sdk::DbContext::disconnect`], + /// the returned error will be downcastable to [`__sdk::DisconnectedError`]. + /// + /// This is a low-level primitive exposed for power users who need significant control over scheduling. + /// Most applications should call [`Self::frame_tick`] each frame + /// to fully exhaust the queue whenever time is available. + pub fn advance_one_message(&self) -> __sdk::Result { + self.imp.advance_one_message() + } + + /// Process one WebSocket message, potentially blocking the current thread until one is received. + /// + /// Returns an error if the connection is disconnected. + /// If the disconnection in question was normal, + /// i.e. the result of a call to [`__sdk::DbContext::disconnect`], + /// the returned error will be downcastable to [`__sdk::DisconnectedError`]. + /// + /// This is a low-level primitive exposed for power users who need significant control over scheduling. + /// Most applications should call [`Self::run_threaded`] to spawn a thread + /// which advances the connection automatically. + pub fn advance_one_message_blocking(&self) -> __sdk::Result<()> { + self.imp.advance_one_message_blocking() + } + + /// Process one WebSocket message, `await`ing until one is received. + /// + /// Returns an error if the connection is disconnected. + /// If the disconnection in question was normal, + /// i.e. the result of a call to [`__sdk::DbContext::disconnect`], + /// the returned error will be downcastable to [`__sdk::DisconnectedError`]. + /// + /// This is a low-level primitive exposed for power users who need significant control over scheduling. + /// Most applications should call [`Self::run_async`] to run an `async` loop + /// which advances the connection when polled. + pub async fn advance_one_message_async(&self) -> __sdk::Result<()> { + self.imp.advance_one_message_async().await + } + + /// Process all WebSocket messages waiting in the queue, + /// then return without `await`ing or blocking the current thread. + pub fn frame_tick(&self) -> __sdk::Result<()> { + self.imp.frame_tick() + } + + /// Spawn a thread which processes WebSocket messages as they are received. + pub fn run_threaded(&self) -> std::thread::JoinHandle<()> { + self.imp.run_threaded() + } + + /// Run an `async` loop which processes WebSocket messages when polled. + pub async fn run_async(&self) -> __sdk::Result<()> { + self.imp.run_async().await + } +} + +impl __sdk::DbConnection for DbConnection { + fn new(imp: __sdk::DbContextImpl) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + imp, + } + } +} + +/// A handle on a subscribed query. +// TODO: Document this better after implementing the new subscription API. +#[derive(Clone)] +pub struct SubscriptionHandle { + imp: __sdk::SubscriptionHandleImpl, +} + +impl __sdk::InModule for SubscriptionHandle { + type Module = RemoteModule; +} + +impl __sdk::SubscriptionHandle for SubscriptionHandle { + fn new(imp: __sdk::SubscriptionHandleImpl) -> Self { + Self { imp } + } + + /// Returns true if this subscription has been terminated due to an unsubscribe call or an error. + fn is_ended(&self) -> bool { + self.imp.is_ended() + } + + /// Returns true if this subscription has been applied and has not yet been unsubscribed. + fn is_active(&self) -> bool { + self.imp.is_active() + } + + /// Unsubscribe from the query controlled by this `SubscriptionHandle`, + /// then run `on_end` when its rows are removed from the client cache. + fn unsubscribe_then(self, on_end: __sdk::OnEndedCallback) -> __sdk::Result<()> { + self.imp.unsubscribe_then(Some(on_end)) + } + + fn unsubscribe(self) -> __sdk::Result<()> { + self.imp.unsubscribe_then(None) + } +} + +/// Alias trait for a [`__sdk::DbContext`] connected to this module, +/// with that trait's associated types bounded to this module's concrete types. +/// +/// Users can use this trait as a boundary on definitions which should accept +/// either a [`DbConnection`] or an [`EventContext`] and operate on either. +pub trait RemoteDbContext: + __sdk::DbContext< + DbView = RemoteTables, + Reducers = RemoteReducers, + SubscriptionBuilder = __sdk::SubscriptionBuilder, +> +{ +} +impl< + Ctx: __sdk::DbContext< + DbView = RemoteTables, + Reducers = RemoteReducers, + SubscriptionBuilder = __sdk::SubscriptionBuilder, + >, + > RemoteDbContext for Ctx +{ +} + +/// An [`__sdk::DbContext`] augmented with a [`__sdk::Event`], +/// passed to [`__sdk::Table::on_insert`], [`__sdk::Table::on_delete`] and [`__sdk::TableWithPrimaryKey::on_update`] callbacks. +pub struct EventContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + /// The event which caused these callbacks to run. + pub event: __sdk::Event, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for EventContext { + type Event = __sdk::Event; + fn event(&self) -> &Self::Event { + &self.event + } + fn new(imp: __sdk::DbContextImpl, event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + event, + imp, + } + } +} + +impl __sdk::InModule for EventContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for EventContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::EventContext for EventContext {} + +/// An [`__sdk::DbContext`] augmented with a [`__sdk::ReducerEvent`], +/// passed to on-reducer callbacks. +pub struct ReducerEventContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + /// The event which caused these callbacks to run. + pub event: __sdk::ReducerEvent, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for ReducerEventContext { + type Event = __sdk::ReducerEvent; + fn event(&self) -> &Self::Event { + &self.event + } + fn new(imp: __sdk::DbContextImpl, event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + event, + imp, + } + } +} + +impl __sdk::InModule for ReducerEventContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for ReducerEventContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::ReducerEventContext for ReducerEventContext {} + +/// An [`__sdk::DbContext`] passed to procedure callbacks. +pub struct ProcedureEventContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for ProcedureEventContext { + type Event = (); + fn event(&self) -> &Self::Event { + &() + } + fn new(imp: __sdk::DbContextImpl, _event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + imp, + } + } +} + +impl __sdk::InModule for ProcedureEventContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for ProcedureEventContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::ProcedureEventContext for ProcedureEventContext {} + +/// An [`__sdk::DbContext`] passed to [`__sdk::SubscriptionBuilder::on_applied`] and [`SubscriptionHandle::unsubscribe_then`] callbacks. +pub struct SubscriptionEventContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for SubscriptionEventContext { + type Event = (); + fn event(&self) -> &Self::Event { + &() + } + fn new(imp: __sdk::DbContextImpl, _event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + imp, + } + } +} + +impl __sdk::InModule for SubscriptionEventContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for SubscriptionEventContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::SubscriptionEventContext for SubscriptionEventContext {} + +/// An [`__sdk::DbContext`] augmented with a [`__sdk::Error`], +/// passed to [`__sdk::DbConnectionBuilder::on_disconnect`], [`__sdk::DbConnectionBuilder::on_connect_error`] and [`__sdk::SubscriptionBuilder::on_error`] callbacks. +pub struct ErrorContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + /// The event which caused these callbacks to run. + pub event: Option<__sdk::Error>, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for ErrorContext { + type Event = Option<__sdk::Error>; + fn event(&self) -> &Self::Event { + &self.event + } + fn new(imp: __sdk::DbContextImpl, event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + event, + imp, + } + } +} + +impl __sdk::InModule for ErrorContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for ErrorContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::ErrorContext for ErrorContext {} + +impl __sdk::SpacetimeModule for RemoteModule { + type DbConnection = DbConnection; + type EventContext = EventContext; + type ReducerEventContext = ReducerEventContext; + type ProcedureEventContext = ProcedureEventContext; + type SubscriptionEventContext = SubscriptionEventContext; + type ErrorContext = ErrorContext; + type Reducer = Reducer; + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + type DbUpdate = DbUpdate; + type AppliedDiff<'r> = AppliedDiff<'r>; + type SubscriptionHandle = SubscriptionHandle; + type QueryBuilder = __sdk::QueryBuilder; + + fn register_tables(client_cache: &mut __sdk::ClientCache) { + person_2_table::register_table(client_cache); + person_at_level_2_table::register_table(client_cache); + player_1_table::register_table(client_cache); + } + const ALL_TABLE_NAMES: &'static [&'static str] = &["person_2", "Level2Person", "Player1Canonical"]; +} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/person_2_table.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/person_2_table.rs new file mode 100644 index 00000000000..d485d0202cd --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/person_2_table.rs @@ -0,0 +1,158 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use super::person_2_type::Person2; +use super::person_3_info_type::Person3Info; +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +/// Table handle for the table `person_2`. +/// +/// Obtain a handle from the [`Person2TableAccess::person_2`] method on [`super::RemoteTables`], +/// like `ctx.db.person_2()`. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.person_2().on_insert(...)`. +pub struct Person2TableHandle<'ctx> { + imp: __sdk::TableHandle, + ctx: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +#[allow(non_camel_case_types)] +/// Extension trait for access to the table `person_2`. +/// +/// Implemented for [`super::RemoteTables`]. +pub trait Person2TableAccess { + #[allow(non_snake_case)] + /// Obtain a [`Person2TableHandle`], which mediates access to the table `person_2`. + fn person_2(&self) -> Person2TableHandle<'_>; +} + +impl Person2TableAccess for super::RemoteTables { + fn person_2(&self) -> Person2TableHandle<'_> { + Person2TableHandle { + imp: self.imp.get_table::("person_2"), + ctx: std::marker::PhantomData, + } + } +} + +pub struct Person2InsertCallbackId(__sdk::CallbackId); +pub struct Person2DeleteCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::Table for Person2TableHandle<'ctx> { + type Row = Person2; + type EventContext = super::EventContext; + + fn count(&self) -> u64 { + self.imp.count() + } + fn iter(&self) -> impl Iterator + '_ { + self.imp.iter() + } + + type InsertCallbackId = Person2InsertCallbackId; + + fn on_insert( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> Person2InsertCallbackId { + Person2InsertCallbackId(self.imp.on_insert(Box::new(callback))) + } + + fn remove_on_insert(&self, callback: Person2InsertCallbackId) { + self.imp.remove_on_insert(callback.0) + } + + type DeleteCallbackId = Person2DeleteCallbackId; + + fn on_delete( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> Person2DeleteCallbackId { + Person2DeleteCallbackId(self.imp.on_delete(Box::new(callback))) + } + + fn remove_on_delete(&self, callback: Person2DeleteCallbackId) { + self.imp.remove_on_delete(callback.0) + } +} + +pub struct Person2UpdateCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::TableWithPrimaryKey for Person2TableHandle<'ctx> { + type UpdateCallbackId = Person2UpdateCallbackId; + + fn on_update( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static, + ) -> Person2UpdateCallbackId { + Person2UpdateCallbackId(self.imp.on_update(Box::new(callback))) + } + + fn remove_on_update(&self, callback: Person2UpdateCallbackId) { + self.imp.remove_on_update(callback.0) + } +} + +/// Access to the `person_2_id` unique index on the table `person_2`, +/// which allows point queries on the field of the same name +/// via the [`Person2Person2IdUnique::find`] method. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.person_2().person_2_id().find(...)`. +pub struct Person2Person2IdUnique<'ctx> { + imp: __sdk::UniqueConstraintHandle, + phantom: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +impl<'ctx> Person2TableHandle<'ctx> { + /// Get a handle on the `person_2_id` unique index on the table `person_2`. + pub fn person_2_id(&self) -> Person2Person2IdUnique<'ctx> { + Person2Person2IdUnique { + imp: self.imp.get_unique_constraint::("person_2_id"), + phantom: std::marker::PhantomData, + } + } +} + +impl<'ctx> Person2Person2IdUnique<'ctx> { + /// Find the subscribed row whose `person_2_id` column value is equal to `col_val`, + /// if such a row is present in the client cache. + pub fn find(&self, col_val: &u32) -> Option { + self.imp.find(col_val) + } +} + +#[doc(hidden)] +pub(super) fn register_table(client_cache: &mut __sdk::ClientCache) { + let _table = client_cache.get_or_make_table::("person_2"); + _table.add_unique_constraint::("person_2_id", |row| &row.person_2_id); +} + +#[doc(hidden)] +pub(super) fn parse_table_update(raw_updates: __ws::v2::TableUpdate) -> __sdk::Result<__sdk::TableUpdate> { + __sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| { + __sdk::InternalError::failed_parse("TableUpdate", "TableUpdate") + .with_cause(e) + .into() + }) +} + +#[allow(non_camel_case_types)] +/// Extension trait for query builder access to the table `Person2`. +/// +/// Implemented for [`__sdk::QueryTableAccessor`]. +pub trait person_2QueryTableAccess { + #[allow(non_snake_case)] + /// Get a query builder for the table `Person2`. + fn person_2(&self) -> __sdk::__query_builder::Table; +} + +impl person_2QueryTableAccess for __sdk::QueryTableAccessor { + fn person_2(&self) -> __sdk::__query_builder::Table { + __sdk::__query_builder::Table::new("person_2") + } +} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/person_2_type.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/person_2_type.rs new file mode 100644 index 00000000000..fbd750cdc38 --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/person_2_type.rs @@ -0,0 +1,62 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +use super::person_3_info_type::Person3Info; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct Person2 { + pub person_2_id: u32, + pub first_name: String, + pub player_ref: u32, + pub person_info: Person3Info, +} + +impl __sdk::InModule for Person2 { + type Module = super::RemoteModule; +} + +/// Column accessor struct for the table `Person2`. +/// +/// Provides typed access to columns for query building. +pub struct Person2Cols { + pub person_2_id: __sdk::__query_builder::Col, + pub first_name: __sdk::__query_builder::Col, + pub player_ref: __sdk::__query_builder::Col, + pub person_info: __sdk::__query_builder::Col, +} + +impl __sdk::__query_builder::HasCols for Person2 { + type Cols = Person2Cols; + fn cols(table_name: &'static str) -> Self::Cols { + Person2Cols { + person_2_id: __sdk::__query_builder::Col::new(table_name, "person_2_id"), + first_name: __sdk::__query_builder::Col::new(table_name, "first_name"), + player_ref: __sdk::__query_builder::Col::new(table_name, "player_ref"), + person_info: __sdk::__query_builder::Col::new(table_name, "person_info"), + } + } +} + +/// Indexed column accessor struct for the table `Person2`. +/// +/// Provides typed access to indexed columns for query building. +pub struct Person2IxCols { + pub person_2_id: __sdk::__query_builder::IxCol, + pub player_ref: __sdk::__query_builder::IxCol, +} + +impl __sdk::__query_builder::HasIxCols for Person2 { + type IxCols = Person2IxCols; + fn ix_cols(table_name: &'static str) -> Self::IxCols { + Person2IxCols { + person_2_id: __sdk::__query_builder::IxCol::new(table_name, "person_2_id"), + player_ref: __sdk::__query_builder::IxCol::new(table_name, "player_ref"), + } + } +} + +impl __sdk::__query_builder::CanBeLookupTable for Person2 {} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/person_3_info_type.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/person_3_info_type.rs new file mode 100644 index 00000000000..5967814da41 --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/person_3_info_type.rs @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct Person3Info { + pub age_value_1: u8, + pub score_total: u32, +} + +impl __sdk::InModule for Person3Info { + type Module = super::RemoteModule; +} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/person_at_level_2_table.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/person_at_level_2_table.rs new file mode 100644 index 00000000000..ae76250648d --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/person_at_level_2_table.rs @@ -0,0 +1,110 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use super::person_2_type::Person2; +use super::person_3_info_type::Person3Info; +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +/// Table handle for the table `Level2Person`. +/// +/// Obtain a handle from the [`PersonAtLevel2TableAccess::person_at_level_2`] method on [`super::RemoteTables`], +/// like `ctx.db.person_at_level_2()`. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.person_at_level_2().on_insert(...)`. +pub struct PersonAtLevel2TableHandle<'ctx> { + imp: __sdk::TableHandle, + ctx: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +#[allow(non_camel_case_types)] +/// Extension trait for access to the table `Level2Person`. +/// +/// Implemented for [`super::RemoteTables`]. +pub trait PersonAtLevel2TableAccess { + #[allow(non_snake_case)] + /// Obtain a [`PersonAtLevel2TableHandle`], which mediates access to the table `Level2Person`. + fn person_at_level_2(&self) -> PersonAtLevel2TableHandle<'_>; +} + +impl PersonAtLevel2TableAccess for super::RemoteTables { + fn person_at_level_2(&self) -> PersonAtLevel2TableHandle<'_> { + PersonAtLevel2TableHandle { + imp: self.imp.get_table::("Level2Person"), + ctx: std::marker::PhantomData, + } + } +} + +pub struct PersonAtLevel2InsertCallbackId(__sdk::CallbackId); +pub struct PersonAtLevel2DeleteCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::Table for PersonAtLevel2TableHandle<'ctx> { + type Row = Person2; + type EventContext = super::EventContext; + + fn count(&self) -> u64 { + self.imp.count() + } + fn iter(&self) -> impl Iterator + '_ { + self.imp.iter() + } + + type InsertCallbackId = PersonAtLevel2InsertCallbackId; + + fn on_insert( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> PersonAtLevel2InsertCallbackId { + PersonAtLevel2InsertCallbackId(self.imp.on_insert(Box::new(callback))) + } + + fn remove_on_insert(&self, callback: PersonAtLevel2InsertCallbackId) { + self.imp.remove_on_insert(callback.0) + } + + type DeleteCallbackId = PersonAtLevel2DeleteCallbackId; + + fn on_delete( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> PersonAtLevel2DeleteCallbackId { + PersonAtLevel2DeleteCallbackId(self.imp.on_delete(Box::new(callback))) + } + + fn remove_on_delete(&self, callback: PersonAtLevel2DeleteCallbackId) { + self.imp.remove_on_delete(callback.0) + } +} + +#[doc(hidden)] +pub(super) fn register_table(client_cache: &mut __sdk::ClientCache) { + let _table = client_cache.get_or_make_table::("Level2Person"); +} + +#[doc(hidden)] +pub(super) fn parse_table_update(raw_updates: __ws::v2::TableUpdate) -> __sdk::Result<__sdk::TableUpdate> { + __sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| { + __sdk::InternalError::failed_parse("TableUpdate", "TableUpdate") + .with_cause(e) + .into() + }) +} + +#[allow(non_camel_case_types)] +/// Extension trait for query builder access to the table `Person2`. +/// +/// Implemented for [`__sdk::QueryTableAccessor`]. +pub trait person_at_level_2QueryTableAccess { + #[allow(non_snake_case)] + /// Get a query builder for the table `Person2`. + fn person_at_level_2(&self) -> __sdk::__query_builder::Table; +} + +impl person_at_level_2QueryTableAccess for __sdk::QueryTableAccessor { + fn person_at_level_2(&self) -> __sdk::__query_builder::Table { + __sdk::__query_builder::Table::new("Level2Person") + } +} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/player_1_table.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/player_1_table.rs new file mode 100644 index 00000000000..40715b187dd --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/player_1_table.rs @@ -0,0 +1,158 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use super::player_1_type::Player1; +use super::player_2_status_type::Player2Status; +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +/// Table handle for the table `Player1Canonical`. +/// +/// Obtain a handle from the [`Player1TableAccess::player_1`] method on [`super::RemoteTables`], +/// like `ctx.db.player_1()`. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.player_1().on_insert(...)`. +pub struct Player1TableHandle<'ctx> { + imp: __sdk::TableHandle, + ctx: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +#[allow(non_camel_case_types)] +/// Extension trait for access to the table `Player1Canonical`. +/// +/// Implemented for [`super::RemoteTables`]. +pub trait Player1TableAccess { + #[allow(non_snake_case)] + /// Obtain a [`Player1TableHandle`], which mediates access to the table `Player1Canonical`. + fn player_1(&self) -> Player1TableHandle<'_>; +} + +impl Player1TableAccess for super::RemoteTables { + fn player_1(&self) -> Player1TableHandle<'_> { + Player1TableHandle { + imp: self.imp.get_table::("Player1Canonical"), + ctx: std::marker::PhantomData, + } + } +} + +pub struct Player1InsertCallbackId(__sdk::CallbackId); +pub struct Player1DeleteCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::Table for Player1TableHandle<'ctx> { + type Row = Player1; + type EventContext = super::EventContext; + + fn count(&self) -> u64 { + self.imp.count() + } + fn iter(&self) -> impl Iterator + '_ { + self.imp.iter() + } + + type InsertCallbackId = Player1InsertCallbackId; + + fn on_insert( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> Player1InsertCallbackId { + Player1InsertCallbackId(self.imp.on_insert(Box::new(callback))) + } + + fn remove_on_insert(&self, callback: Player1InsertCallbackId) { + self.imp.remove_on_insert(callback.0) + } + + type DeleteCallbackId = Player1DeleteCallbackId; + + fn on_delete( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> Player1DeleteCallbackId { + Player1DeleteCallbackId(self.imp.on_delete(Box::new(callback))) + } + + fn remove_on_delete(&self, callback: Player1DeleteCallbackId) { + self.imp.remove_on_delete(callback.0) + } +} + +pub struct Player1UpdateCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::TableWithPrimaryKey for Player1TableHandle<'ctx> { + type UpdateCallbackId = Player1UpdateCallbackId; + + fn on_update( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static, + ) -> Player1UpdateCallbackId { + Player1UpdateCallbackId(self.imp.on_update(Box::new(callback))) + } + + fn remove_on_update(&self, callback: Player1UpdateCallbackId) { + self.imp.remove_on_update(callback.0) + } +} + +/// Access to the `player_1_id` unique index on the table `Player1Canonical`, +/// which allows point queries on the field of the same name +/// via the [`Player1Player1IdUnique::find`] method. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.player_1().player_1_id().find(...)`. +pub struct Player1Player1IdUnique<'ctx> { + imp: __sdk::UniqueConstraintHandle, + phantom: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +impl<'ctx> Player1TableHandle<'ctx> { + /// Get a handle on the `player_1_id` unique index on the table `Player1Canonical`. + pub fn player_1_id(&self) -> Player1Player1IdUnique<'ctx> { + Player1Player1IdUnique { + imp: self.imp.get_unique_constraint::("player_1_id"), + phantom: std::marker::PhantomData, + } + } +} + +impl<'ctx> Player1Player1IdUnique<'ctx> { + /// Find the subscribed row whose `player_1_id` column value is equal to `col_val`, + /// if such a row is present in the client cache. + pub fn find(&self, col_val: &u32) -> Option { + self.imp.find(col_val) + } +} + +#[doc(hidden)] +pub(super) fn register_table(client_cache: &mut __sdk::ClientCache) { + let _table = client_cache.get_or_make_table::("Player1Canonical"); + _table.add_unique_constraint::("player_1_id", |row| &row.player_1_id); +} + +#[doc(hidden)] +pub(super) fn parse_table_update(raw_updates: __ws::v2::TableUpdate) -> __sdk::Result<__sdk::TableUpdate> { + __sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| { + __sdk::InternalError::failed_parse("TableUpdate", "TableUpdate") + .with_cause(e) + .into() + }) +} + +#[allow(non_camel_case_types)] +/// Extension trait for query builder access to the table `Player1`. +/// +/// Implemented for [`__sdk::QueryTableAccessor`]. +pub trait player_1QueryTableAccess { + #[allow(non_snake_case)] + /// Get a query builder for the table `Player1`. + fn player_1(&self) -> __sdk::__query_builder::Table; +} + +impl player_1QueryTableAccess for __sdk::QueryTableAccessor { + fn player_1(&self) -> __sdk::__query_builder::Table { + __sdk::__query_builder::Table::new("Player1Canonical") + } +} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/player_1_type.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/player_1_type.rs new file mode 100644 index 00000000000..6145af63770 --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/player_1_type.rs @@ -0,0 +1,60 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +use super::player_2_status_type::Player2Status; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct Player1 { + pub player_1_id: u32, + pub player_name: String, + pub current_level_2: u32, + pub status_3_field: Player2Status, +} + +impl __sdk::InModule for Player1 { + type Module = super::RemoteModule; +} + +/// Column accessor struct for the table `Player1`. +/// +/// Provides typed access to columns for query building. +pub struct Player1Cols { + pub player_1_id: __sdk::__query_builder::Col, + pub player_name: __sdk::__query_builder::Col, + pub current_level_2: __sdk::__query_builder::Col, + pub status_3_field: __sdk::__query_builder::Col, +} + +impl __sdk::__query_builder::HasCols for Player1 { + type Cols = Player1Cols; + fn cols(table_name: &'static str) -> Self::Cols { + Player1Cols { + player_1_id: __sdk::__query_builder::Col::new(table_name, "player_1_id"), + player_name: __sdk::__query_builder::Col::new(table_name, "player_name"), + current_level_2: __sdk::__query_builder::Col::new(table_name, "current_level_2"), + status_3_field: __sdk::__query_builder::Col::new(table_name, "status_3_field"), + } + } +} + +/// Indexed column accessor struct for the table `Player1`. +/// +/// Provides typed access to indexed columns for query building. +pub struct Player1IxCols { + pub player_1_id: __sdk::__query_builder::IxCol, +} + +impl __sdk::__query_builder::HasIxCols for Player1 { + type IxCols = Player1IxCols; + fn ix_cols(table_name: &'static str) -> Self::IxCols { + Player1IxCols { + player_1_id: __sdk::__query_builder::IxCol::new(table_name, "player_1_id"), + } + } +} + +impl __sdk::__query_builder::CanBeLookupTable for Player1 {} diff --git a/sdks/rust/tests/case-conversion-client/src/module_bindings/player_2_status_type.rs b/sdks/rust/tests/case-conversion-client/src/module_bindings/player_2_status_type.rs new file mode 100644 index 00000000000..1f7082aafef --- /dev/null +++ b/sdks/rust/tests/case-conversion-client/src/module_bindings/player_2_status_type.rs @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub enum Player2Status { + Active1, + + BannedUntil(u32), +} + +impl __sdk::InModule for Player2Status { + type Module = super::RemoteModule; +} diff --git a/sdks/rust/tests/test.rs b/sdks/rust/tests/test.rs index a430382c841..3a2cf8cfc1d 100644 --- a/sdks/rust/tests/test.rs +++ b/sdks/rust/tests/test.rs @@ -488,3 +488,153 @@ macro_rules! view_tests { view_tests!(rust_view, ""); //view_tests!(cpp_view, "-cpp"); + +mod case_conversion_ts { + use spacetimedb_testing::sdk::Test; + + const MODULE: &str = "sdk-test-case-conversion-ts"; + const CLIENT: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/case-conversion-client"); + + fn make_test(subcommand: &str) -> Test { + Test::builder() + .with_name(subcommand) + .with_module(MODULE) + .with_client(CLIENT) + .with_language("rust") + .with_bindings_dir("src/module_bindings") + .with_compile_command("cargo build") + .with_run_command(format!("cargo run -- {}", subcommand)) + .build() + } + + #[test] + fn insert_player() { + make_test("insert-player").run(); + } + + #[test] + fn insert_person() { + make_test("insert-person").run(); + } + + #[test] + fn ban_player() { + make_test("ban-player").run(); + } + + #[test] + fn query_builder_filter() { + make_test("query-builder-filter").run(); + } + + #[test] + fn query_builder_join() { + make_test("query-builder-join").run(); + } + + #[test] + fn query_view() { + make_test("view").run(); + } +} + +mod case_conversion_rust { + use spacetimedb_testing::sdk::Test; + + const MODULE: &str = "sdk-test-case-conversion"; + const CLIENT: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/case-conversion-client"); + + fn make_test(subcommand: &str) -> Test { + Test::builder() + .with_name(subcommand) + .with_module(MODULE) + .with_client(CLIENT) + .with_language("rust") + .with_bindings_dir("src/module_bindings") + .with_compile_command("cargo build") + .with_run_command(format!("cargo run -- {}", subcommand)) + .build() + } + + #[test] + fn insert_player() { + make_test("insert-player").run(); + } + + #[test] + fn insert_person() { + make_test("insert-person").run(); + } + + #[test] + fn ban_player() { + make_test("ban-player").run(); + } + + #[test] + fn query_builder_filter() { + make_test("query-builder-filter").run(); + } + + #[test] + fn query_builder_join() { + make_test("query-builder-join").run(); + } + + #[test] + fn query_view() { + make_test("view").run(); + } +} +/// Tests of case conversion using a TypeScript client against the Rust module `sdk-test-case-conversion`. +/// +/// Uses the TS client at `crates/bindings-typescript/case-conversion-test-client`. +/// Verifies that the TypeScript SDK correctly handles case-converted names from a Rust module: +/// - Table accessors, field names with digit boundaries, nested structs, enum variants +/// - Reducers with explicit names, query builder filters and joins +mod case_conversion_rust_ts_client { + use spacetimedb_testing::sdk::Test; + + const MODULE: &str = "sdk-test-case-conversion"; + const CLIENT: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../typescript/case-conversion-test-client" + ); + + fn make_test(subcommand: &str) -> Test { + Test::builder() + .with_name(subcommand) + .with_module(MODULE) + .with_client(CLIENT) + .with_language("typescript") + .with_bindings_dir("src/module_bindings") + .with_compile_command("sh -c 'pnpm install && pnpm run build'") + .with_run_command(format!("node dist/index.js {}", subcommand)) + .build() + } + + #[test] + fn insert_player() { + make_test("insert-player").run(); + } + + #[test] + fn insert_person() { + make_test("insert-person").run(); + } + + #[test] + fn ban_player() { + make_test("ban-player").run(); + } + + #[test] + fn query_builder_filter() { + make_test("query-builder-filter").run(); + } + + #[test] + fn query_builder_join() { + make_test("query-builder-join").run(); + } +}