diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c2cd75fb205..b21619a9c38 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1410,7 +1410,7 @@ jobs: # Create temp global.json to target .NET 8 SDK for workload install echo '{"sdk":{"version":"8.0.100","rollForward":"latestFeature"}}' > global.json dotnet workload install wasi-experimental - rm global.json + git restore -- global.json - name: Override NuGet packages run: | @@ -1430,9 +1430,9 @@ jobs: working-directory: sdks/csharp run: dotnet restore --configfile NuGet.Config SpacetimeDB.ClientSDK.sln - - name: Run .NET tests + - name: Run C# SDK tests working-directory: sdks/csharp - run: dotnet test -warnaserror --no-restore SpacetimeDB.ClientSDK.csproj + run: dotnet test -warnaserror --no-restore tests~/tests.csproj - name: Verify C# formatting working-directory: sdks/csharp diff --git a/Cargo.lock b/Cargo.lock index a13e6d9b3a2..7213d62f0b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8160,6 +8160,7 @@ dependencies = [ "spacetimedb-primitives", "spacetimedb-schema", "spacetimedb-testing", + "tempfile", ] [[package]] diff --git a/TESTING.md b/TESTING.md index ac090c4afab..e18a2f4a38b 100644 --- a/TESTING.md +++ b/TESTING.md @@ -97,6 +97,34 @@ of either the module libraries or client SDKs: 5. Repeat steps 2 through 4 for any other client projects which ought to cover the same behavior. 6. Run the new test with the relevant `cargo test` command for that SDK. +## C# namespace coverage + +The namespace tests are integration tests, plus focused generator diagnostics: + +- `dotnet test crates/bindings-csharp/Codegen.Tests -f net8.0` and + `-f net10.0`: existing Verify fixtures on both targets; .NET 10 additionally + checks mount restrictions, generated-name diagnostics, and dependency discovery. +- `cargo test -p spacetimedb-testing --test standalone_integration_test namespace_csharp`: + independent dependency publication, root export selection, and cross-namespace + helper/HTTP calls, and runtime name conversion compared with host validation. +- `cargo test -p spacetimedb-testing --test environment namespace_csharp_environment_security`: + root/public environment access, denial of namespaced host calls, and default + namespace case conversion when `Name` is omitted. +- `cargo test -p spacetimedb-codegen --test codegen`: codegen snapshots and a + generated C# client for a TypeScript submodule, including distinct accessor + and canonical names. +- The [namespace client regression](sdks/csharp/examples~/regression-tests/namespaces/README.md) + runs against the real .NET 10 module and covers tables, queries, subscriptions, + callbacks, scheduling, transactions, and root-defined RLS with + `Accessor = "MyAuth", Name = "auth_data"`. The existing + `sdks/csharp/tools~/run-regression-tests.sh 8 10` harness includes it in the + .NET 10 module pass while retaining .NET 8 regressions. + +Use the local package setup in [DEVELOP.md](sdks/csharp/DEVELOP.md), not stale +published NuGet packages, when exercising changed query/runtime code. +Library-defined RLS inside named namespaces and cross-language module composition +are unsupported, not integration cases awaiting a passing assertion. + ## Schema parity tests `crates/schema/tests/ensure_same_schema.rs` is a separate but important companion to the SDK tests. @@ -142,4 +170,4 @@ To add a new module library to the Standalone integration test suite: and so you are free to ignore them. 3. Modify `crates/testing/tests/standalone_integration_test.rs` to define new `#[test] #[serial]` test functions which use your new `module-test-XX` module to do the same operations as the existing tests. -4. Run the tests with `cargo test -p spacetimedb-testing --test standalone_integration_test`. \ No newline at end of file +4. Run the tests with `cargo test -p spacetimedb-testing --test standalone_integration_test`. diff --git a/crates/bindings-csharp/BSATN.Codegen/Type.cs b/crates/bindings-csharp/BSATN.Codegen/Type.cs index 537c1c9f2dc..ff0e4899ec5 100644 --- a/crates/bindings-csharp/BSATN.Codegen/Type.cs +++ b/crates/bindings-csharp/BSATN.Codegen/Type.cs @@ -470,7 +470,7 @@ INamedTypeSymbol type typeSyntax .Members.OfType() .SelectMany(f => f.Declaration.Variables) - .Select(v => type.GetMembers(v.Identifier.Text).OfType().Single()) + .Select(v => type.GetMembers(v.Identifier.ValueText).OfType().Single()) .Where(f => !f.IsStatic); public static IFieldSymbol? FindSpacetimeDbField(ITypeSymbol rowType, string fieldName) diff --git a/crates/bindings-csharp/BSATN.Runtime/BSATN/Runtime.cs b/crates/bindings-csharp/BSATN.Runtime/BSATN/Runtime.cs index e7519e22765..a6c573c4ed4 100644 --- a/crates/bindings-csharp/BSATN.Runtime/BSATN/Runtime.cs +++ b/crates/bindings-csharp/BSATN.Runtime/BSATN/Runtime.cs @@ -56,6 +56,12 @@ public interface IStructuralReadWrite /// /// /// +#if NET10_0_OR_GREATER + // Avoid an extra per-row call in NativeAOT scan iterators. + [System.Runtime.CompilerServices.MethodImpl( + System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining + )] +#endif static T Read(BinaryReader reader) where T : IStructuralReadWrite, new() { diff --git a/crates/bindings-csharp/BSATN.Runtime/QueryBuilder.cs b/crates/bindings-csharp/BSATN.Runtime/QueryBuilder.cs index e8d52a084e6..952c602f545 100644 --- a/crates/bindings-csharp/BSATN.Runtime/QueryBuilder.cs +++ b/crates/bindings-csharp/BSATN.Runtime/QueryBuilder.cs @@ -3,6 +3,30 @@ namespace SpacetimeDB; using System; using System.Globalization; +/// A table identifier with a separately quoted optional namespace and local name. +public readonly struct SqlTableName +{ + public string? Namespace { get; } + public string LocalName { get; } + + public SqlTableName(string localName) + { + LocalName = localName; + Namespace = null; + } + + public SqlTableName(string @namespace, string localName) + { + Namespace = @namespace ?? throw new ArgumentNullException(nameof(@namespace)); + LocalName = localName; + } + + public override string ToString() => + Namespace is null + ? SqlFormat.QuoteIdent(LocalName) + : SqlFormat.QuoteIdent(Namespace) + "." + SqlFormat.QuoteIdent(LocalName); +} + public readonly struct SqlLiteral { internal string Sql { get; } @@ -113,11 +137,13 @@ internal IxJoinEq(string leftRefSql, string rightRefSql) } } -public readonly struct Col(string tableName, string columnName) +public readonly struct Col(SqlTableName tableName, string columnName) where TValue : notnull { - internal string RefSql => - $"{SqlFormat.QuoteIdent(tableName)}.{SqlFormat.QuoteIdent(columnName)}"; + public Col(string tableName, string columnName) + : this(new SqlTableName(tableName), columnName) { } + + internal string RefSql => $"{tableName}.{SqlFormat.QuoteIdent(columnName)}"; public BoolExpr Eq(SqlLiteral value) => new($"({RefSql} = {value.Sql})"); @@ -146,11 +172,13 @@ public readonly struct Col(string tableName, string columnName) public override string ToString() => RefSql; } -public readonly struct IxCol(string tableName, string columnName) +public readonly struct IxCol(SqlTableName tableName, string columnName) where TValue : notnull { - internal string RefSql => - $"{SqlFormat.QuoteIdent(tableName)}.{SqlFormat.QuoteIdent(columnName)}"; + public IxCol(string tableName, string columnName) + : this(new SqlTableName(tableName), columnName) { } + + internal string RefSql => $"{tableName}.{SqlFormat.QuoteIdent(columnName)}"; public BoolExpr Eq(SqlLiteral value) => new($"({RefSql} = {value.Sql})"); @@ -162,16 +190,19 @@ public IxJoinEq Eq(IxCol other) = public override string ToString() => RefSql; } -public sealed class Table(string tableName, TCols cols, TIxCols ixCols) +public sealed class Table(SqlTableName tableName, TCols cols, TIxCols ixCols) : IQuery { - internal string TableRefSql => SqlFormat.QuoteIdent(tableName); + public Table(string tableName, TCols cols, TIxCols ixCols) + : this(new SqlTableName(tableName), cols, ixCols) { } + + internal string TableRefSql => tableName.ToString(); internal TCols Cols => cols; internal TIxCols IxCols => ixCols; - public string ToSql() => $"SELECT * FROM {SqlFormat.QuoteIdent(tableName)}"; + public string ToSql() => $"SELECT * FROM {TableRefSql}"; public FromWhere Where(Func predicate) => new(this, QueryPredicate.ToBoolExpr(predicate(cols)!)); diff --git a/crates/bindings-csharp/Codegen.Tests/Codegen.Tests.csproj b/crates/bindings-csharp/Codegen.Tests/Codegen.Tests.csproj index 0f7a1bfc47f..ee5a32e04ad 100644 --- a/crates/bindings-csharp/Codegen.Tests/Codegen.Tests.csproj +++ b/crates/bindings-csharp/Codegen.Tests/Codegen.Tests.csproj @@ -17,7 +17,6 @@ - @@ -26,6 +25,7 @@ + @@ -35,9 +35,10 @@ - - - + + + + diff --git a/crates/bindings-csharp/Codegen.Tests/EnvironmentTests.cs b/crates/bindings-csharp/Codegen.Tests/EnvironmentTests.cs index d3564f218ae..a609a4db9c9 100644 --- a/crates/bindings-csharp/Codegen.Tests/EnvironmentTests.cs +++ b/crates/bindings-csharp/Codegen.Tests/EnvironmentTests.cs @@ -162,7 +162,7 @@ public static void InvalidDeclarationsAreCompileErrors(string field) Assert.Contains( result.Diagnostics, diagnostic => - diagnostic.Id == "STDBENV001" && diagnostic.Severity == DiagnosticSeverity.Error + diagnostic.Id == "STDB0039" && diagnostic.Severity == DiagnosticSeverity.Error ); } diff --git a/crates/bindings-csharp/Codegen.Tests/TestInit.cs b/crates/bindings-csharp/Codegen.Tests/TestInit.cs index 17b229a8d75..e733c3aad52 100644 --- a/crates/bindings-csharp/Codegen.Tests/TestInit.cs +++ b/crates/bindings-csharp/Codegen.Tests/TestInit.cs @@ -3,10 +3,34 @@ namespace SpacetimeDB.Codegen.Tests; using System.Runtime.CompilerServices; using System.Text; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; // Global Verify setup for all tests we might have. static class TestInit { + internal static (string Code, IEnumerable Errors) FormatCode(string code) + { + var header = ""; + // CSharpier reorders conditional global imports below ordinary imports. + // Keep this already-formatted header intact and format the declarations only. + if (code.Contains("global using ")) + { + var root = CSharpSyntaxTree.ParseText(code).GetCompilationUnitRoot(); + var headerEnd = root.Usings.Last().FullSpan.End; + header = code[..headerEnd]; + code = code[headerEnd..]; + } + var result = CSharpier.Core.CSharp.CSharpFormatter.Format( + code, + new() { IncludeGenerated = true, EndOfLine = CSharpier.Core.EndOfLine.LF } + ); +#if NET10_0_OR_GREATER + return (header + result.Code, result.ErrorDiagnostics); +#else + return (header + result.Code, result.CompilationErrors); +#endif + } + // A custom Diagnostic converter that pretty-prints the error with the source code snippet and squiggly underline. // TODO: upstream this? class DiagConverter : WriteOnlyJsonConverter @@ -31,7 +55,7 @@ public override void Write(VerifyJsonWriter writer, Diagnostic diag) { var line = lines[lineIdx]; // print the source line - comment.AppendLine(line.ToString()); + comment.AppendLine(line.ToString().TrimEnd()); // print squiggly line highlighting the location if (line.Span.Intersection(loc.SourceSpan) is { } intersection) { @@ -73,17 +97,14 @@ public static void Initialize() { var unformattedCode = sb.ToString(); sb.Clear(); - var result = CSharpier.CodeFormatter.Format( - unformattedCode, - new() { IncludeGenerated = true, EndOfLine = CSharpier.EndOfLine.LF } - ); + var result = FormatCode(unformattedCode); sb.Append(result.Code); // Print errors in the end so that their line numbers are still meaningful. - if (result.CompilationErrors.Any()) + if (result.Errors.Any()) { sb.AppendLine(); sb.AppendLine("// Generated code produced compilation errors:"); - foreach (var diag in result.CompilationErrors) + foreach (var diag in result.Errors) { sb.Append("// ").AppendLine(diag.ToString()); } diff --git a/crates/bindings-csharp/Codegen.Tests/Tests.cs b/crates/bindings-csharp/Codegen.Tests/Tests.cs index 5ecccedb31b..5d24a28392b 100644 --- a/crates/bindings-csharp/Codegen.Tests/Tests.cs +++ b/crates/bindings-csharp/Codegen.Tests/Tests.cs @@ -20,6 +20,12 @@ namespace SpacetimeDB.Codegen.Tests; /// public static class GeneratorSnapshotTests { +#if NET10_0_OR_GREATER + private const string ModuleTargetFramework = "net10.0"; +#else + private const string ModuleTargetFramework = "net8.0"; +#endif + // Note that we can't use assembly path here because it will be put in some deep nested folder. // Instead, to get the test project directory, we can use the `CallerFilePath` attribute which will magically give us path to the current file. static string GetProjectDir([CallerFilePath] string path = "") => Path.GetDirectoryName(path)!; @@ -34,15 +40,34 @@ private class Fixture(string projectDir, CSharpCompilation sampleCompilation) public static async Task Compile(string name) { + var targetFramework = name == "client" ? "netstandard2.1" : ModuleTargetFramework; var projectDir = Path.Combine(GetProjectDir(), "fixtures", name); - using var workspace = MSBuildWorkspace.Create(); + using var workspace = MSBuildWorkspace.Create( + new Dictionary { ["TargetFramework"] = targetFramework } + ); var sampleProject = await workspace.OpenProjectAsync($"{projectDir}/{name}.csproj"); var compilation = await sampleProject.GetCompilationAsync(); return new(projectDir, (CSharpCompilation)compilation!); } - public Task Verify(string fileName, object target) => - Verifier.Verify(target).UseDirectory($"{projectDir}/snapshots").UseFileName(fileName); + public Task Verify(string fileName, object target) + { + if ( + ( + fileName == nameof(Module) + || fileName == nameof(EnvironmentGenerator) + || fileName == "ExtraCompilationErrors" + ) + && ModuleTargetFramework == "net10.0" + ) + { + fileName += ".net10"; + } + return Verifier + .Verify(target) + .UseDirectory($"{projectDir}/snapshots") + .UseFileName(fileName); + } private static CSharpGeneratorDriver CreateDriver( IIncrementalGenerator generator, @@ -170,30 +195,66 @@ static void AssertPublicBoundIsAvailableInRuntime(Compilation compilation) Assert.Equal(Accessibility.Public, bound!.DeclaredAccessibility); } - static void AssertRuntimeDoesNotDefineLocal(Compilation compilation) + static void AssertContextOwnership(Compilation compilation) { var runtimeAssembly = compilation - .References.Select(r => compilation.GetAssemblyOrModuleSymbol(r)) + .References.Select(compilation.GetAssemblyOrModuleSymbol) .OfType() .FirstOrDefault(a => a.Name == "SpacetimeDB.Runtime"); Assert.NotNull(runtimeAssembly); - // These types are generated per-module by SpacetimeDB.Codegen.Module. - // If Runtime defines any of them too, user projects can hit CS0436 warnings. - var codegenOwnedTypes = new[] + // Use the fixture's target, not the test host: the .NET 10 suite also compiles .NET 8 examples. + var sharedContexts = ( + (CSharpParseOptions)compilation.SyntaxTrees.First().Options + ).PreprocessorSymbolNames.Contains("NET10_0_OR_GREATER"); + foreach ( + var name in new[] + { + "SpacetimeDB.Local", + "SpacetimeDB.ReducerContext", + "SpacetimeDB.ProcedureContext", + "SpacetimeDB.ProcedureTxContext", + "SpacetimeDB.HandlerContext", + "SpacetimeDB.HandlerTxContext", + "SpacetimeDB.ViewContext", + "SpacetimeDB.AnonymousViewContext", + "SpacetimeDB.QueryBuilder", + } + ) + { + var runtimeType = runtimeAssembly!.GetTypeByMetadataName(name); + var generatedType = compilation.Assembly.GetTypeByMetadataName(name); + if (sharedContexts) + { + Assert.NotNull(runtimeType); + Assert.Equal(Accessibility.Public, runtimeType!.DeclaredAccessibility); + Assert.Null(generatedType); + } + else + { + Assert.Null(runtimeType); + Assert.NotNull(generatedType); + } + Assert.True( + SymbolEqualityComparer.Default.Equals( + sharedContexts ? runtimeType : generatedType, + compilation.GetTypeByMetadataName(name) + ), + $"{name} must resolve to its owning assembly without ambiguity." + ); + } + + // The legacy runtime shell remains on .NET 8, where generated code shadows it. + var readOnlyName = "SpacetimeDB.Internal.LocalReadOnly"; + Assert.NotNull(runtimeAssembly!.GetTypeByMetadataName(readOnlyName)); + if (sharedContexts) { - "SpacetimeDB.Local", - "SpacetimeDB.ProcedureContext", - "SpacetimeDB.ProcedureTxContext", - "SpacetimeDB.ReducerContext", - "SpacetimeDB.ViewContext", - "SpacetimeDB.AnonymousViewContext", - }; - - foreach (var name in codegenOwnedTypes) + Assert.Null(compilation.Assembly.GetTypeByMetadataName(readOnlyName)); + } + else { - Assert.Null(runtimeAssembly!.GetTypeByMetadataName(name)); + Assert.NotNull(compilation.Assembly.GetTypeByMetadataName(readOnlyName)); } } @@ -206,6 +267,264 @@ static void AssertNoCs0436Diagnostics(Compilation compilation) Assert.DoesNotContain(diagnostics, d => d.Id == "CS0436"); } +#if NET10_0_OR_GREATER + [Fact] + public static async Task NamespaceDeclarationsParseAndValidate() + { + var fixture = await Fixture.Compile("server"); + const string usings = + "global using System; global using System.IO; " + + "global using System.Collections.Generic; global using System.Linq;\n"; + CSharpCompilation Create( + string name, + string source, + params MetadataReference[] references + ) => + CSharpCompilation.Create( + name, + [CSharpSyntaxTree.ParseText(usings + source, fixture.ParseOptions)], + fixture.SampleCompilation.References.Concat(references), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); + MetadataReference Dependency(string name) + { + var compilation = Create( + name, + $$""" + namespace {{name}} { + public class Marker { } + [SpacetimeDB.Table(Accessor = "{{name}}Row")] + public partial struct Row { public uint Id; } + } + """ + ); + var driver = CSharpGeneratorDriver.Create( + [ + new Type().AsSourceGenerator(), + new Module().AsSourceGenerator(), + new EnvironmentGenerator().AsSourceGenerator(), + ], + parseOptions: fixture.ParseOptions + ); + driver.RunGeneratorsAndUpdateCompilation( + compilation, + out var output, + out var diagnostics + ); + Assert.Empty(diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error)); + using var dll = new MemoryStream(); + var emitted = output.Emit(dll); + Assert.True(emitted.Success, string.Join("\n", emitted.Diagnostics)); + return MetadataReference.CreateFromImage(dll.ToArray()); + } + var auth = Dependency("Auth"); + var audit = Dependency("Audit"); + string Mount( + string marker = "Auth.Marker", + string accessor = "MyAuth", + string? name = null + ) => + $"[assembly: SpacetimeDB.Namespace(typeof({marker}), Accessor = \"{accessor}\"{(name is null ? "" : ", Name = " + SymbolDisplay.FormatLiteral(name, true))})]\n"; + GeneratorDriver Run(string source) => + CSharpGeneratorDriver + .Create( + [new Module().AsSourceGenerator()], + parseOptions: fixture.ParseOptions, + driverOptions: new GeneratorDriverOptions( + IncrementalGeneratorOutputKind.None, + trackIncrementalGeneratorSteps: true + ) + ) + .RunGenerators(Create("Consumer", source, auth, audit)); + void Reject(string source, string message) + { + var diagnostics = Run(source).GetRunResult().Diagnostics; + Assert.Contains(diagnostics, d => d.GetMessage().Contains(message)); + Assert.All(diagnostics, d => Assert.True(d.Location.IsInSource, d.ToString())); + } + + object[] Parsed(GeneratorDriver driver) => + [ + .. driver + .GetRunResult() + .Results.Single() + .TrackedSteps["SpacetimeDB.Namespace.Parse"] + .Single() + .Outputs.SelectMany(o => + ((System.Collections.IEnumerable)o.Value).Cast() + ), + ]; + Assert.Empty(Run(Mount(accessor: new string('a', 63))).GetRunResult().Diagnostics); + Assert.Empty(Run(Mount(accessor: "public")).GetRunResult().Diagnostics); + Assert.Empty(Run(Mount(name: new string('a', 63))).GetRunResult().Diagnostics); + Assert.Empty(Run(Mount(accessor: "PUBLIC", name: "public")).GetRunResult().Diagnostics); + Assert.Empty(Run(Mount(name: "class")).GetRunResult().Diagnostics); + Reject(Mount(name: new string('a', 64)), "63 UTF-8 bytes"); + Reject(Mount(name: ""), "Name must be a nonempty database identifier"); + Reject(Mount(name: "st"), "reserved"); + Reject(Mount(accessor: "public", name: "auth_data"), "public scope"); + Reject(Mount(name: "PUBLIC"), "public scope"); + Reject(Mount(accessor: new string('a', 64)), "63 UTF-8 bytes"); + foreach (var name in new[] { "", "auth.data", "a-b", "1auth", " auth" }) + Reject(Mount(accessor: name), "database identifier"); + foreach (var name in new[] { "st", "ST", "spacetimedb", "pg_catalog", "PG_temp" }) + Reject(Mount(accessor: name), "reserved"); + foreach (var name in new[] { "GetType", "ToString", "Equals", "GetHashCode" }) + Reject(Mount(accessor: name), "receiver member"); + foreach (var accessor in new[] { "", "a.b", "a-b", "1auth", "@class", " auth" }) + Reject(Mount(accessor: accessor), "C# identifier"); + Reject("[assembly: SpacetimeDB.Namespace(typeof(Auth.Marker))]", "C# identifier"); + Reject("[assembly: SpacetimeDB.Namespace(null)]", "marker type"); + Reject(Mount("LocalMarker") + "public class LocalMarker { }", "cannot mount itself"); + Reject(Mount("System.String"), "no discovered module descriptor"); + Reject(Mount() + Mount(accessor: "Other"), "only be mounted once"); + Reject(Mount() + Mount("Audit.Marker", "MYAUTH"), "case-insensitive"); + Reject(Mount() + Mount("Audit.Marker", "MyAuth"), "accessor 'MyAuth'"); + Reject( + Mount() + + "[SpacetimeDB.Table(Accessor = \"MyAuth\")] public partial struct Row { public uint Id; }", + "root table accessor" + ); + + var oldLanguage = fixture.ParseOptions.WithLanguageVersion(LanguageVersion.CSharp13); + var oldCompilation = Create("Consumer", "", auth, audit) + .RemoveAllSyntaxTrees() + .AddSyntaxTrees(CSharpSyntaxTree.ParseText(usings + Mount(), oldLanguage)); + var oldResult = CSharpGeneratorDriver + .Create([new Module().AsSourceGenerator()], parseOptions: oldLanguage) + .RunGenerators(oldCompilation) + .GetRunResult(); + Assert.Contains( + oldResult.Diagnostics, + d => d.GetMessage().Contains("require .NET 10 and C# 14") + ); + + var original = Run(Mount()); + foreach ( + var source in new[] + { + Mount(accessor: "Other"), + Mount(accessor: "class"), + Mount(name: "auth_data"), + } + ) + { + var changed = original.RunGenerators(Create("Consumer", source, auth, audit)); + Assert.Empty(changed.GetRunResult().Diagnostics); + Assert.NotEqual(Assert.Single(Parsed(original)), Assert.Single(Parsed(changed))); + Assert.Contains( + changed + .GetRunResult() + .Results.Single() + .TrackedSteps["SpacetimeDB.Namespace.Parse"] + .SelectMany(s => s.Outputs), + o => o.Reason == IncrementalStepRunReason.Modified + ); + } + } + + [Fact] + public static async Task NamespaceGeneratedNameCollisions() + { + var fixture = await Fixture.Compile("server"); + (Compilation Output, ImmutableArray Diagnostics) Generate(string source) + { + var compilation = CSharpCompilation.Create( + "CollisionProof", + [ + CSharpSyntaxTree.ParseText( + "global using System; global using System.IO; global using System.Collections.Generic;\n" + + source, + fixture.ParseOptions + ), + ], + fixture.SampleCompilation.References, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); + CSharpGeneratorDriver + .Create( + [ + new Type().AsSourceGenerator(), + new Module().AsSourceGenerator(), + new EnvironmentGenerator().AsSourceGenerator(), + ], + parseOptions: fixture.ParseOptions + ) + .RunGeneratorsAndUpdateCompilation( + compilation, + out var output, + out var diagnostics + ); + return (output, diagnostics); + } + foreach ( + var (accessor, fields, symbol) in new[] + { + ("User", "[SpacetimeDB.Unique] public uint Count;", "Count"), + ( + "User", + "[SpacetimeDB.Unique] public uint Id; [SpacetimeDB.Unique] public uint __Id;", + "__Id" + ), + ( + "User", + "[SpacetimeDB.Unique] public uint Id; [SpacetimeDB.Unique] public uint IdUniqueIndex;", + "IdUniqueIndex" + ), + ("User", "public uint UserCols;", "UserCols"), + ("User", "[SpacetimeDB.PrimaryKey] public uint UserIxCols;", "UserIxCols"), + ("Tables", "public uint Id;", "Tables"), + ("ReadOnlyTables", "public uint Id;", "ReadOnlyTables"), + ("Queries", "public uint Id;", "Queries"), + ("GetType", "public uint Id;", "GetType"), + } + ) + { + var (_, diagnostics) = Generate( + $$""" + [SpacetimeDB.Table(Accessor = "{{accessor}}")] + public partial struct Row { {{fields}} } + """ + ); + Assert.DoesNotContain(diagnostics, d => d.Id == "CS8785"); + Assert.True( + diagnostics.Any(d => + d.GetMessage().Contains("Generated C# name") + && d.GetMessage().Contains(symbol) + && d.Location.IsInSource + ), + $"Expected collision for {accessor}.{symbol}: {string.Join("\n", diagnostics)}" + ); + } + var (_, crossTableDiagnostics) = Generate( + """ + [SpacetimeDB.Table(Accessor = "User")] + [SpacetimeDB.Table(Accessor = "UserIx")] + public partial struct Row { public uint Id; } + """ + ); + Assert.Contains( + crossTableDiagnostics, + d => + d.GetMessage().Contains("UserIxCols") + && d.GetMessage().Contains("table 'User'") + && d.GetMessage().Contains("table 'UserIx'") + ); + + var (valid, validDiagnostics) = Generate( + """ + [SpacetimeDB.Table(Accessor = "First")] + [SpacetimeDB.Table(Accessor = "Second")] + public partial struct Row { [SpacetimeDB.Unique] public uint @class; } + """ + ); + Assert.Empty(validDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error)); + using var dll = new MemoryStream(); + var emitted = valid.Emit(dll); + Assert.True(emitted.Success, string.Join("\n", emitted.Diagnostics)); + } +#endif + [Fact] public static async Task TypeGeneratorOnClient() { @@ -218,10 +537,439 @@ public static async Task TypeGeneratorOnClient() Assert.Empty(GetCompilationErrors(compilationAfterGen)); } +#if NET10_0_OR_GREATER + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public static async Task NamespaceDependenciesRegisterOnceInStableOrder( + bool rootHasTable, + bool mounted + ) + { + var fixture = await Fixture.Compile("server"); + const string usings = + "global using System; global using System.IO; " + + "global using System.Collections.Generic; global using System.Linq;\n"; + CSharpCompilation Create( + string name, + string source, + params MetadataReference[] references + ) => + CSharpCompilation.Create( + name, + [CSharpSyntaxTree.ParseText(usings + source, fixture.ParseOptions)], + fixture.SampleCompilation.References.Concat(references), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); + CSharpCompilation Generate(CSharpCompilation input) + { + var driver = CSharpGeneratorDriver.Create( + [ + new Type().AsSourceGenerator(), + new Module().AsSourceGenerator(), + new EnvironmentGenerator().AsSourceGenerator(), + ], + parseOptions: fixture.ParseOptions + ); + driver.RunGeneratorsAndUpdateCompilation(input, out var output, out var diagnostics); + Assert.Empty(diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error)); + Assert.Empty(GetCompilationErrors(output)); + return (CSharpCompilation)output; + } + MetadataReference Emit(CSharpCompilation compilation) + { + using var dll = new MemoryStream(); + var result = compilation.Emit(dll); + Assert.True(result.Success, string.Join("\n", result.Diagnostics)); + return MetadataReference.CreateFromImage(dll.ToArray()); + } + string Table(string name) => + $$""" + namespace {{name}} { + public class Sentinel { } + [SpacetimeDB.Table] + public partial struct {{name}}Row { public uint Id; } + } + """; + string Descriptor(CSharpCompilation compilation) => + Assert + .Single(compilation.GetSymbolsWithName("AssemblyDescriptor", SymbolFilter.Type)) + .ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + MethodDeclarationSyntax Method(CSharpCompilation compilation, string name) => + Assert.Single( + compilation + .SyntaxTrees.SelectMany(tree => tree.GetRoot().DescendantNodes()) + .OfType() + .Where(type => type.Identifier.ValueText == "ModuleRegistration") + .SelectMany(type => type.Members.OfType()) + .Where(method => method.Identifier.ValueText == name) + ); + + var sharedCompilation = Generate(Create("Shared", Table("Shared"))); + var shared = Emit(sharedCompilation); + var alphaCompilation = Generate( + Create( + "Alpha", + Table("Alpha") + "public class AlphaLink { public Shared.Sentinel Value; }", + shared + ) + ); + var alpha = Emit(alphaCompilation); + var betaCompilation = Generate( + Create( + "Beta", + Table("Beta") + "public class BetaLink { public Shared.Sentinel Value; }", + shared + ) + ); + var beta = Emit(betaCompilation); + var utility = Emit( + Create("Utility", "public class UtilityLink { public Shared.Sentinel Value; }", shared) + ); + var rootSource = rootHasTable ? Table("Root") : ""; + if (mounted) + { + rootSource = + "[assembly: SpacetimeDB.Namespace(typeof(Alpha.Sentinel), Accessor = \"Auth\")]\n" + + "[assembly: SpacetimeDB.Namespace(typeof(Beta.Sentinel), Accessor = \"class\")]\n" + + rootSource; + } + + var root = Generate(Create("Root", rootSource, beta, utility, shared, alpha)); + var reordered = Generate(Create("Root", rootSource, alpha, shared, utility, beta)); + + string[] Calls(CSharpCompilation compilation) => + [ + .. Method(compilation, "Initialize") + .DescendantNodes() + .OfType() + .Select(call => call.Expression.ToString()) + .Where(call => call.EndsWith(".Register")), + ]; + CSharpCompilation[] orderedDependencies = mounted + ? [sharedCompilation, alphaCompilation, betaCompilation] + : [alphaCompilation, betaCompilation, sharedCompilation]; + var expected = new[] { Descriptor(root) + ".Register" } + .Concat(orderedDependencies.Select(c => Descriptor(c) + ".Register")) + .ToArray(); + if (mounted) + { + var init = Method(root, "Initialize"); + var submodules = init.DescendantNodes() + .OfType() + .Where(call => call.Expression.ToString().EndsWith(".RegisterSubmodule")) + .ToArray(); + Assert.Equal( + ["\"Auth\"", "\"class\""], + submodules.Select(call => call.ArgumentList.Arguments[0].ToString()) + ); + } + Assert.Equal(expected, Calls(root)); + Assert.Equal(expected, Calls(reordered)); + + if (rootHasTable || mounted) + { + return; + } + + foreach (var accessor in new[] { "public", "PUBLIC" }) + { + var publicConsumer = Generate( + Create( + "PublicAccessorConsumer", + $$""" + [assembly: SpacetimeDB.Namespace(typeof(Alpha.Sentinel), Accessor = "{{accessor}}")] + public static class Helpers { + public static void Insert(SpacetimeDB.ReducerContext ctx) => + ctx.Db.AlphaRow.Insert(new Alpha.AlphaRow { Id = 1 }); + public static ulong Count(SpacetimeDB.ViewContext ctx) => ctx.Db.AlphaRow.Count; + public static ulong Count(SpacetimeDB.AnonymousViewContext ctx) => ctx.Db.AlphaRow.Count; + public static SpacetimeDB.IQuery Query(SpacetimeDB.ViewContext ctx) => + ctx.From.AlphaRow(); + public static SpacetimeDB.IQuery Query(SpacetimeDB.AnonymousViewContext ctx) => + ctx.From.AlphaRow(); + } + """, + alpha, + shared + ) + ); + Assert.Equal( + new[] + { + Descriptor(publicConsumer) + ".Register", + Descriptor(alphaCompilation) + ".Register", + Descriptor(sharedCompilation) + ".Register", + }, + Calls(publicConsumer) + ); + Assert.DoesNotContain( + "RegisterSubmodule", + Method(publicConsumer, "Initialize").ToString() + ); + } + + string HttpModule(string name) => + $$""" + namespace {{name}}Module { + using SpacetimeDB; + public static partial class Functions { + [HttpHandler] + public static HttpResponse {{name}}(HandlerContext ctx, HttpRequest request) => + throw new Exception(); + [HttpRouter] + public static Router Routes() => Router.New() + .Get("/short", Handlers.{{name}}) + .Get("/qualified", global::SpacetimeDB.Handlers.{{name}}); + } + } + """; + // The library references a table-only module, which also generates a Handlers container. + var httpLibrary = Emit( + Generate(Create("HttpLibrary", HttpModule("LibraryHandler"), alpha, shared)) + ); + Generate(Create("HttpConsumer", HttpModule("RootHandler"), httpLibrary, alpha, shared)); + + string Policy(string? policy) => + policy is null + ? "" + : $$""" + public static class NamingSettings { + [SpacetimeDB.Settings] + public const SpacetimeDB.CaseConversionPolicy Naming = SpacetimeDB.CaseConversionPolicy.{{policy}}; + } + """; + foreach ( + var (rootPolicy, dependencyPolicy) in new (string?, string?)[] + { + ("SnakeCase", "None"), + (null, "None"), + ("None", "SnakeCase"), + ("None", "None"), + ("SnakeCase", "SnakeCase"), + (null, "SnakeCase"), + ("None", null), + } + ) + { + var dependency = Emit( + Generate( + Create("PolicyDependency", Table("PolicyDependency") + Policy(dependencyPolicy)) + ) + ); + foreach (var mount in new[] { "", "public", "Named" }) + { + var source = + ( + mount.Length == 0 + ? "" + : $"[assembly: SpacetimeDB.Namespace(typeof(PolicyDependency.Sentinel), Accessor = \"{mount}\")]\n" + ) + Policy(rootPolicy); + var compilation = Create("PolicyConsumer", source, dependency); + if ( + mount != "Named" + && dependencyPolicy is not null + && dependencyPolicy != (rootPolicy ?? "SnakeCase") + ) + { + var result = CSharpGeneratorDriver + .Create( + [new Module().AsSourceGenerator()], + parseOptions: fixture.ParseOptions + ) + .RunGenerators(compilation) + .GetRunResult(); + Assert.Contains( + result.Diagnostics, + diagnostic => + diagnostic.Severity == DiagnosticSeverity.Error + && diagnostic.Descriptor.Title.ToString() + == "Conflicting case conversion policies" + && diagnostic.GetMessage().Contains("PolicyConsumer") + && diagnostic.GetMessage().Contains("PolicyDependency") + && diagnostic.GetMessage().Contains("SnakeCase") + && diagnostic.GetMessage().Contains("None") + ); + } + else + { + Generate(compilation); + } + } + } + + // An unrelated utility alone must not cause an otherwise empty module to register. + var plainUtility = Emit(Create("PlainUtility", "public class PlainUtility { }")); + var empty = Generate(Create("Empty", "", plainUtility)); + Assert.Empty(empty.GetSymbolsWithName("AssemblyDescriptor", SymbolFilter.Type)); + + var nested = Emit( + Generate( + Create( + "Nested", + "[assembly: SpacetimeDB.Namespace(typeof(Alpha.Sentinel), Accessor = \"Auth\")]", + alpha, + shared + ) + ) + ); + var nestedResult = CSharpGeneratorDriver + .Create([new Module().AsSourceGenerator()], parseOptions: fixture.ParseOptions) + .RunGenerators(Create("Outer", "", nested, alpha, shared)) + .GetRunResult(); + Assert.Contains( + nestedResult.Diagnostics, + diagnostic => diagnostic.GetMessage().Contains("Only the consuming root") + ); + + foreach (var kind in new[] { "Init", "ClientConnected", "ClientDisconnected" }) + { + var lifecycle = Emit( + Generate( + Create( + "LifecycleDependency", + $$""" + public class Marker { } + public static partial class LifecycleFunctions { + [SpacetimeDB.Reducer(SpacetimeDB.ReducerKind.{{kind}})] + public static void Handle(SpacetimeDB.ReducerContext ctx) { } + } + """ + ) + ) + ); + var lifecycleResult = CSharpGeneratorDriver + .Create([new Module().AsSourceGenerator()], parseOptions: fixture.ParseOptions) + .RunGenerators( + Create( + "LifecycleConsumer", + "[assembly: SpacetimeDB.Namespace(typeof(Marker), Accessor = \"Auth\")]", + lifecycle + ) + ) + .GetRunResult(); + Assert.Contains( + lifecycleResult.Diagnostics, + diagnostic => + diagnostic.Severity == DiagnosticSeverity.Error + && diagnostic.Descriptor.Title.ToString() + == "Root-only declarations in mounted dependency" + && diagnostic.GetMessage().Contains("LifecycleFunctions.Handle (" + kind + ")") + && diagnostic.GetMessage().Contains("Auth") + ); + // The same dependency can still be published alone or merged into the root scope. + Generate(Create("FlatLifecycleConsumer", "", lifecycle)); + Generate( + Create( + "PublicLifecycleConsumer", + "[assembly: SpacetimeDB.Namespace(typeof(Marker), Accessor = \"public\")]", + lifecycle + ) + ); + } + + foreach ( + var (source, declaration) in new[] + { + ( + "#pragma warning disable STDB_UNSTABLE\n" + + """ + public static class Rules { + [SpacetimeDB.ClientVisibilityFilter] + public static readonly SpacetimeDB.Filter Visible = + new SpacetimeDB.Filter.Sql("SELECT * FROM Entry"); + } + """, + "row-level security filters" + ), + ( + "[SpacetimeDB.Env] public struct Settings { public string SECRET; }", + "environment variables" + ), + } + ) + { + // These declarations must register even without tables or functions in the assembly. + var dependencyCompilation = Generate( + Create("RestrictedDependency", source + "\npublic class Entry { }") + ); + var dependencyDescriptor = Descriptor(dependencyCompilation); + var dependency = Emit(dependencyCompilation); + if (declaration == "row-level security filters") + { + Assert.Contains( + Method(dependencyCompilation, "Register") + .DescendantNodes() + .OfType(), + call => + call.Expression.ToString() == "builder.RegisterClientVisibilityFilter" + && call.ArgumentList.Arguments.Single().ToString() + == "global::Rules.Visible" + ); + } + var result = CSharpGeneratorDriver + .Create([new Module().AsSourceGenerator()], parseOptions: fixture.ParseOptions) + .RunGenerators( + Create( + "RestrictedConsumer", + "[assembly: SpacetimeDB.Namespace(typeof(Entry), Accessor = \"Auth\")]", + dependency + ) + ) + .GetRunResult(); + Assert.Contains( + result.Diagnostics, + diagnostic => + diagnostic.Severity == DiagnosticSeverity.Error + && diagnostic.GetMessage().Contains("RestrictedDependency") + && diagnostic.GetMessage().Contains("'Auth'") + && diagnostic.GetMessage().Contains(declaration) + && diagnostic.GetMessage().Contains("root scope") + ); + foreach ( + var mount in new[] + { + "", + "[assembly: SpacetimeDB.Namespace(typeof(Entry), Accessor = \"public\")]", + } + ) + { + var consumer = Generate(Create("PublicConsumer", mount, dependency)); + Assert.Equal( + new[] + { + Descriptor(consumer) + ".Register", + dependencyDescriptor + ".Register", + }, + Calls(consumer) + ); + } + } + + // Empty environment schemas contain no keys and are permitted by the host. + var emptyEnvironment = Emit( + Generate(Create("EmptyEnvironment", "[SpacetimeDB.Env] public struct Settings { }")) + ); + Generate( + Create( + "EmptyEnvironmentConsumer", + "[assembly: SpacetimeDB.Namespace(typeof(Settings), Accessor = \"Auth\")]", + emptyEnvironment + ) + ); + } +#endif + [Fact] public static async Task TypeAndModuleGeneratorsOnServer() { var fixture = await Fixture.Compile("server"); + await fixture.Verify( + nameof(EnvironmentGenerator), + fixture.RunGeneratorAndGetResult(new EnvironmentGenerator()) + ); var compilationAfterGen = await fixture.RunAndCheckGenerators( new SpacetimeDB.Codegen.Type(), @@ -231,7 +979,7 @@ public static async Task TypeAndModuleGeneratorsOnServer() Assert.Empty(GetCompilationErrors(compilationAfterGen)); AssertPublicBoundIsAvailableInRuntime(compilationAfterGen); - AssertRuntimeDoesNotDefineLocal(compilationAfterGen); + AssertContextOwnership(compilationAfterGen); AssertGeneratedCodeDoesNotUseInternalBound(compilationAfterGen); // Regression guard for user-reported warning spam: @@ -256,7 +1004,7 @@ public static async Task SettingsAndExplicitNames() Assert.Empty(GetCompilationErrors(compilationAfterGen)); AssertPublicBoundIsAvailableInRuntime(compilationAfterGen); - AssertRuntimeDoesNotDefineLocal(compilationAfterGen); + AssertContextOwnership(compilationAfterGen); AssertGeneratedCodeDoesNotUseInternalBound(compilationAfterGen); } @@ -368,7 +1116,7 @@ public static async Task TestDiagnostics() await fixture.Verify("ExtraCompilationErrors", GetCompilationErrors(compilationAfterGen)); AssertPublicBoundIsAvailableInRuntime(compilationAfterGen); - AssertRuntimeDoesNotDefineLocal(compilationAfterGen); + AssertContextOwnership(compilationAfterGen); AssertGeneratedCodeDoesNotUseInternalBound(compilationAfterGen); } diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomClass.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomClass.verified.cs index c3ddd0f9ac9..0197c0b0e66 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomClass.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomClass.verified.cs @@ -48,7 +48,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new SpacetimeDB.BSATN.AggregateElement[] { new("IntField", IntFieldRW.GetAlgebraicType(registrar)), - new("StringField", StringFieldRW.GetAlgebraicType(registrar)) + new("StringField", StringFieldRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomStruct.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomStruct.verified.cs index 4730a9cb550..f7b28a0e3fc 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomStruct.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomStruct.verified.cs @@ -50,7 +50,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new SpacetimeDB.BSATN.AggregateElement[] { new("IntField", IntFieldRW.GetAlgebraicType(registrar)), - new("StringField", StringFieldRW.GetAlgebraicType(registrar)) + new("StringField", StringFieldRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomTaggedEnum.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomTaggedEnum.verified.cs index 0f6a93c3c41..b63a76c9365 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomTaggedEnum.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#CustomTaggedEnum.verified.cs @@ -27,10 +27,9 @@ public CustomTaggedEnum Read(System.IO.BinaryReader reader) { 0 => new IntVariant(IntVariantRW.Read(reader)), 1 => new StringVariant(StringVariantRW.Read(reader)), - _ - => throw new System.InvalidOperationException( - "Invalid tag value, this state should be unreachable." - ) + _ => throw new System.InvalidOperationException( + "Invalid tag value, this state should be unreachable." + ), }; } @@ -56,7 +55,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new SpacetimeDB.BSATN.AggregateElement[] { new("IntVariant", IntVariantRW.GetAlgebraicType(registrar)), - new("StringVariant", StringVariantRW.GetAlgebraicType(registrar)) + new("StringVariant", StringVariantRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#PublicTable.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#PublicTable.verified.cs index e447adafb6e..630d6c9c7db 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#PublicTable.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/client/snapshots/Type#PublicTable.verified.cs @@ -157,7 +157,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new( "NullableReferenceField", NullableReferenceFieldRW.GetAlgebraicType(registrar) - ) + ), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/ExtraCompilationErrors.net10.verified.txt b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/ExtraCompilationErrors.net10.verified.txt new file mode 100644 index 00000000000..e6f8b198379 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/ExtraCompilationErrors.net10.verified.txt @@ -0,0 +1,738 @@ +[ + {/* + { + ctx.GetIdentity(); + ^^^^^^^^^^^ + return null; +*/ + Message: 'AnonymousViewContext' does not contain a definition for 'GetIdentity' and no accessible extension method 'GetIdentity' accepting a first argument of type 'AnonymousViewContext' could be found (are you missing a using directive or an assembly reference?), + Severity: Error, + Descriptor: { + Id: CS1061, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS1061), + MessageFormat: '{0}' does not contain a definition for '{1}' and no accessible extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?), + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + + builder.RegisterClientVisibilityFilter(global::Module.MY_FILTER); + ^^^^^^^^^ + builder.RegisterClientVisibilityFilter(global::Module.MY_FOURTH_FILTER); +*/ + Message: 'Module.MY_FILTER' is inaccessible due to its protection level, + Severity: Error, + Descriptor: { + Id: CS0122, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0122), + MessageFormat: '{0}' is inaccessible due to its protection level, + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + ctx.Db.Player.Identity.Delete(0); + ^^^^^^ + return null; +*/ + Message: 'PlayerReadOnly.IdentityIndex' does not contain a definition for 'Delete' and no accessible extension method 'Delete' accepting a first argument of type 'PlayerReadOnly.IdentityIndex' could be found (are you missing a using directive or an assembly reference?), + Severity: Error, + Descriptor: { + Id: CS1061, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS1061), + MessageFormat: '{0}' does not contain a definition for '{1}' and no accessible extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?), + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + ctx.Db.Player.Delete(new Player { Identity = new() }); + ^^^^^^ + return null; +*/ + Message: 'PlayerReadOnly' does not contain a definition for 'Delete' and no accessible extension method 'Delete' accepting a first argument of type 'PlayerReadOnly' could be found (are you missing a using directive or an assembly reference?), + Severity: Error, + Descriptor: { + Id: CS1061, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS1061), + MessageFormat: '{0}' does not contain a definition for '{1}' and no accessible extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?), + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + ctx.Db.Player.Insert(new Player { Identity = new() }); + ^^^^^^ + return new Player { Identity = new() }; +*/ + Message: 'PlayerReadOnly' does not contain a definition for 'Insert' and no accessible extension method 'Insert' accepting a first argument of type 'PlayerReadOnly' could be found (are you missing a using directive or an assembly reference?), + Severity: Error, + Descriptor: { + Id: CS1061, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS1061), + MessageFormat: '{0}' does not contain a definition for '{1}' and no accessible extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?), + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + return ctx.Db.Player.Iter(); + ^^^^ + } +*/ + Message: 'PlayerReadOnly' does not contain a definition for 'Iter' and no accessible extension method 'Iter' accepting a first argument of type 'PlayerReadOnly' could be found (are you missing a using directive or an assembly reference?), + Severity: Error, + Descriptor: { + Id: CS1061, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS1061), + MessageFormat: '{0}' does not contain a definition for '{1}' and no accessible extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?), + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + ctx.Db.Player.Iter(); + ^^^^ + return null; +*/ + Message: 'PlayerReadOnly' does not contain a definition for 'Iter' and no accessible extension method 'Iter' accepting a first argument of type 'PlayerReadOnly' could be found (are you missing a using directive or an assembly reference?), + Severity: Error, + Descriptor: { + Id: CS1061, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS1061), + MessageFormat: '{0}' does not contain a definition for '{1}' and no accessible extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?), + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + // Valid Filter, but [ClientVisibilityFilter] is disabled + [SpacetimeDB.ClientVisibilityFilter] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + public static readonly Filter MY_FOURTH_FILTER = new Filter.Sql( +*/ + Message: 'SpacetimeDB.ClientVisibilityFilterAttribute' is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed., + Severity: Error, + Descriptor: { + Id: STDB_UNSTABLE, + Title: Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed., + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS9204), + MessageFormat: '{0}' is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed., + Category: Compiler, + DefaultSeverity: Warning, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + CustomObsolete + ] + } + }, + {/* + +partial struct TestTypeParams : System.IEquatable, SpacetimeDB.BSATN.IStructuralReadWrite { + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +*/ + Message: 'TestTypeParams' does not implement interface member 'IEquatable.Equals(TestTypeParams?)', + Severity: Error, + Descriptor: { + Id: CS0535, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0535), + MessageFormat: '{0}' does not implement interface member '{1}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* +var ___hashUnsupportedSystemType = UnsupportedSystemType == null ? 0 : UnsupportedSystemType.GetHashCode(); +var ___hashUnresolvedType = UnresolvedType == null ? 0 : UnresolvedType.GetHashCode(); + ^^^^^^^^^^^ +var ___hashUnsupportedEnum = UnsupportedEnum.GetHashCode(); +*/ + Message: 'UnresolvedType' does not contain a definition for 'GetHashCode' and no accessible extension method 'GetHashCode' accepting a first argument of type 'UnresolvedType' could be found (are you missing a using directive or an assembly reference?), + Severity: Error, + Descriptor: { + Id: CS1061, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS1061), + MessageFormat: '{0}' does not contain a definition for '{1}' and no accessible extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?), + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* +[SpacetimeDB.Table] +public partial struct TestDefaultFieldValues + ^^^^^^^^^^^^^^^^^^^^^^ +{ +*/ + Message: A 'struct' with field initializers must include an explicitly declared constructor., + Severity: Error, + Descriptor: { + Id: CS8983, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS8983), + MessageFormat: A 'struct' with field initializers must include an explicitly declared constructor., + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + var tableName = TestDuplicateTableNameSqlNameCache.Name; + ^^^^ + return new(tableName, new TestDuplicateTableNameCols(tableName), new TestDuplicateTableNameIxCols(tableName)); +*/ + Message: Ambiguity between 'AssemblyDescriptor.TestDuplicateTableNameSqlNameCache.Name' and 'AssemblyDescriptor.TestDuplicateTableNameSqlNameCache.Name', + Severity: Error, + Descriptor: { + Id: CS0229, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0229), + MessageFormat: Ambiguity between '{0}' and '{1}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + var tableName = TestDuplicateTableNameSqlNameCache.Name; + ^^^^ + return new(tableName, new TestDuplicateTableNameCols(tableName), new TestDuplicateTableNameIxCols(tableName)); +*/ + Message: Ambiguity between 'AssemblyDescriptor.TestDuplicateTableNameSqlNameCache.Name' and 'AssemblyDescriptor.TestDuplicateTableNameSqlNameCache.Name', + Severity: Error, + Descriptor: { + Id: CS0229, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0229), + MessageFormat: Ambiguity between '{0}' and '{1}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + + var returnValue = Module.ViewDefWrongContext((SpacetimeDB.ViewContext)ctx); + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + var listSerializer = new SpacetimeDB.BSATN.List(); +*/ + Message: Argument 1: cannot convert from 'SpacetimeDB.ViewContext' to 'SpacetimeDB.ReducerContext', + Severity: Error, + Descriptor: { + Id: CS1503, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS1503), + MessageFormat: Argument {0}: cannot convert from '{1}' to '{2}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + builder.RegisterClientVisibilityFilter(global::Module.MY_SECOND_FILTER); + builder.RegisterClientVisibilityFilter(global::Module.MY_THIRD_FILTER); + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + { +*/ + Message: Argument 1: cannot convert from 'string' to 'SpacetimeDB.Filter', + Severity: Error, + Descriptor: { + Id: CS1503, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS1503), + MessageFormat: Argument {0}: cannot convert from '{1}' to '{2}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + return ctx.Db.TestIndexIssues.TestUnexpectedColumns.Filter(0); + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + } +*/ + Message: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?), + Severity: Error, + Descriptor: { + Id: CS0266, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0266), + MessageFormat: Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?), + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + + var returnValue = Module.ViewDefNoContext((SpacetimeDB.ViewContext)ctx); + ^^^^^^^^^^^^^^^^ + var listSerializer = new SpacetimeDB.BSATN.List(); +*/ + Message: No overload for method 'ViewDefNoContext' takes 1 arguments, + Severity: Error, + Descriptor: { + Id: CS1501, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS1501), + MessageFormat: No overload for method '{0}' takes {1} arguments, + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + public global::SpacetimeDB.Table TestDuplicateTableName() => new AssemblyDescriptor.Queries().TestDuplicateTableName(); + ^^^^^^^^^^^^^^^^^^^^^^ + } +*/ + Message: The call is ambiguous between the following methods or properties: 'SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.Queries.TestDuplicateTableName() [{ProjectDirectory}fixtures/diag/SpacetimeDB.Codegen/SpacetimeDB.Codegen.Module/FFI.cs(809)]' and 'SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.Queries.TestDuplicateTableName() [{ProjectDirectory}fixtures/diag/SpacetimeDB.Codegen/SpacetimeDB.Codegen.Module/FFI.cs(1031)]', + Severity: Error, + Descriptor: { + Id: CS0121, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0121), + MessageFormat: The call is ambiguous between the following methods or properties: '{0}' and '{1}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + public global::SpacetimeDB.Table TestDuplicateTableName() => new AssemblyDescriptor.Queries().TestDuplicateTableName(); + ^^^^^^^^^^^^^^^^^^^^^^ + } +*/ + Message: The call is ambiguous between the following methods or properties: 'SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.Queries.TestDuplicateTableName() [{ProjectDirectory}fixtures/diag/SpacetimeDB.Codegen/SpacetimeDB.Codegen.Module/FFI.cs(809)]' and 'SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.Queries.TestDuplicateTableName() [{ProjectDirectory}fixtures/diag/SpacetimeDB.Codegen/SpacetimeDB.Codegen.Module/FFI.cs(1031)]', + Severity: Error, + Descriptor: { + Id: CS0121, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0121), + MessageFormat: The call is ambiguous between the following methods or properties: '{0}' and '{1}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + } + public readonly struct TestDuplicateTableNameCols + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + { +*/ + Message: The namespace 'SpacetimeDB.Generated.diag_4F830E2879BB50E3' already contains a definition for 'TestDuplicateTableNameCols', + Severity: Error, + Descriptor: { + Id: CS0101, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0101), + MessageFormat: The namespace '{1}' already contains a definition for '{0}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + + public readonly struct TestDuplicateTableNameIxCols + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + { +*/ + Message: The namespace 'SpacetimeDB.Generated.diag_4F830E2879BB50E3' already contains a definition for 'TestDuplicateTableNameIxCols', + Severity: Error, + Descriptor: { + Id: CS0101, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0101), + MessageFormat: The namespace '{1}' already contains a definition for '{0}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + private static class TestDuplicateTableNameSqlNameCache + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + { +*/ + Message: The type 'AssemblyDescriptor' already contains a definition for 'TestDuplicateTableNameSqlNameCache', + Severity: Error, + Descriptor: { + Id: CS0102, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0102), + MessageFormat: The type '{0}' already contains a definition for '{1}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + Params: [], + ReturnType: new SpacetimeDB.BSATN.ValueOption().GetAlgebraicType(registrar) + ^^^^^ +); +*/ + Message: The type name 'BSATN' does not exist in the type 'NotSpacetimeType', + Severity: Error, + Descriptor: { + Id: CS0426, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0426), + MessageFormat: The type name '{0}' does not exist in the type '{1}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + var returnValue = Module.ViewDefReturnsNotASpacetimeType((SpacetimeDB.AnonymousViewContext)ctx); + var listSerializer = SpacetimeDB.BSATN.ValueOption.GetListSerializer(); + ^^^^^ + var listValue = ModuleRegistration.ToListOrEmpty(returnValue); +*/ + Message: The type name 'BSATN' does not exist in the type 'NotSpacetimeType', + Severity: Error, + Descriptor: { + Id: CS0426, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0426), + MessageFormat: The type name '{0}' does not exist in the type '{1}', + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + internal static readonly TRW FieldRW = new(); + ^^^ + +*/ + Message: The type or namespace name 'TRW' could not be found (are you missing a using directive or an assembly reference?), + Severity: Error, + Descriptor: { + Id: CS0246, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0246), + MessageFormat: The type or namespace name '{0}' could not be found (are you missing a using directive or an assembly reference?), + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + public Exception UnsupportedSystemType; + public UnresolvedType UnresolvedType; + ^^^^^^^^^^^^^^ + public LocalEnum UnsupportedEnum; +*/ + Message: The type or namespace name 'UnresolvedType' could not be found (are you missing a using directive or an assembly reference?), + Severity: Error, + Descriptor: { + Id: CS0246, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0246), + MessageFormat: The type or namespace name '{0}' could not be found (are you missing a using directive or an assembly reference?), + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + public global::SpacetimeDB.Table TestDuplicateTableName() + ^^^^^^^^^^^^^^^^^^^^^^ + { +*/ + Message: Type 'AssemblyDescriptor.Queries' already defines a member called 'TestDuplicateTableName' with the same parameter types, + Severity: Error, + Descriptor: { + Id: CS0111, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0111), + MessageFormat: Type '{1}' already defines a member called '{0}' with the same parameter types, + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + // Prevent eager initialization before the root installs namespace placements. + static TestDuplicateTableNameSqlNameCache() { } + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + } +*/ + Message: Type 'AssemblyDescriptor.TestDuplicateTableNameSqlNameCache' already defines a member called 'TestDuplicateTableNameSqlNameCache' with the same parameter types, + Severity: Error, + Descriptor: { + Id: CS0111, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0111), + MessageFormat: Type '{1}' already defines a member called '{0}' with the same parameter types, + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + { + public global::SpacetimeDB.Table TestDuplicateTableName() => new AssemblyDescriptor.Queries().TestDuplicateTableName(); + ^^^^^^^^^^^^^^^^^^^^^^ + } +*/ + Message: Type 'QueryTableExtensions' already defines a member called 'TestDuplicateTableName' with the same parameter types, + Severity: Error, + Descriptor: { + Id: CS0111, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0111), + MessageFormat: Type '{1}' already defines a member called '{0}' with the same parameter types, + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + + internal TestDuplicateTableNameCols(global::SpacetimeDB.SqlTableName tableName) + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + { +*/ + Message: Type 'TestDuplicateTableNameCols' already defines a member called 'TestDuplicateTableNameCols' with the same parameter types, + Severity: Error, + Descriptor: { + Id: CS0111, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0111), + MessageFormat: Type '{1}' already defines a member called '{0}' with the same parameter types, + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + + internal TestDuplicateTableNameIxCols(global::SpacetimeDB.SqlTableName tableName) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + { +*/ + Message: Type 'TestDuplicateTableNameIxCols' already defines a member called 'TestDuplicateTableNameIxCols' with the same parameter types, + Severity: Error, + Descriptor: { + Id: CS0111, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0111), + MessageFormat: Type '{1}' already defines a member called '{0}' with the same parameter types, + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + }, + {/* + +partial struct TestTypeParams : System.IEquatable, SpacetimeDB.BSATN.IStructuralReadWrite { + ^^^^^^^^^^^^^^ + +*/ + Message: Using the generic type 'TestTypeParams' requires 1 type arguments, + Severity: Error, + Descriptor: { + Id: CS0305, + Title: , + HelpLink: https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0305), + MessageFormat: Using the generic {1} '{0}' requires {2} type arguments, + Category: Compiler, + DefaultSeverity: Error, + IsEnabledByDefault: true, + CustomTags: [ + Compiler, + Telemetry, + NotConfigurable + ] + } + } +] \ No newline at end of file diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/ExtraCompilationErrors.verified.txt b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/ExtraCompilationErrors.verified.txt index 8d65f041f30..e3c89b1d9d8 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/ExtraCompilationErrors.verified.txt +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/ExtraCompilationErrors.verified.txt @@ -23,10 +23,10 @@ } }, {/* - - SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_FILTER); - ^^^^^^^^^ -SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_FOURTH_FILTER); + + builder.RegisterClientVisibilityFilter(global::Module.MY_FILTER); + ^^^^^^^^^ + builder.RegisterClientVisibilityFilter(global::Module.MY_FOURTH_FILTER); */ Message: 'Module.MY_FILTER' is inaccessible due to its protection level, Severity: Error, @@ -253,7 +253,7 @@ public partial struct TestDefaultFieldValues } }, {/* - + var returnValue = Module.ViewDefWrongContext((SpacetimeDB.ViewContext)ctx); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ var listSerializer = new SpacetimeDB.BSATN.List(); @@ -276,9 +276,9 @@ public partial struct TestDefaultFieldValues } }, {/* -SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_SECOND_FILTER); -SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_THIRD_FILTER); - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + builder.RegisterClientVisibilityFilter(global::Module.MY_SECOND_FILTER); + builder.RegisterClientVisibilityFilter(global::Module.MY_THIRD_FILTER); + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ { */ Message: Argument 1: cannot convert from 'string' to 'SpacetimeDB.Filter', @@ -322,7 +322,7 @@ SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_THI } }, {/* - + var returnValue = Module.ViewDefNoContext((SpacetimeDB.ViewContext)ctx); ^^^^^^^^^^^^^^^^ var listSerializer = new SpacetimeDB.BSATN.List(); @@ -345,10 +345,10 @@ SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_THI } }, {/* - public global::SpacetimeDB.Table TestDuplicateTableName() => - new("TestDuplicateTableName", new TestDuplicateTableNameCols("TestDuplicateTableName"), new TestDuplicateTableNameIxCols("TestDuplicateTableName")); - ^^^^^^^^^^^^^^^^^^^^^^^^^^ -} + public global::SpacetimeDB.Table TestDuplicateTableName() => + new("TestDuplicateTableName", new TestDuplicateTableNameCols("TestDuplicateTableName"), new TestDuplicateTableNameIxCols("TestDuplicateTableName")); + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + } */ Message: The call is ambiguous between the following methods or properties: 'TestDuplicateTableNameCols.TestDuplicateTableNameCols(string)' and 'TestDuplicateTableNameCols.TestDuplicateTableNameCols(string)', Severity: Error, @@ -368,10 +368,10 @@ SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_THI } }, {/* - public global::SpacetimeDB.Table TestDuplicateTableName() => - new("TestDuplicateTableName", new TestDuplicateTableNameCols("TestDuplicateTableName"), new TestDuplicateTableNameIxCols("TestDuplicateTableName")); - ^^^^^^^^^^^^^^^^^^^^^^^^^^ -} + public global::SpacetimeDB.Table TestDuplicateTableName() => + new("TestDuplicateTableName", new TestDuplicateTableNameCols("TestDuplicateTableName"), new TestDuplicateTableNameIxCols("TestDuplicateTableName")); + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + } */ Message: The call is ambiguous between the following methods or properties: 'TestDuplicateTableNameCols.TestDuplicateTableNameCols(string)' and 'TestDuplicateTableNameCols.TestDuplicateTableNameCols(string)', Severity: Error, @@ -391,10 +391,10 @@ SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_THI } }, {/* - public global::SpacetimeDB.Table TestDuplicateTableName() => - new("TestDuplicateTableName", new TestDuplicateTableNameCols("TestDuplicateTableName"), new TestDuplicateTableNameIxCols("TestDuplicateTableName")); - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -} + public global::SpacetimeDB.Table TestDuplicateTableName() => + new("TestDuplicateTableName", new TestDuplicateTableNameCols("TestDuplicateTableName"), new TestDuplicateTableNameIxCols("TestDuplicateTableName")); + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + } */ Message: The call is ambiguous between the following methods or properties: 'TestDuplicateTableNameIxCols.TestDuplicateTableNameIxCols(string)' and 'TestDuplicateTableNameIxCols.TestDuplicateTableNameIxCols(string)', Severity: Error, @@ -414,10 +414,10 @@ SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_THI } }, {/* - public global::SpacetimeDB.Table TestDuplicateTableName() => - new("TestDuplicateTableName", new TestDuplicateTableNameCols("TestDuplicateTableName"), new TestDuplicateTableNameIxCols("TestDuplicateTableName")); - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -} + public global::SpacetimeDB.Table TestDuplicateTableName() => + new("TestDuplicateTableName", new TestDuplicateTableNameCols("TestDuplicateTableName"), new TestDuplicateTableNameIxCols("TestDuplicateTableName")); + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + } */ Message: The call is ambiguous between the following methods or properties: 'TestDuplicateTableNameIxCols.TestDuplicateTableNameIxCols(string)' and 'TestDuplicateTableNameIxCols.TestDuplicateTableNameIxCols(string)', Severity: Error, @@ -437,10 +437,10 @@ SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_THI } }, {/* -} -public readonly struct TestDuplicateTableNameCols - ^^^^^^^^^^^^^^^^^^^^^^^^^^ -{ + } + public readonly struct TestDuplicateTableNameCols + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + { */ Message: The namespace 'SpacetimeDB' already contains a definition for 'TestDuplicateTableNameCols', Severity: Error, @@ -461,9 +461,9 @@ public readonly struct TestDuplicateTableNameCols }, {/* -public readonly struct TestDuplicateTableNameIxCols - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -{ + public readonly struct TestDuplicateTableNameIxCols + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + { */ Message: The namespace 'SpacetimeDB' already contains a definition for 'TestDuplicateTableNameIxCols', Severity: Error, @@ -575,10 +575,10 @@ public readonly struct TestDuplicateTableNameIxCols } }, {/* -{ - public global::SpacetimeDB.Table TestDuplicateTableName() => - ^^^^^^^^^^^^^^^^^^^^^^ - new("TestDuplicateTableName", new TestDuplicateTableNameCols("TestDuplicateTableName"), new TestDuplicateTableNameIxCols("TestDuplicateTableName")); + { + public global::SpacetimeDB.Table TestDuplicateTableName() => + ^^^^^^^^^^^^^^^^^^^^^^ + new("TestDuplicateTableName", new TestDuplicateTableNameCols("TestDuplicateTableName"), new TestDuplicateTableNameIxCols("TestDuplicateTableName")); */ Message: Type 'QueryBuilder' already defines a member called 'TestDuplicateTableName' with the same parameter types, Severity: Error, @@ -599,9 +599,9 @@ public readonly struct TestDuplicateTableNameIxCols }, {/* - internal TestDuplicateTableNameCols(string tableName) - ^^^^^^^^^^^^^^^^^^^^^^^^^^ - { + internal TestDuplicateTableNameCols(string tableName) + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + { */ Message: Type 'TestDuplicateTableNameCols' already defines a member called 'TestDuplicateTableNameCols' with the same parameter types, Severity: Error, @@ -622,9 +622,9 @@ public readonly struct TestDuplicateTableNameIxCols }, {/* - internal TestDuplicateTableNameIxCols(string tableName) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - { + internal TestDuplicateTableNameIxCols(string tableName) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + { */ Message: Type 'TestDuplicateTableNameIxCols' already defines a member called 'TestDuplicateTableNameIxCols' with the same parameter types, Severity: Error, diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#FFI.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#FFI.verified.cs index e81f122020d..249ea5f98a4 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#FFI.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#FFI.verified.cs @@ -1,20 +1,28 @@ //HintName: FFI.cs // #nullable enable -// The runtime already defines SpacetimeDB.Internal.LocalReadOnly in Runtime\Internal\Module.cs as an empty partial type. -// This is needed so every module build doesn't generate a full LocalReadOnly type, but just adds on to the existing. -// We extend it here with generated table accessors, and just need to suppress the duplicate-type warning. +// .NET 8 generates a module-local LocalReadOnly which shadows the runtime shell. #pragma warning disable CS0436 #pragma warning disable STDB_UNSTABLE +#if NET10_0_OR_GREATER +global using SpacetimeDB.Generated.diag_4F830E2879BB50E3; +#endif using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal = SpacetimeDB.Internal; using TxContext = SpacetimeDB.Internal.TxContext; +#if NET10_0_OR_GREATER +[assembly: global::SpacetimeDB.ModuleDescriptorAttribute( + typeof(global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor) +)] + +#endif namespace SpacetimeDB { +#if !NET10_0_OR_GREATER public readonly struct TestDuplicateTableNameCols { internal TestDuplicateTableNameCols(string tableName) { } @@ -644,9 +652,11 @@ public readonly partial struct QueryBuilder new TestUniqueNotEquatableIxCols("TestUniqueNotEquatable") ); } +#endif - public static class Handlers { } + internal static class Handlers { } +#if !NET10_0_OR_GREATER public sealed record ReducerContext : DbContext, Internal.IReducerContext { public global::SpacetimeDB.ModuleEnvironment Env => default; @@ -916,10 +926,1234 @@ public sealed record AnonymousViewContext public global::SpacetimeDB.ModuleEnvironment Env => default; public QueryBuilder From => default; - internal AnonymousViewContext(Internal.LocalReadOnly db) - : base(db) { } + internal AnonymousViewContext(Internal.LocalReadOnly db) + : base(db) { } + } +#endif +} + +#if NET10_0_OR_GREATER +namespace SpacetimeDB.Generated.diag_4F830E2879BB50E3 +{ + public static partial class AssemblyDescriptor + { + public const string? CaseConversionPolicy = "SnakeCase"; + public const string RootOnlyDeclarations = + "row-level security filters, lifecycle reducer Reducers.TestDuplicateReducerKind1 (Init), lifecycle reducer Reducers.TestDuplicateReducerKind2 (Init)"; + public const int ReducerCount = 8; + public const int ProcedureCount = 0; + public const int HttpHandlerCount = 0; + public const int ViewCount = 12; + public const int AnonymousViewCount = 4; + + public static global::SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink error + ) => + global::ModuleRegistration.CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink result_sink + ) => + global::ModuleRegistration.CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource request, + global::SpacetimeDB.Internal.BytesSource request_body, + global::SpacetimeDB.Internal.BytesSink response_sink, + global::SpacetimeDB.Internal.BytesSink response_body_sink + ) => + global::ModuleRegistration.CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => + global::ModuleRegistration.CallLocalView( + id, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => global::ModuleRegistration.CallLocalAnonymousView(id, args, sink); + + public static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) => global::ModuleRegistration.Register(builder, httpBuilder); + + public readonly struct Tables + { + public global::SpacetimeDB.Internal.TableHandles.Player Player => new(); + public global::SpacetimeDB.Internal.TableHandles.TestAutoIncNotInteger TestAutoIncNotInteger => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestDefaultFieldValues TestDefaultFieldValues => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestDuplicateTableName TestDuplicateTableName => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestIndexIssues TestIndexIssues => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestScheduleWithMissingScheduleAtField TestScheduleWithMissingScheduleAtField => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestScheduleWithoutPrimaryKey TestScheduleWithoutPrimaryKey => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestScheduleWithoutScheduleAt TestScheduleWithoutScheduleAt => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestScheduleWithWrongPrimaryKeyType TestScheduleWithWrongPrimaryKeyType => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestScheduleWithWrongScheduleAtType TestScheduleWithWrongScheduleAtType => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestUniqueNotEquatable TestUniqueNotEquatable => + new(); + } + + public readonly struct ReadOnlyTables + { + public global::SpacetimeDB.Internal.ViewHandles.PlayerReadOnly Player => new(); + public global::SpacetimeDB.Internal.ViewHandles.TestAutoIncNotIntegerReadOnly TestAutoIncNotInteger => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestDefaultFieldValuesReadOnly TestDefaultFieldValues => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestDuplicateTableNameReadOnly TestDuplicateTableName => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestIndexIssuesReadOnly TestIndexIssues => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestScheduleWithMissingScheduleAtFieldReadOnly TestScheduleWithMissingScheduleAtField => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestScheduleWithoutPrimaryKeyReadOnly TestScheduleWithoutPrimaryKey => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestScheduleWithoutScheduleAtReadOnly TestScheduleWithoutScheduleAt => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestScheduleWithWrongPrimaryKeyTypeReadOnly TestScheduleWithWrongPrimaryKeyType => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestScheduleWithWrongScheduleAtTypeReadOnly TestScheduleWithWrongScheduleAtType => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestUniqueNotEquatableReadOnly TestUniqueNotEquatable => + new(); + } + + public readonly partial struct Queries { } + } + + public static class LocalTableExtensions + { + extension(global::SpacetimeDB.Local db) + { + public global::SpacetimeDB.Internal.TableHandles.Player Player => new(); + public global::SpacetimeDB.Internal.TableHandles.TestAutoIncNotInteger TestAutoIncNotInteger => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestDefaultFieldValues TestDefaultFieldValues => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestDuplicateTableName TestDuplicateTableName => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestIndexIssues TestIndexIssues => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestScheduleWithMissingScheduleAtField TestScheduleWithMissingScheduleAtField => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestScheduleWithoutPrimaryKey TestScheduleWithoutPrimaryKey => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestScheduleWithoutScheduleAt TestScheduleWithoutScheduleAt => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestScheduleWithWrongPrimaryKeyType TestScheduleWithWrongPrimaryKeyType => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestScheduleWithWrongScheduleAtType TestScheduleWithWrongScheduleAtType => + new(); + public global::SpacetimeDB.Internal.TableHandles.TestUniqueNotEquatable TestUniqueNotEquatable => + new(); + } + } + + public static class ReadOnlyTableExtensions + { + extension(global::SpacetimeDB.Internal.LocalReadOnly db) + { + public global::SpacetimeDB.Internal.ViewHandles.PlayerReadOnly Player => new(); + public global::SpacetimeDB.Internal.ViewHandles.TestAutoIncNotIntegerReadOnly TestAutoIncNotInteger => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestDefaultFieldValuesReadOnly TestDefaultFieldValues => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestDuplicateTableNameReadOnly TestDuplicateTableName => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestIndexIssuesReadOnly TestIndexIssues => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestScheduleWithMissingScheduleAtFieldReadOnly TestScheduleWithMissingScheduleAtField => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestScheduleWithoutPrimaryKeyReadOnly TestScheduleWithoutPrimaryKey => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestScheduleWithoutScheduleAtReadOnly TestScheduleWithoutScheduleAt => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestScheduleWithWrongPrimaryKeyTypeReadOnly TestScheduleWithWrongPrimaryKeyType => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestScheduleWithWrongScheduleAtTypeReadOnly TestScheduleWithWrongScheduleAtType => + new(); + public global::SpacetimeDB.Internal.ViewHandles.TestUniqueNotEquatableReadOnly TestUniqueNotEquatable => + new(); + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) { } + } + + public readonly struct TestDuplicateTableNameCols + { + internal TestDuplicateTableNameCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public readonly struct TestDuplicateTableNameIxCols + { + internal TestDuplicateTableNameIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestDuplicateTableNameSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestDuplicateTableName" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestDuplicateTableNameSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::InAnotherNamespace.TestDuplicateTableName, + TestDuplicateTableNameCols, + TestDuplicateTableNameIxCols + > TestDuplicateTableName() + { + var tableName = TestDuplicateTableNameSqlNameCache.Name; + return new( + tableName, + new TestDuplicateTableNameCols(tableName), + new TestDuplicateTableNameIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::InAnotherNamespace.TestDuplicateTableName, + TestDuplicateTableNameCols, + TestDuplicateTableNameIxCols + > TestDuplicateTableName() => new AssemblyDescriptor.Queries().TestDuplicateTableName(); + } + } + + public readonly struct PlayerCols + { + public readonly global::SpacetimeDB.Col Identity; + + internal PlayerCols(global::SpacetimeDB.SqlTableName tableName) + { + Identity = new global::SpacetimeDB.Col( + tableName, + "Identity" + ); + } + } + + public readonly struct PlayerIxCols + { + internal PlayerIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class PlayerSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "Player" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PlayerSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table Player() + { + var tableName = PlayerSqlNameCache.Name; + return new(tableName, new PlayerCols(tableName), new PlayerIxCols(tableName)); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table Player() => + new AssemblyDescriptor.Queries().Player(); + } + } + + public readonly struct TestAutoIncNotIntegerCols + { + public readonly global::SpacetimeDB.Col AutoIncField; + public readonly global::SpacetimeDB.Col< + global::TestAutoIncNotInteger, + string + > IdentityField; + + internal TestAutoIncNotIntegerCols(global::SpacetimeDB.SqlTableName tableName) + { + AutoIncField = new global::SpacetimeDB.Col( + tableName, + "AutoIncField" + ); + IdentityField = new global::SpacetimeDB.Col( + tableName, + "IdentityField" + ); + } + } + + public readonly struct TestAutoIncNotIntegerIxCols + { + internal TestAutoIncNotIntegerIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestAutoIncNotIntegerSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestAutoIncNotInteger" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestAutoIncNotIntegerSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestAutoIncNotInteger, + TestAutoIncNotIntegerCols, + TestAutoIncNotIntegerIxCols + > TestAutoIncNotInteger() + { + var tableName = TestAutoIncNotIntegerSqlNameCache.Name; + return new( + tableName, + new TestAutoIncNotIntegerCols(tableName), + new TestAutoIncNotIntegerIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestAutoIncNotInteger, + TestAutoIncNotIntegerCols, + TestAutoIncNotIntegerIxCols + > TestAutoIncNotInteger() => new AssemblyDescriptor.Queries().TestAutoIncNotInteger(); + } + } + + public readonly struct TestDefaultFieldValuesCols + { + public readonly global::SpacetimeDB.Col UniqueField; + public readonly global::SpacetimeDB.Col< + global::TestDefaultFieldValues, + string + > DefaultString; + public readonly global::SpacetimeDB.Col DefaultBool; + public readonly global::SpacetimeDB.Col DefaultI8; + public readonly global::SpacetimeDB.Col DefaultU8; + public readonly global::SpacetimeDB.Col DefaultI16; + public readonly global::SpacetimeDB.Col DefaultU16; + public readonly global::SpacetimeDB.Col DefaultI32; + public readonly global::SpacetimeDB.Col DefaultU32; + public readonly global::SpacetimeDB.Col DefaultI64; + public readonly global::SpacetimeDB.Col DefaultU64; + public readonly global::SpacetimeDB.Col DefaultHex; + public readonly global::SpacetimeDB.Col DefaultBin; + public readonly global::SpacetimeDB.Col DefaultF32; + public readonly global::SpacetimeDB.Col DefaultF64; + public readonly global::SpacetimeDB.Col DefaultEnum; + public readonly global::SpacetimeDB.Col< + global::TestDefaultFieldValues, + MyStruct + > DefaultNull; + + internal TestDefaultFieldValuesCols(global::SpacetimeDB.SqlTableName tableName) + { + UniqueField = new global::SpacetimeDB.Col( + tableName, + "UniqueField" + ); + DefaultString = new global::SpacetimeDB.Col( + tableName, + "DefaultString" + ); + DefaultBool = new global::SpacetimeDB.Col( + tableName, + "DefaultBool" + ); + DefaultI8 = new global::SpacetimeDB.Col( + tableName, + "DefaultI8" + ); + DefaultU8 = new global::SpacetimeDB.Col( + tableName, + "DefaultU8" + ); + DefaultI16 = new global::SpacetimeDB.Col( + tableName, + "DefaultI16" + ); + DefaultU16 = new global::SpacetimeDB.Col( + tableName, + "DefaultU16" + ); + DefaultI32 = new global::SpacetimeDB.Col( + tableName, + "DefaultI32" + ); + DefaultU32 = new global::SpacetimeDB.Col( + tableName, + "DefaultU32" + ); + DefaultI64 = new global::SpacetimeDB.Col( + tableName, + "DefaultI64" + ); + DefaultU64 = new global::SpacetimeDB.Col( + tableName, + "DefaultU64" + ); + DefaultHex = new global::SpacetimeDB.Col( + tableName, + "DefaultHex" + ); + DefaultBin = new global::SpacetimeDB.Col( + tableName, + "DefaultBin" + ); + DefaultF32 = new global::SpacetimeDB.Col( + tableName, + "DefaultF32" + ); + DefaultF64 = new global::SpacetimeDB.Col( + tableName, + "DefaultF64" + ); + DefaultEnum = new global::SpacetimeDB.Col( + tableName, + "DefaultEnum" + ); + DefaultNull = new global::SpacetimeDB.Col( + tableName, + "DefaultNull" + ); + } + } + + public readonly struct TestDefaultFieldValuesIxCols + { + internal TestDefaultFieldValuesIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestDefaultFieldValuesSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestDefaultFieldValues" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestDefaultFieldValuesSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestDefaultFieldValues, + TestDefaultFieldValuesCols, + TestDefaultFieldValuesIxCols + > TestDefaultFieldValues() + { + var tableName = TestDefaultFieldValuesSqlNameCache.Name; + return new( + tableName, + new TestDefaultFieldValuesCols(tableName), + new TestDefaultFieldValuesIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestDefaultFieldValues, + TestDefaultFieldValuesCols, + TestDefaultFieldValuesIxCols + > TestDefaultFieldValues() => new AssemblyDescriptor.Queries().TestDefaultFieldValues(); + } + } + + public readonly struct TestDuplicateTableNameCols + { + internal TestDuplicateTableNameCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public readonly struct TestDuplicateTableNameIxCols + { + internal TestDuplicateTableNameIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestDuplicateTableNameSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestDuplicateTableName" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestDuplicateTableNameSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestDuplicateTableName, + TestDuplicateTableNameCols, + TestDuplicateTableNameIxCols + > TestDuplicateTableName() + { + var tableName = TestDuplicateTableNameSqlNameCache.Name; + return new( + tableName, + new TestDuplicateTableNameCols(tableName), + new TestDuplicateTableNameIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestDuplicateTableName, + TestDuplicateTableNameCols, + TestDuplicateTableNameIxCols + > TestDuplicateTableName() => new AssemblyDescriptor.Queries().TestDuplicateTableName(); + } + } + + public readonly struct TestIndexIssuesCols + { + public readonly global::SpacetimeDB.Col SelfIndexingColumn; + public readonly global::SpacetimeDB.Col< + global::TestIndexIssues, + int + > SecondaryIndexingColumn; + + internal TestIndexIssuesCols(global::SpacetimeDB.SqlTableName tableName) + { + SelfIndexingColumn = new global::SpacetimeDB.Col( + tableName, + "SelfIndexingColumn" + ); + SecondaryIndexingColumn = new global::SpacetimeDB.Col( + tableName, + "SecondaryIndexingColumn" + ); + } + } + + public readonly struct TestIndexIssuesIxCols + { + public readonly global::SpacetimeDB.IxCol SelfIndexingColumn; + public readonly global::SpacetimeDB.IxCol< + global::TestIndexIssues, + int + > SecondaryIndexingColumn; + + internal TestIndexIssuesIxCols(global::SpacetimeDB.SqlTableName tableName) + { + SelfIndexingColumn = new global::SpacetimeDB.IxCol( + tableName, + "SelfIndexingColumn" + ); + SecondaryIndexingColumn = new global::SpacetimeDB.IxCol( + tableName, + "SecondaryIndexingColumn" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class TestIndexIssuesSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestIndexIssuesSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestIndexIssues, + TestIndexIssuesCols, + TestIndexIssuesIxCols + > TestIndexIssues() + { + var tableName = TestIndexIssuesSqlNameCache.Name; + return new( + tableName, + new TestIndexIssuesCols(tableName), + new TestIndexIssuesIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestIndexIssues, + TestIndexIssuesCols, + TestIndexIssuesIxCols + > TestIndexIssues() => new AssemblyDescriptor.Queries().TestIndexIssues(); + } + } + + public readonly struct TestScheduleWithoutPrimaryKeyCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithoutPrimaryKeyCols(global::SpacetimeDB.SqlTableName tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithoutPrimaryKeyIxCols + { + internal TestScheduleWithoutPrimaryKeyIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestScheduleWithoutPrimaryKeySqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithoutPrimaryKey" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithoutPrimaryKeySqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithoutPrimaryKeyCols, + TestScheduleWithoutPrimaryKeyIxCols + > TestScheduleWithoutPrimaryKey() + { + var tableName = TestScheduleWithoutPrimaryKeySqlNameCache.Name; + return new( + tableName, + new TestScheduleWithoutPrimaryKeyCols(tableName), + new TestScheduleWithoutPrimaryKeyIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithoutPrimaryKeyCols, + TestScheduleWithoutPrimaryKeyIxCols + > TestScheduleWithoutPrimaryKey() => + new AssemblyDescriptor.Queries().TestScheduleWithoutPrimaryKey(); + } + } + + public readonly struct TestScheduleWithWrongPrimaryKeyTypeCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithWrongPrimaryKeyTypeCols(global::SpacetimeDB.SqlTableName tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithWrongPrimaryKeyTypeIxCols + { + public readonly global::SpacetimeDB.IxCol IdWrongType; + + internal TestScheduleWithWrongPrimaryKeyTypeIxCols( + global::SpacetimeDB.SqlTableName tableName + ) + { + IdWrongType = new global::SpacetimeDB.IxCol( + tableName, + "IdWrongType" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class TestScheduleWithWrongPrimaryKeyTypeSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongPrimaryKeyType" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithWrongPrimaryKeyTypeSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithWrongPrimaryKeyTypeCols, + TestScheduleWithWrongPrimaryKeyTypeIxCols + > TestScheduleWithWrongPrimaryKeyType() + { + var tableName = TestScheduleWithWrongPrimaryKeyTypeSqlNameCache.Name; + return new( + tableName, + new TestScheduleWithWrongPrimaryKeyTypeCols(tableName), + new TestScheduleWithWrongPrimaryKeyTypeIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithWrongPrimaryKeyTypeCols, + TestScheduleWithWrongPrimaryKeyTypeIxCols + > TestScheduleWithWrongPrimaryKeyType() => + new AssemblyDescriptor.Queries().TestScheduleWithWrongPrimaryKeyType(); + } + } + + public readonly struct TestScheduleWithoutScheduleAtCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithoutScheduleAtCols(global::SpacetimeDB.SqlTableName tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithoutScheduleAtIxCols + { + public readonly global::SpacetimeDB.IxCol IdCorrectType; + + internal TestScheduleWithoutScheduleAtIxCols(global::SpacetimeDB.SqlTableName tableName) + { + IdCorrectType = new global::SpacetimeDB.IxCol( + tableName, + "IdCorrectType" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class TestScheduleWithoutScheduleAtSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithoutScheduleAt" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithoutScheduleAtSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithoutScheduleAtCols, + TestScheduleWithoutScheduleAtIxCols + > TestScheduleWithoutScheduleAt() + { + var tableName = TestScheduleWithoutScheduleAtSqlNameCache.Name; + return new( + tableName, + new TestScheduleWithoutScheduleAtCols(tableName), + new TestScheduleWithoutScheduleAtIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithoutScheduleAtCols, + TestScheduleWithoutScheduleAtIxCols + > TestScheduleWithoutScheduleAt() => + new AssemblyDescriptor.Queries().TestScheduleWithoutScheduleAt(); + } + } + + public readonly struct TestScheduleWithWrongScheduleAtTypeCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithWrongScheduleAtTypeCols(global::SpacetimeDB.SqlTableName tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithWrongScheduleAtTypeIxCols + { + public readonly global::SpacetimeDB.IxCol IdCorrectType; + + internal TestScheduleWithWrongScheduleAtTypeIxCols( + global::SpacetimeDB.SqlTableName tableName + ) + { + IdCorrectType = new global::SpacetimeDB.IxCol( + tableName, + "IdCorrectType" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class TestScheduleWithWrongScheduleAtTypeSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongScheduleAtType" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithWrongScheduleAtTypeSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithWrongScheduleAtTypeCols, + TestScheduleWithWrongScheduleAtTypeIxCols + > TestScheduleWithWrongScheduleAtType() + { + var tableName = TestScheduleWithWrongScheduleAtTypeSqlNameCache.Name; + return new( + tableName, + new TestScheduleWithWrongScheduleAtTypeCols(tableName), + new TestScheduleWithWrongScheduleAtTypeIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithWrongScheduleAtTypeCols, + TestScheduleWithWrongScheduleAtTypeIxCols + > TestScheduleWithWrongScheduleAtType() => + new AssemblyDescriptor.Queries().TestScheduleWithWrongScheduleAtType(); + } + } + + public readonly struct TestScheduleWithMissingScheduleAtFieldCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithMissingScheduleAtFieldCols( + global::SpacetimeDB.SqlTableName tableName + ) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithMissingScheduleAtFieldIxCols + { + internal TestScheduleWithMissingScheduleAtFieldIxCols( + global::SpacetimeDB.SqlTableName tableName + ) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestScheduleWithMissingScheduleAtFieldSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithMissingScheduleAtField" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithMissingScheduleAtFieldSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithMissingScheduleAtFieldCols, + TestScheduleWithMissingScheduleAtFieldIxCols + > TestScheduleWithMissingScheduleAtField() + { + var tableName = TestScheduleWithMissingScheduleAtFieldSqlNameCache.Name; + return new( + tableName, + new TestScheduleWithMissingScheduleAtFieldCols(tableName), + new TestScheduleWithMissingScheduleAtFieldIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithMissingScheduleAtFieldCols, + TestScheduleWithMissingScheduleAtFieldIxCols + > TestScheduleWithMissingScheduleAtField() => + new AssemblyDescriptor.Queries().TestScheduleWithMissingScheduleAtField(); + } + } + + public readonly struct TestUniqueNotEquatableCols + { + public readonly global::SpacetimeDB.Col UniqueField; + public readonly global::SpacetimeDB.Col< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + > PrimaryKeyField; + + internal TestUniqueNotEquatableCols(global::SpacetimeDB.SqlTableName tableName) + { + UniqueField = new global::SpacetimeDB.Col( + tableName, + "UniqueField" + ); + PrimaryKeyField = new global::SpacetimeDB.Col< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + >(tableName, "PrimaryKeyField"); + } + } + + public readonly struct TestUniqueNotEquatableIxCols + { + public readonly global::SpacetimeDB.IxCol< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + > PrimaryKeyField; + + internal TestUniqueNotEquatableIxCols(global::SpacetimeDB.SqlTableName tableName) + { + PrimaryKeyField = new global::SpacetimeDB.IxCol< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + >(tableName, "PrimaryKeyField"); + } + } + + public static partial class AssemblyDescriptor + { + private static class TestUniqueNotEquatableSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestUniqueNotEquatable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestUniqueNotEquatableSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestUniqueNotEquatable, + TestUniqueNotEquatableCols, + TestUniqueNotEquatableIxCols + > TestUniqueNotEquatable() + { + var tableName = TestUniqueNotEquatableSqlNameCache.Name; + return new( + tableName, + new TestUniqueNotEquatableCols(tableName), + new TestUniqueNotEquatableIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestUniqueNotEquatable, + TestUniqueNotEquatableCols, + TestUniqueNotEquatableIxCols + > TestUniqueNotEquatable() => new AssemblyDescriptor.Queries().TestUniqueNotEquatable(); + } } } +#endif namespace SpacetimeDB.Internal.TableHandles { @@ -946,14 +2180,14 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "Player_Identity_idx_btree", AccessorName: "Identity", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< Player, global::Player - >.MakeUniqueConstraint(0) + >.MakeUniqueConstraint(0), ], Sequences: [], TableType: SpacetimeDB.Internal.TableType.User, @@ -986,7 +2220,12 @@ public ulong Clear() => global::SpacetimeDB.Internal.ITableView.DoClear(); public sealed class IdentityUniqueIndex - : UniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + Player, + global::Player, + SpacetimeDB.Identity, + SpacetimeDB.Identity.BSATN + > { internal IdentityUniqueIndex() : base("Player_Identity_idx_btree") { } @@ -1038,14 +2277,14 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "TestAutoIncNotInteger_IdentityField_idx_btree", AccessorName: "IdentityField", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< TestAutoIncNotInteger, global::TestAutoIncNotInteger - >.MakeUniqueConstraint(1) + >.MakeUniqueConstraint(1), ], Sequences: [ @@ -1056,7 +2295,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar global::SpacetimeDB.Internal.ITableView< TestAutoIncNotInteger, global::TestAutoIncNotInteger - >.MakeSequence(1) + >.MakeSequence(1), ], TableType: SpacetimeDB.Internal.TableType.User, TableAccess: SpacetimeDB.Internal.TableAccess.Private, @@ -1103,7 +2342,7 @@ public ulong Clear() => >.DoClear(); public sealed class IdentityFieldUniqueIndex - : UniqueIndex< + : global::SpacetimeDB.Internal.UniqueIndex< TestAutoIncNotInteger, global::TestAutoIncNotInteger, string, @@ -1150,14 +2389,14 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "TestDefaultFieldValues_UniqueField_idx_btree", AccessorName: "UniqueField", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< TestDefaultFieldValues, global::TestDefaultFieldValues - >.MakeUniqueConstraint(0) + >.MakeUniqueConstraint(0), ], Sequences: [], TableType: SpacetimeDB.Internal.TableType.User, @@ -1325,7 +2564,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "TestIndexIssues_SelfIndexingColumn_idx_btree", AccessorName: "TestUnexpectedColumns", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) - ) + ), ], Constraints: [], Sequences: [], @@ -1681,14 +2920,14 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "TestScheduleWithoutScheduleAt_IdCorrectType_idx_btree", AccessorName: "IdCorrectType", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< TestScheduleWithoutScheduleAt, global::TestScheduleIssues - >.MakeUniqueConstraint(1) + >.MakeUniqueConstraint(1), ], Sequences: [], TableType: SpacetimeDB.Internal.TableType.User, @@ -1736,7 +2975,7 @@ public ulong Clear() => >.DoClear(); public sealed class IdCorrectTypeUniqueIndex - : UniqueIndex< + : global::SpacetimeDB.Internal.UniqueIndex< TestScheduleWithoutScheduleAt, global::TestScheduleIssues, int, @@ -1786,14 +3025,14 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "TestScheduleWithWrongPrimaryKeyType_IdWrongType_idx_btree", AccessorName: "IdWrongType", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< TestScheduleWithWrongPrimaryKeyType, global::TestScheduleIssues - >.MakeUniqueConstraint(0) + >.MakeUniqueConstraint(0), ], Sequences: [], TableType: SpacetimeDB.Internal.TableType.User, @@ -1845,7 +3084,7 @@ public ulong Clear() => >.DoClear(); public sealed class IdWrongTypeUniqueIndex - : UniqueIndex< + : global::SpacetimeDB.Internal.UniqueIndex< TestScheduleWithWrongPrimaryKeyType, global::TestScheduleIssues, string, @@ -1895,14 +3134,14 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "TestScheduleWithWrongScheduleAtType_IdCorrectType_idx_btree", AccessorName: "IdCorrectType", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< TestScheduleWithWrongScheduleAtType, global::TestScheduleIssues - >.MakeUniqueConstraint(1) + >.MakeUniqueConstraint(1), ], Sequences: [], TableType: SpacetimeDB.Internal.TableType.User, @@ -1954,7 +3193,7 @@ public ulong Clear() => >.DoClear(); public sealed class IdCorrectTypeUniqueIndex - : UniqueIndex< + : global::SpacetimeDB.Internal.UniqueIndex< TestScheduleWithWrongScheduleAtType, global::TestScheduleIssues, int, @@ -2009,7 +3248,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "TestUniqueNotEquatable_PrimaryKeyField_idx_btree", AccessorName: "PrimaryKeyField", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) - ) + ), ], Constraints: [ @@ -2020,7 +3259,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar global::SpacetimeDB.Internal.ITableView< TestUniqueNotEquatable, global::TestUniqueNotEquatable - >.MakeUniqueConstraint(1) + >.MakeUniqueConstraint(1), ], Sequences: [], TableType: SpacetimeDB.Internal.TableType.User, @@ -2068,7 +3307,7 @@ public ulong Clear() => >.DoClear(); public sealed class PrimaryKeyFieldUniqueIndex - : UniqueIndex< + : global::SpacetimeDB.Internal.UniqueIndex< TestUniqueNotEquatable, global::TestUniqueNotEquatable, TestEnumWithExplicitValues, @@ -3189,6 +4428,7 @@ internal PrimaryKeyFieldIndex() } } +#if !NET10_0_OR_GREATER namespace SpacetimeDB.Internal { public sealed partial class LocalReadOnly @@ -3216,6 +4456,7 @@ public sealed partial class LocalReadOnly new(); } } +#endif static class ModuleRegistration { @@ -3415,8 +4656,11 @@ public static List ToListOrEmpty(T? value) // Prevent trimming of FFI exports that are invoked from C and not visible to C# trimmer. [DynamicDependency(DynamicallyAccessedMemberTypes.PublicMethods, typeof(ModuleRegistration))] #endif - public static void Main() + public static void Main() => Initialize(); + + internal static void Initialize() { +#if !NET10_0_OR_GREATER SpacetimeDB.Internal.Module.SetReducerContextConstructor( (identity, connectionId, random, time) => new SpacetimeDB.ReducerContext(identity, connectionId, random, time) @@ -3427,133 +4671,142 @@ public static void Main() new SpacetimeDB.Internal.LocalReadOnly() ) ); - SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor( - () => new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly()) + SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor(() => + new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly()) ); SpacetimeDB.Internal.Module.SetProcedureContextConstructor( (identity, connectionId, random, time) => new SpacetimeDB.ProcedureContext(identity, connectionId, random, time) ); - SpacetimeDB.Internal.Module.SetCaseConversionPolicy( - SpacetimeDB.CaseConversionPolicy.SnakeCase + SpacetimeDB.Internal.Module.SetHandlerContextConstructor( + (random, time) => new SpacetimeDB.HandlerContext(random, time) ); - SpacetimeDB.Internal.Module.RegisterExplicitIndexName( - "TestIndexIssues_SecondaryIndexingColumn_idx_btree", - "TestCanonicalNameWithoutAccessor" +#endif + +#if NET10_0_OR_GREATER + global::SpacetimeDB.Internal.Module.InstallNamespaces( + new global::SpacetimeDB.Internal.NamespaceRegistry( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + global::SpacetimeDB.CaseConversionPolicy.SnakeCase, + new (string, string, string?, global::SpacetimeDB.CaseConversionPolicy)[] { } + ) + ); + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.Register( + global::SpacetimeDB.Internal.Module.RootBuilder ); +#else + Register(global::SpacetimeDB.Internal.Module.RootBuilder); +#endif + } - SpacetimeDB.Internal.Module.SetHandlerContextConstructor( - (random, time) => new SpacetimeDB.HandlerContext(random, time) + internal static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) + { + // HTTP routes retain the root routing API even for mounted modules. + httpBuilder ??= builder; + builder.SetCaseConversionPolicy(SpacetimeDB.CaseConversionPolicy.SnakeCase); + builder.RegisterExplicitIndexName( + "TestIndexIssues_SecondaryIndexingColumn_idx_btree", + "TestCanonicalNameWithoutAccessor" ); var __memoryStream = new MemoryStream(); var __writer = new BinaryWriter(__memoryStream); - SpacetimeDB.Internal.Module.RegisterReducer<__ReducerWithReservedPrefix>(); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); + builder.RegisterReducer<__ReducerWithReservedPrefix>(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); // IMPORTANT: The order in which we register views matters. // It must correspond to the order in which we call `GenerateDispatcherClass`. // See the comment on `GenerateDispatcherClass` for more explanation. - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterAnonymousView(); - SpacetimeDB.Internal.Module.RegisterAnonymousView(); - SpacetimeDB.Internal.Module.RegisterAnonymousView(); - SpacetimeDB.Internal.Module.RegisterAnonymousView(); - - SpacetimeDB.Internal.Module.RegisterViewPrimaryKey( - "view_primary_key_missing_column", - ["MissingIdentity"] - ); - SpacetimeDB.Internal.Module.RegisterViewPrimaryKey( - "view_primary_key_non_equatable_column", - ["Identity"] - ); - SpacetimeDB.Internal.Module.RegisterViewPrimaryKey( + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterAnonymousView(); + builder.RegisterAnonymousView(); + builder.RegisterAnonymousView(); + builder.RegisterAnonymousView(); + + builder.RegisterViewPrimaryKey("view_primary_key_missing_column", ["MissingIdentity"]); + builder.RegisterViewPrimaryKey("view_primary_key_non_equatable_column", ["Identity"]); + builder.RegisterViewPrimaryKey( "view_primary_key_uses_non_bsatn_partial_field", ["ExtraPartialIdentity"] ); - SpacetimeDB.Internal.Module.RegisterViewPrimaryKey( + builder.RegisterViewPrimaryKey( "view_primary_key_uses_wrong_source_name", ["renamed_identity"] ); - SpacetimeDB.Internal.Module.RegisterTable< - global::Player, - SpacetimeDB.Internal.TableHandles.Player - >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable(); + builder.RegisterTable< global::TestAutoIncNotInteger, - SpacetimeDB.Internal.TableHandles.TestAutoIncNotInteger + global::SpacetimeDB.Internal.TableHandles.TestAutoIncNotInteger >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::TestDefaultFieldValues, - SpacetimeDB.Internal.TableHandles.TestDefaultFieldValues + global::SpacetimeDB.Internal.TableHandles.TestDefaultFieldValues >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::TestDuplicateTableName, - SpacetimeDB.Internal.TableHandles.TestDuplicateTableName + global::SpacetimeDB.Internal.TableHandles.TestDuplicateTableName >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::TestIndexIssues, - SpacetimeDB.Internal.TableHandles.TestIndexIssues + global::SpacetimeDB.Internal.TableHandles.TestIndexIssues >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::TestScheduleIssues, - SpacetimeDB.Internal.TableHandles.TestScheduleWithMissingScheduleAtField + global::SpacetimeDB.Internal.TableHandles.TestScheduleWithMissingScheduleAtField >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::TestScheduleIssues, - SpacetimeDB.Internal.TableHandles.TestScheduleWithoutPrimaryKey + global::SpacetimeDB.Internal.TableHandles.TestScheduleWithoutPrimaryKey >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::TestScheduleIssues, - SpacetimeDB.Internal.TableHandles.TestScheduleWithoutScheduleAt + global::SpacetimeDB.Internal.TableHandles.TestScheduleWithoutScheduleAt >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::TestScheduleIssues, - SpacetimeDB.Internal.TableHandles.TestScheduleWithWrongPrimaryKeyType + global::SpacetimeDB.Internal.TableHandles.TestScheduleWithWrongPrimaryKeyType >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::TestScheduleIssues, - SpacetimeDB.Internal.TableHandles.TestScheduleWithWrongScheduleAtType + global::SpacetimeDB.Internal.TableHandles.TestScheduleWithWrongScheduleAtType >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::TestUniqueNotEquatable, - SpacetimeDB.Internal.TableHandles.TestUniqueNotEquatable + global::SpacetimeDB.Internal.TableHandles.TestUniqueNotEquatable >(); - SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_FILTER); - SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_FOURTH_FILTER); - SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_SECOND_FILTER); - SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter(global::Module.MY_THIRD_FILTER); + builder.RegisterClientVisibilityFilter(global::Module.MY_FILTER); + builder.RegisterClientVisibilityFilter(global::Module.MY_FOURTH_FILTER); + builder.RegisterClientVisibilityFilter(global::Module.MY_SECOND_FILTER); + builder.RegisterClientVisibilityFilter(global::Module.MY_THIRD_FILTER); { var value = new SpacetimeDB.BSATN.String(); __memoryStream.Position = 0; __memoryStream.SetLength(0); value.Write(__writer, "A default string set by attribute"); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 1, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 1, array); } { @@ -3562,11 +4815,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 10, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 10, array); } { @@ -3575,11 +4824,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 11, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 11, array); } { @@ -3588,11 +4833,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 12, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 12, array); } { @@ -3601,11 +4842,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2F); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 13, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 13, array); } { @@ -3614,11 +4851,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 14, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 14, array); } { @@ -3627,11 +4860,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, (MyEnum)2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 15, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 15, array); } { @@ -3640,11 +4869,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, null); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 16, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 16, array); } { @@ -3653,11 +4878,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, true); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 2, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 2, array); } { @@ -3666,11 +4887,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 3, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 3, array); } { @@ -3679,11 +4896,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 4, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 4, array); } { @@ -3692,11 +4905,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 5, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 5, array); } { @@ -3705,11 +4914,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 6, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 6, array); } { @@ -3718,11 +4923,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 7, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 7, array); } { @@ -3731,11 +4932,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 8, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 8, array); } { @@ -3744,11 +4941,7 @@ public static void Main() __memoryStream.SetLength(0); value.Write(__writer, 2); var array = __memoryStream.ToArray(); - SpacetimeDB.Internal.Module.RegisterTableDefaultValue( - "TestDefaultFieldValues", - 9, - array - ); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 9, array); } } @@ -4537,110 +5730,165 @@ public static SpacetimeDB.Internal.Errno __call_reducer__( SpacetimeDB.Timestamp timestamp, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink error + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.ReducerCount + ) + return global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.CallLocalReducer( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + localId -= global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .ReducerCount; + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); +#else + return CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error ) => id switch { - 0 - => __call_reducer_0( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 1 - => __call_reducer_1( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 2 - => __call_reducer_2( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 3 - => __call_reducer_3( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 4 - => __call_reducer_4( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 5 - => __call_reducer_5( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 6 - => __call_reducer_6( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 7 - => __call_reducer_7( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - _ - => SpacetimeDB.Internal.Module.WriteReducerError( - error, - new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") - ) + 0 => __call_reducer_0( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 1 => __call_reducer_1( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 2 => __call_reducer_2( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 3 => __call_reducer_3( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 4 => __call_reducer_4( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 5 => __call_reducer_5( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 6 => __call_reducer_6( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 7 => __call_reducer_7( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + _ => SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -4657,15 +5905,76 @@ public static SpacetimeDB.Internal.Errno __call_procedure__( SpacetimeDB.Timestamp timestamp, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink result_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .ProcedureCount + ) + return global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.CallLocalProcedure( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + localId -= global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .ProcedureCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); +#else + return CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink ) => id switch { - _ - => throw new System.ArgumentOutOfRangeException( - nameof(id), - id, - "Unknown procedure id" - ) + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown procedure id" + ), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -4678,15 +5987,64 @@ public static SpacetimeDB.Internal.Errno __call_http_handler__( SpacetimeDB.Internal.BytesSource request_body, SpacetimeDB.Internal.BytesSink response_sink, SpacetimeDB.Internal.BytesSink response_body_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .HttpHandlerCount + ) + return global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.CallLocalHttpHandler( + localId, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + localId -= global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .HttpHandlerCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); +#else + return CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource request, + SpacetimeDB.Internal.BytesSource request_body, + SpacetimeDB.Internal.BytesSink response_sink, + SpacetimeDB.Internal.BytesSink response_body_sink ) => id switch { - _ - => throw new System.ArgumentOutOfRangeException( - nameof(id), - id, - "Unknown HTTP handler id" - ) + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown HTTP handler id" + ), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -4700,6 +6058,42 @@ public static SpacetimeDB.Internal.Errno __call_view__( ulong sender_3, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint)global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.ViewCount + ) + return global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.CallLocalView( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + localId -= global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.ViewCount; + return UnknownViewId(id); +#else + return CallLocalView(id, sender_0, sender_1, sender_2, sender_3, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink ) => id switch { @@ -4715,7 +6109,7 @@ SpacetimeDB.Internal.BytesSink sink 9 => __call_view_9(sender_0, sender_1, sender_2, sender_3, args, sink), 10 => __call_view_10(sender_0, sender_1, sender_2, sender_3, args, sink), 11 => __call_view_11(sender_0, sender_1, sender_2, sender_3, args, sink), - _ => UnknownViewId(id) + _ => UnknownViewId(id), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -4725,6 +6119,43 @@ public static SpacetimeDB.Internal.Errno __call_view_anon__( int id, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownAnonymousViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .AnonymousViewCount + ) + return global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.CallLocalAnonymousView( + localId, + args, + sink + ); + localId -= global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .AnonymousViewCount; + return UnknownAnonymousViewId(id); +#else + return CallLocalAnonymousView(id, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink ) => id switch { @@ -4732,7 +6163,7 @@ SpacetimeDB.Internal.BytesSink sink 1 => __call_view_anon_1(args, sink), 2 => __call_view_anon_2(args, sink), 3 => __call_view_anon_3(args, sink), - _ => UnknownAnonymousViewId(id) + _ => UnknownAnonymousViewId(id), }; private static SpacetimeDB.Internal.Errno UnknownViewId(int id) diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#Player.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#Player.verified.cs index ff392b76903..afcd60afc5b 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#Player.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#Player.verified.cs @@ -44,7 +44,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar registrar.RegisterType(_ => new SpacetimeDB.BSATN.AlgebraicType.Product( new SpacetimeDB.BSATN.AggregateElement[] { - new("Identity", IdentityRW.GetAlgebraicType(registrar)) + new("Identity", IdentityRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestAutoIncNotInteger.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestAutoIncNotInteger.verified.cs index 7efaa55cdcb..089c7521c72 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestAutoIncNotInteger.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestAutoIncNotInteger.verified.cs @@ -51,7 +51,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new SpacetimeDB.BSATN.AggregateElement[] { new("AutoIncField", AutoIncFieldRW.GetAlgebraicType(registrar)), - new("IdentityField", IdentityFieldRW.GetAlgebraicType(registrar)) + new("IdentityField", IdentityFieldRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestDefaultFieldValues.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestDefaultFieldValues.verified.cs index de8c4cfdb03..bf5c8f0b4fc 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestDefaultFieldValues.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestDefaultFieldValues.verified.cs @@ -117,7 +117,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new("DefaultF32", DefaultF32RW.GetAlgebraicType(registrar)), new("DefaultF64", DefaultF64RW.GetAlgebraicType(registrar)), new("DefaultEnum", DefaultEnumRW.GetAlgebraicType(registrar)), - new("DefaultNull", DefaultNullRW.GetAlgebraicType(registrar)) + new("DefaultNull", DefaultNullRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestIndexIssues.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestIndexIssues.verified.cs index 862805ded3e..3dd8a0a7425 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestIndexIssues.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestIndexIssues.verified.cs @@ -54,7 +54,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new( "SecondaryIndexingColumn", SecondaryIndexingColumnRW.GetAlgebraicType(registrar) - ) + ), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestScheduleIssues.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestScheduleIssues.verified.cs index 858ed058a53..cfbfc151870 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestScheduleIssues.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestScheduleIssues.verified.cs @@ -65,7 +65,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new( "ScheduleAtCorrectType", ScheduleAtCorrectTypeRW.GetAlgebraicType(registrar) - ) + ), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestTableTaggedEnum.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestTableTaggedEnum.verified.cs index 7e321681b88..38190b0b5f7 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestTableTaggedEnum.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestTableTaggedEnum.verified.cs @@ -27,10 +27,9 @@ public TestTableTaggedEnum Read(System.IO.BinaryReader reader) { 0 => new X(XRW.Read(reader)), 1 => new Y(YRW.Read(reader)), - _ - => throw new System.InvalidOperationException( - "Invalid tag value, this state should be unreachable." - ) + _ => throw new System.InvalidOperationException( + "Invalid tag value, this state should be unreachable." + ), }; } @@ -57,7 +56,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new SpacetimeDB.BSATN.AggregateElement[] { new("X", XRW.GetAlgebraicType(registrar)), - new("Y", YRW.GetAlgebraicType(registrar)) + new("Y", YRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestUniqueNotEquatable.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestUniqueNotEquatable.verified.cs index 3c5ecbf67ff..c635f1a06ee 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestUniqueNotEquatable.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module#TestUniqueNotEquatable.verified.cs @@ -55,7 +55,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new SpacetimeDB.BSATN.AggregateElement[] { new("UniqueField", UniqueFieldRW.GetAlgebraicType(registrar)), - new("PrimaryKeyField", PrimaryKeyFieldRW.GetAlgebraicType(registrar)) + new("PrimaryKeyField", PrimaryKeyFieldRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#FFI.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#FFI.verified.cs new file mode 100644 index 00000000000..34a847d2e03 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#FFI.verified.cs @@ -0,0 +1,6597 @@ +//HintName: FFI.cs +// +#nullable enable +// .NET 8 generates a module-local LocalReadOnly which shadows the runtime shell. +#pragma warning disable CS0436 +#pragma warning disable STDB_UNSTABLE + +#if NET10_0_OR_GREATER +global using SpacetimeDB.Generated.diag_4F830E2879BB50E3; +#endif +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Internal = SpacetimeDB.Internal; +using TxContext = SpacetimeDB.Internal.TxContext; +#if NET10_0_OR_GREATER +[assembly: global::SpacetimeDB.ModuleDescriptorAttribute( + typeof(global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor) +)] + +#endif + +namespace SpacetimeDB +{ +#if !NET10_0_OR_GREATER + public readonly struct TestDuplicateTableNameCols + { + internal TestDuplicateTableNameCols(string tableName) { } + } + + public readonly struct TestDuplicateTableNameIxCols + { + internal TestDuplicateTableNameIxCols(string tableName) { } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::InAnotherNamespace.TestDuplicateTableName, + TestDuplicateTableNameCols, + TestDuplicateTableNameIxCols + > TestDuplicateTableName() => + new( + "TestDuplicateTableName", + new TestDuplicateTableNameCols("TestDuplicateTableName"), + new TestDuplicateTableNameIxCols("TestDuplicateTableName") + ); + } + + public readonly struct PlayerCols + { + public readonly global::SpacetimeDB.Col Identity; + + internal PlayerCols(string tableName) + { + Identity = new global::SpacetimeDB.Col( + tableName, + "Identity" + ); + } + } + + public readonly struct PlayerIxCols + { + internal PlayerIxCols(string tableName) { } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table Player() => + new("Player", new PlayerCols("Player"), new PlayerIxCols("Player")); + } + + public readonly struct TestAutoIncNotIntegerCols + { + public readonly global::SpacetimeDB.Col AutoIncField; + public readonly global::SpacetimeDB.Col< + global::TestAutoIncNotInteger, + string + > IdentityField; + + internal TestAutoIncNotIntegerCols(string tableName) + { + AutoIncField = new global::SpacetimeDB.Col( + tableName, + "AutoIncField" + ); + IdentityField = new global::SpacetimeDB.Col( + tableName, + "IdentityField" + ); + } + } + + public readonly struct TestAutoIncNotIntegerIxCols + { + internal TestAutoIncNotIntegerIxCols(string tableName) { } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::TestAutoIncNotInteger, + TestAutoIncNotIntegerCols, + TestAutoIncNotIntegerIxCols + > TestAutoIncNotInteger() => + new( + "TestAutoIncNotInteger", + new TestAutoIncNotIntegerCols("TestAutoIncNotInteger"), + new TestAutoIncNotIntegerIxCols("TestAutoIncNotInteger") + ); + } + + public readonly struct TestDefaultFieldValuesCols + { + public readonly global::SpacetimeDB.Col UniqueField; + public readonly global::SpacetimeDB.Col< + global::TestDefaultFieldValues, + string + > DefaultString; + public readonly global::SpacetimeDB.Col DefaultBool; + public readonly global::SpacetimeDB.Col DefaultI8; + public readonly global::SpacetimeDB.Col DefaultU8; + public readonly global::SpacetimeDB.Col DefaultI16; + public readonly global::SpacetimeDB.Col DefaultU16; + public readonly global::SpacetimeDB.Col DefaultI32; + public readonly global::SpacetimeDB.Col DefaultU32; + public readonly global::SpacetimeDB.Col DefaultI64; + public readonly global::SpacetimeDB.Col DefaultU64; + public readonly global::SpacetimeDB.Col DefaultHex; + public readonly global::SpacetimeDB.Col DefaultBin; + public readonly global::SpacetimeDB.Col DefaultF32; + public readonly global::SpacetimeDB.Col DefaultF64; + public readonly global::SpacetimeDB.Col DefaultEnum; + public readonly global::SpacetimeDB.Col< + global::TestDefaultFieldValues, + MyStruct + > DefaultNull; + + internal TestDefaultFieldValuesCols(string tableName) + { + UniqueField = new global::SpacetimeDB.Col( + tableName, + "UniqueField" + ); + DefaultString = new global::SpacetimeDB.Col( + tableName, + "DefaultString" + ); + DefaultBool = new global::SpacetimeDB.Col( + tableName, + "DefaultBool" + ); + DefaultI8 = new global::SpacetimeDB.Col( + tableName, + "DefaultI8" + ); + DefaultU8 = new global::SpacetimeDB.Col( + tableName, + "DefaultU8" + ); + DefaultI16 = new global::SpacetimeDB.Col( + tableName, + "DefaultI16" + ); + DefaultU16 = new global::SpacetimeDB.Col( + tableName, + "DefaultU16" + ); + DefaultI32 = new global::SpacetimeDB.Col( + tableName, + "DefaultI32" + ); + DefaultU32 = new global::SpacetimeDB.Col( + tableName, + "DefaultU32" + ); + DefaultI64 = new global::SpacetimeDB.Col( + tableName, + "DefaultI64" + ); + DefaultU64 = new global::SpacetimeDB.Col( + tableName, + "DefaultU64" + ); + DefaultHex = new global::SpacetimeDB.Col( + tableName, + "DefaultHex" + ); + DefaultBin = new global::SpacetimeDB.Col( + tableName, + "DefaultBin" + ); + DefaultF32 = new global::SpacetimeDB.Col( + tableName, + "DefaultF32" + ); + DefaultF64 = new global::SpacetimeDB.Col( + tableName, + "DefaultF64" + ); + DefaultEnum = new global::SpacetimeDB.Col( + tableName, + "DefaultEnum" + ); + DefaultNull = new global::SpacetimeDB.Col( + tableName, + "DefaultNull" + ); + } + } + + public readonly struct TestDefaultFieldValuesIxCols + { + internal TestDefaultFieldValuesIxCols(string tableName) { } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::TestDefaultFieldValues, + TestDefaultFieldValuesCols, + TestDefaultFieldValuesIxCols + > TestDefaultFieldValues() => + new( + "TestDefaultFieldValues", + new TestDefaultFieldValuesCols("TestDefaultFieldValues"), + new TestDefaultFieldValuesIxCols("TestDefaultFieldValues") + ); + } + + public readonly struct TestDuplicateTableNameCols + { + internal TestDuplicateTableNameCols(string tableName) { } + } + + public readonly struct TestDuplicateTableNameIxCols + { + internal TestDuplicateTableNameIxCols(string tableName) { } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::TestDuplicateTableName, + TestDuplicateTableNameCols, + TestDuplicateTableNameIxCols + > TestDuplicateTableName() => + new( + "TestDuplicateTableName", + new TestDuplicateTableNameCols("TestDuplicateTableName"), + new TestDuplicateTableNameIxCols("TestDuplicateTableName") + ); + } + + public readonly struct TestIndexIssuesCols + { + public readonly global::SpacetimeDB.Col SelfIndexingColumn; + public readonly global::SpacetimeDB.Col< + global::TestIndexIssues, + int + > SecondaryIndexingColumn; + + internal TestIndexIssuesCols(string tableName) + { + SelfIndexingColumn = new global::SpacetimeDB.Col( + tableName, + "SelfIndexingColumn" + ); + SecondaryIndexingColumn = new global::SpacetimeDB.Col( + tableName, + "SecondaryIndexingColumn" + ); + } + } + + public readonly struct TestIndexIssuesIxCols + { + public readonly global::SpacetimeDB.IxCol SelfIndexingColumn; + public readonly global::SpacetimeDB.IxCol< + global::TestIndexIssues, + int + > SecondaryIndexingColumn; + + internal TestIndexIssuesIxCols(string tableName) + { + SelfIndexingColumn = new global::SpacetimeDB.IxCol( + tableName, + "SelfIndexingColumn" + ); + SecondaryIndexingColumn = new global::SpacetimeDB.IxCol( + tableName, + "SecondaryIndexingColumn" + ); + } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::TestIndexIssues, + TestIndexIssuesCols, + TestIndexIssuesIxCols + > TestIndexIssues() => + new( + "TestIndexIssues", + new TestIndexIssuesCols("TestIndexIssues"), + new TestIndexIssuesIxCols("TestIndexIssues") + ); + } + + public readonly struct TestScheduleWithoutPrimaryKeyCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithoutPrimaryKeyCols(string tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithoutPrimaryKeyIxCols + { + internal TestScheduleWithoutPrimaryKeyIxCols(string tableName) { } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithoutPrimaryKeyCols, + TestScheduleWithoutPrimaryKeyIxCols + > TestScheduleWithoutPrimaryKey() => + new( + "TestScheduleWithoutPrimaryKey", + new TestScheduleWithoutPrimaryKeyCols("TestScheduleWithoutPrimaryKey"), + new TestScheduleWithoutPrimaryKeyIxCols("TestScheduleWithoutPrimaryKey") + ); + } + + public readonly struct TestScheduleWithWrongPrimaryKeyTypeCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithWrongPrimaryKeyTypeCols(string tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithWrongPrimaryKeyTypeIxCols + { + public readonly global::SpacetimeDB.IxCol IdWrongType; + + internal TestScheduleWithWrongPrimaryKeyTypeIxCols(string tableName) + { + IdWrongType = new global::SpacetimeDB.IxCol( + tableName, + "IdWrongType" + ); + } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithWrongPrimaryKeyTypeCols, + TestScheduleWithWrongPrimaryKeyTypeIxCols + > TestScheduleWithWrongPrimaryKeyType() => + new( + "TestScheduleWithWrongPrimaryKeyType", + new TestScheduleWithWrongPrimaryKeyTypeCols("TestScheduleWithWrongPrimaryKeyType"), + new TestScheduleWithWrongPrimaryKeyTypeIxCols("TestScheduleWithWrongPrimaryKeyType") + ); + } + + public readonly struct TestScheduleWithoutScheduleAtCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithoutScheduleAtCols(string tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithoutScheduleAtIxCols + { + public readonly global::SpacetimeDB.IxCol IdCorrectType; + + internal TestScheduleWithoutScheduleAtIxCols(string tableName) + { + IdCorrectType = new global::SpacetimeDB.IxCol( + tableName, + "IdCorrectType" + ); + } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithoutScheduleAtCols, + TestScheduleWithoutScheduleAtIxCols + > TestScheduleWithoutScheduleAt() => + new( + "TestScheduleWithoutScheduleAt", + new TestScheduleWithoutScheduleAtCols("TestScheduleWithoutScheduleAt"), + new TestScheduleWithoutScheduleAtIxCols("TestScheduleWithoutScheduleAt") + ); + } + + public readonly struct TestScheduleWithWrongScheduleAtTypeCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithWrongScheduleAtTypeCols(string tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithWrongScheduleAtTypeIxCols + { + public readonly global::SpacetimeDB.IxCol IdCorrectType; + + internal TestScheduleWithWrongScheduleAtTypeIxCols(string tableName) + { + IdCorrectType = new global::SpacetimeDB.IxCol( + tableName, + "IdCorrectType" + ); + } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithWrongScheduleAtTypeCols, + TestScheduleWithWrongScheduleAtTypeIxCols + > TestScheduleWithWrongScheduleAtType() => + new( + "TestScheduleWithWrongScheduleAtType", + new TestScheduleWithWrongScheduleAtTypeCols("TestScheduleWithWrongScheduleAtType"), + new TestScheduleWithWrongScheduleAtTypeIxCols("TestScheduleWithWrongScheduleAtType") + ); + } + + public readonly struct TestScheduleWithMissingScheduleAtFieldCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithMissingScheduleAtFieldCols(string tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithMissingScheduleAtFieldIxCols + { + internal TestScheduleWithMissingScheduleAtFieldIxCols(string tableName) { } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithMissingScheduleAtFieldCols, + TestScheduleWithMissingScheduleAtFieldIxCols + > TestScheduleWithMissingScheduleAtField() => + new( + "TestScheduleWithMissingScheduleAtField", + new TestScheduleWithMissingScheduleAtFieldCols( + "TestScheduleWithMissingScheduleAtField" + ), + new TestScheduleWithMissingScheduleAtFieldIxCols( + "TestScheduleWithMissingScheduleAtField" + ) + ); + } + + public readonly struct TestUniqueNotEquatableCols + { + public readonly global::SpacetimeDB.Col UniqueField; + public readonly global::SpacetimeDB.Col< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + > PrimaryKeyField; + + internal TestUniqueNotEquatableCols(string tableName) + { + UniqueField = new global::SpacetimeDB.Col( + tableName, + "UniqueField" + ); + PrimaryKeyField = new global::SpacetimeDB.Col< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + >(tableName, "PrimaryKeyField"); + } + } + + public readonly struct TestUniqueNotEquatableIxCols + { + public readonly global::SpacetimeDB.IxCol< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + > PrimaryKeyField; + + internal TestUniqueNotEquatableIxCols(string tableName) + { + PrimaryKeyField = new global::SpacetimeDB.IxCol< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + >(tableName, "PrimaryKeyField"); + } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::TestUniqueNotEquatable, + TestUniqueNotEquatableCols, + TestUniqueNotEquatableIxCols + > TestUniqueNotEquatable() => + new( + "TestUniqueNotEquatable", + new TestUniqueNotEquatableCols("TestUniqueNotEquatable"), + new TestUniqueNotEquatableIxCols("TestUniqueNotEquatable") + ); + } +#endif + + internal static class Handlers { } + +#if !NET10_0_OR_GREATER + public sealed record ReducerContext : DbContext, Internal.IReducerContext + { + public global::SpacetimeDB.ModuleEnvironment Env => default; + public readonly Identity Sender; + public readonly ConnectionId? ConnectionId; + public readonly Random Rng; + public readonly Timestamp Timestamp; + public readonly AuthCtx SenderAuth; + + // **Note:** must be 0..=u32::MAX + internal int CounterUuid; + public Identity DatabaseIdentity => Internal.IReducerContext.GetDatabaseIdentity(); + + // We keep this property for compatibility with existing module code. + [global::System.Obsolete( + "ReducerContext.Identity is deprecated. Use DatabaseIdentity instead." + )] + public Identity Identity => DatabaseIdentity; + + internal ReducerContext( + Identity identity, + ConnectionId? connectionId, + Random random, + Timestamp time, + AuthCtx? senderAuth = null + ) + { + Sender = identity; + ConnectionId = connectionId; + Rng = random; + Timestamp = time; + SenderAuth = senderAuth ?? AuthCtx.BuildFromSystemTables(connectionId, identity); + CounterUuid = 0; + } + + /// + /// Create a new random `v4` using the built-in RNG. + /// + /// + /// This method fills the random bytes using the context RNG. + /// + /// + /// + /// var uuid = ctx.NewUuidV4(); + /// Log.Info(uuid); + /// + /// + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + /// + /// Create a new sortable `v7` using the built-in RNG, monotonic counter, + /// and timestamp. + /// + /// + /// A newly generated `v7` that is monotonically ordered + /// and suitable for use as a primary key or for ordered storage. + /// + /// + /// Thrown if generation fails. + /// + /// + /// + /// [SpacetimeDB.Reducer] + /// public static Guid GenerateUuidV7(ReducerContext ctx) + /// { + /// Guid uuid = ctx.NewUuidV7(); + /// Log.Info(uuid); + /// } + /// + /// + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } + } + + public sealed partial class ProcedureContext : global::SpacetimeDB.ProcedureContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + private readonly Local _db = new(); + + internal ProcedureContext( + Identity identity, + ConnectionId? connectionId, + Random random, + Timestamp time + ) + : base(identity, connectionId, random, time) { } + + protected override global::SpacetimeDB.LocalBase CreateLocal() => _db; + + protected override global::SpacetimeDB.ProcedureTxContextBase CreateTxContext( + Internal.TxContext inner + ) => _cached ??= new ProcedureTxContext(inner); + + private ProcedureTxContext? _cached; + + public Local Db => _db; + + public TResult WithTx(Func body) => + base.WithTx(tx => body((ProcedureTxContext)tx)); + + public TxOutcome TryWithTx( + Func> body + ) + where TError : Exception => base.TryWithTx(tx => body((ProcedureTxContext)tx)); + + /// + /// Create a new random `v4` using the built-in RNG. + /// + /// + /// This method fills the random bytes using the context RNG. + /// + /// + /// + /// var uuid = ctx.NewUuidV4(); + /// Log.Info(uuid); + /// + /// + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + /// + /// Create a new sortable `v7` using the built-in RNG, monotonic counter, + /// and timestamp. + /// + /// + /// A newly generated `v7` that is monotonically ordered + /// and suitable for use as a primary key or for ordered storage. + /// + /// + /// Thrown if UUID generation fails. + /// + /// + /// + /// [SpacetimeDB.Procedure] + /// public static Guid GenerateUuidV7(ReducerContext ctx) + /// { + /// Guid uuid = ctx.NewUuidV7(); + /// Log.Info(uuid); + /// } + /// + /// + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } + } + + public sealed partial class HandlerContext : global::SpacetimeDB.HandlerContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + private readonly Local _db = new(); + + internal HandlerContext(Random random, Timestamp time) + : base(random, time) { } + + protected override global::SpacetimeDB.LocalBase CreateLocal() => _db; + + protected override global::SpacetimeDB.HandlerTxContextBase CreateTxContext( + Internal.TxContext inner + ) => _cached ??= new HandlerTxContext(inner); + + private HandlerTxContext? _cached; + + [Experimental("STDB_UNSTABLE")] + public TResult WithTx(Func body) => + base.WithTx(tx => body((HandlerTxContext)tx)); + + [Experimental("STDB_UNSTABLE")] + public TxOutcome TryWithTx( + Func> body + ) + where TError : Exception => base.TryWithTx(tx => body((HandlerTxContext)tx)); + + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } + } + + public sealed class ProcedureTxContext : global::SpacetimeDB.ProcedureTxContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + + internal ProcedureTxContext(Internal.TxContext inner) + : base(inner) { } + + public new Local Db => (Local)base.Db; + } + + [Experimental("STDB_UNSTABLE")] + public sealed class HandlerTxContext : global::SpacetimeDB.HandlerTxContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + + internal HandlerTxContext(Internal.TxContext inner) + : base(inner) { } + + public new Local Db => (Local)base.Db; + } + + public sealed class Local : global::SpacetimeDB.LocalBase + { + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.Player Player => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestAutoIncNotInteger TestAutoIncNotInteger => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestDefaultFieldValues TestDefaultFieldValues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestDuplicateTableName TestDuplicateTableName => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestIndexIssues TestIndexIssues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithMissingScheduleAtField TestScheduleWithMissingScheduleAtField => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithoutPrimaryKey TestScheduleWithoutPrimaryKey => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithoutScheduleAt TestScheduleWithoutScheduleAt => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithWrongPrimaryKeyType TestScheduleWithWrongPrimaryKeyType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithWrongScheduleAtType TestScheduleWithWrongScheduleAtType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestUniqueNotEquatable TestUniqueNotEquatable => + new(); + } + + public sealed record ViewContext : DbContext, Internal.IViewContext + { + public Identity Sender { get; } + + public global::SpacetimeDB.ModuleEnvironment Env => default; + public QueryBuilder From => default; + + internal ViewContext(Identity sender, Internal.LocalReadOnly db) + : base(db) + { + Sender = sender; + } + } + + public sealed record AnonymousViewContext + : DbContext, + Internal.IAnonymousViewContext + { + public global::SpacetimeDB.ModuleEnvironment Env => default; + public QueryBuilder From => default; + + internal AnonymousViewContext(Internal.LocalReadOnly db) + : base(db) { } + } +#endif +} + +#if NET10_0_OR_GREATER +namespace SpacetimeDB.Generated.diag_4F830E2879BB50E3 +{ + public static partial class AssemblyDescriptor + { + public const string? CaseConversionPolicy = "SnakeCase"; + public const string RootOnlyDeclarations = + "row-level security filters, lifecycle reducer Reducers.TestDuplicateReducerKind1 (Init), lifecycle reducer Reducers.TestDuplicateReducerKind2 (Init)"; + public const int ReducerCount = 8; + public const int ProcedureCount = 0; + public const int HttpHandlerCount = 0; + public const int ViewCount = 12; + public const int AnonymousViewCount = 4; + + public static global::SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink error + ) => + global::ModuleRegistration.CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink result_sink + ) => + global::ModuleRegistration.CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource request, + global::SpacetimeDB.Internal.BytesSource request_body, + global::SpacetimeDB.Internal.BytesSink response_sink, + global::SpacetimeDB.Internal.BytesSink response_body_sink + ) => + global::ModuleRegistration.CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => + global::ModuleRegistration.CallLocalView( + id, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => global::ModuleRegistration.CallLocalAnonymousView(id, args, sink); + + public static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) => global::ModuleRegistration.Register(builder, httpBuilder); + + public readonly struct Tables + { + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.Player Player => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestAutoIncNotInteger TestAutoIncNotInteger => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestDefaultFieldValues TestDefaultFieldValues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestDuplicateTableName TestDuplicateTableName => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestIndexIssues TestIndexIssues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithMissingScheduleAtField TestScheduleWithMissingScheduleAtField => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithoutPrimaryKey TestScheduleWithoutPrimaryKey => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithoutScheduleAt TestScheduleWithoutScheduleAt => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithWrongPrimaryKeyType TestScheduleWithWrongPrimaryKeyType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithWrongScheduleAtType TestScheduleWithWrongScheduleAtType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestUniqueNotEquatable TestUniqueNotEquatable => + new(); + } + + public readonly struct ReadOnlyTables + { + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.PlayerReadOnly Player => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestAutoIncNotIntegerReadOnly TestAutoIncNotInteger => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestDefaultFieldValuesReadOnly TestDefaultFieldValues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestDuplicateTableNameReadOnly TestDuplicateTableName => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestIndexIssuesReadOnly TestIndexIssues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithMissingScheduleAtFieldReadOnly TestScheduleWithMissingScheduleAtField => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithoutPrimaryKeyReadOnly TestScheduleWithoutPrimaryKey => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithoutScheduleAtReadOnly TestScheduleWithoutScheduleAt => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithWrongPrimaryKeyTypeReadOnly TestScheduleWithWrongPrimaryKeyType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithWrongScheduleAtTypeReadOnly TestScheduleWithWrongScheduleAtType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestUniqueNotEquatableReadOnly TestUniqueNotEquatable => + new(); + } + + public readonly partial struct Queries { } + } + + public static class LocalTableExtensions + { + extension(global::SpacetimeDB.Local db) + { + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.Player Player => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestAutoIncNotInteger TestAutoIncNotInteger => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestDefaultFieldValues TestDefaultFieldValues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestDuplicateTableName TestDuplicateTableName => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestIndexIssues TestIndexIssues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithMissingScheduleAtField TestScheduleWithMissingScheduleAtField => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithoutPrimaryKey TestScheduleWithoutPrimaryKey => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithoutScheduleAt TestScheduleWithoutScheduleAt => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithWrongPrimaryKeyType TestScheduleWithWrongPrimaryKeyType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithWrongScheduleAtType TestScheduleWithWrongScheduleAtType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestUniqueNotEquatable TestUniqueNotEquatable => + new(); + } + } + + public static class ReadOnlyTableExtensions + { + extension(global::SpacetimeDB.Internal.LocalReadOnly db) + { + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.PlayerReadOnly Player => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestAutoIncNotIntegerReadOnly TestAutoIncNotInteger => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestDefaultFieldValuesReadOnly TestDefaultFieldValues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestDuplicateTableNameReadOnly TestDuplicateTableName => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestIndexIssuesReadOnly TestIndexIssues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithMissingScheduleAtFieldReadOnly TestScheduleWithMissingScheduleAtField => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithoutPrimaryKeyReadOnly TestScheduleWithoutPrimaryKey => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithoutScheduleAtReadOnly TestScheduleWithoutScheduleAt => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithWrongPrimaryKeyTypeReadOnly TestScheduleWithWrongPrimaryKeyType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithWrongScheduleAtTypeReadOnly TestScheduleWithWrongScheduleAtType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestUniqueNotEquatableReadOnly TestUniqueNotEquatable => + new(); + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) { } + } + + public readonly struct TestDuplicateTableNameCols + { + internal TestDuplicateTableNameCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public readonly struct TestDuplicateTableNameIxCols + { + internal TestDuplicateTableNameIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestDuplicateTableNameSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestDuplicateTableName" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestDuplicateTableNameSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::InAnotherNamespace.TestDuplicateTableName, + TestDuplicateTableNameCols, + TestDuplicateTableNameIxCols + > TestDuplicateTableName() + { + var tableName = TestDuplicateTableNameSqlNameCache.Name; + return new( + tableName, + new TestDuplicateTableNameCols(tableName), + new TestDuplicateTableNameIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::InAnotherNamespace.TestDuplicateTableName, + TestDuplicateTableNameCols, + TestDuplicateTableNameIxCols + > TestDuplicateTableName() => new AssemblyDescriptor.Queries().TestDuplicateTableName(); + } + } + + public readonly struct PlayerCols + { + public readonly global::SpacetimeDB.Col Identity; + + internal PlayerCols(global::SpacetimeDB.SqlTableName tableName) + { + Identity = new global::SpacetimeDB.Col( + tableName, + "Identity" + ); + } + } + + public readonly struct PlayerIxCols + { + internal PlayerIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class PlayerSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "Player" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PlayerSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table Player() + { + var tableName = PlayerSqlNameCache.Name; + return new(tableName, new PlayerCols(tableName), new PlayerIxCols(tableName)); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table Player() => + new AssemblyDescriptor.Queries().Player(); + } + } + + public readonly struct TestAutoIncNotIntegerCols + { + public readonly global::SpacetimeDB.Col AutoIncField; + public readonly global::SpacetimeDB.Col< + global::TestAutoIncNotInteger, + string + > IdentityField; + + internal TestAutoIncNotIntegerCols(global::SpacetimeDB.SqlTableName tableName) + { + AutoIncField = new global::SpacetimeDB.Col( + tableName, + "AutoIncField" + ); + IdentityField = new global::SpacetimeDB.Col( + tableName, + "IdentityField" + ); + } + } + + public readonly struct TestAutoIncNotIntegerIxCols + { + internal TestAutoIncNotIntegerIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestAutoIncNotIntegerSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestAutoIncNotInteger" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestAutoIncNotIntegerSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestAutoIncNotInteger, + TestAutoIncNotIntegerCols, + TestAutoIncNotIntegerIxCols + > TestAutoIncNotInteger() + { + var tableName = TestAutoIncNotIntegerSqlNameCache.Name; + return new( + tableName, + new TestAutoIncNotIntegerCols(tableName), + new TestAutoIncNotIntegerIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestAutoIncNotInteger, + TestAutoIncNotIntegerCols, + TestAutoIncNotIntegerIxCols + > TestAutoIncNotInteger() => new AssemblyDescriptor.Queries().TestAutoIncNotInteger(); + } + } + + public readonly struct TestDefaultFieldValuesCols + { + public readonly global::SpacetimeDB.Col UniqueField; + public readonly global::SpacetimeDB.Col< + global::TestDefaultFieldValues, + string + > DefaultString; + public readonly global::SpacetimeDB.Col DefaultBool; + public readonly global::SpacetimeDB.Col DefaultI8; + public readonly global::SpacetimeDB.Col DefaultU8; + public readonly global::SpacetimeDB.Col DefaultI16; + public readonly global::SpacetimeDB.Col DefaultU16; + public readonly global::SpacetimeDB.Col DefaultI32; + public readonly global::SpacetimeDB.Col DefaultU32; + public readonly global::SpacetimeDB.Col DefaultI64; + public readonly global::SpacetimeDB.Col DefaultU64; + public readonly global::SpacetimeDB.Col DefaultHex; + public readonly global::SpacetimeDB.Col DefaultBin; + public readonly global::SpacetimeDB.Col DefaultF32; + public readonly global::SpacetimeDB.Col DefaultF64; + public readonly global::SpacetimeDB.Col DefaultEnum; + public readonly global::SpacetimeDB.Col< + global::TestDefaultFieldValues, + MyStruct + > DefaultNull; + + internal TestDefaultFieldValuesCols(global::SpacetimeDB.SqlTableName tableName) + { + UniqueField = new global::SpacetimeDB.Col( + tableName, + "UniqueField" + ); + DefaultString = new global::SpacetimeDB.Col( + tableName, + "DefaultString" + ); + DefaultBool = new global::SpacetimeDB.Col( + tableName, + "DefaultBool" + ); + DefaultI8 = new global::SpacetimeDB.Col( + tableName, + "DefaultI8" + ); + DefaultU8 = new global::SpacetimeDB.Col( + tableName, + "DefaultU8" + ); + DefaultI16 = new global::SpacetimeDB.Col( + tableName, + "DefaultI16" + ); + DefaultU16 = new global::SpacetimeDB.Col( + tableName, + "DefaultU16" + ); + DefaultI32 = new global::SpacetimeDB.Col( + tableName, + "DefaultI32" + ); + DefaultU32 = new global::SpacetimeDB.Col( + tableName, + "DefaultU32" + ); + DefaultI64 = new global::SpacetimeDB.Col( + tableName, + "DefaultI64" + ); + DefaultU64 = new global::SpacetimeDB.Col( + tableName, + "DefaultU64" + ); + DefaultHex = new global::SpacetimeDB.Col( + tableName, + "DefaultHex" + ); + DefaultBin = new global::SpacetimeDB.Col( + tableName, + "DefaultBin" + ); + DefaultF32 = new global::SpacetimeDB.Col( + tableName, + "DefaultF32" + ); + DefaultF64 = new global::SpacetimeDB.Col( + tableName, + "DefaultF64" + ); + DefaultEnum = new global::SpacetimeDB.Col( + tableName, + "DefaultEnum" + ); + DefaultNull = new global::SpacetimeDB.Col( + tableName, + "DefaultNull" + ); + } + } + + public readonly struct TestDefaultFieldValuesIxCols + { + internal TestDefaultFieldValuesIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestDefaultFieldValuesSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestDefaultFieldValues" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestDefaultFieldValuesSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestDefaultFieldValues, + TestDefaultFieldValuesCols, + TestDefaultFieldValuesIxCols + > TestDefaultFieldValues() + { + var tableName = TestDefaultFieldValuesSqlNameCache.Name; + return new( + tableName, + new TestDefaultFieldValuesCols(tableName), + new TestDefaultFieldValuesIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestDefaultFieldValues, + TestDefaultFieldValuesCols, + TestDefaultFieldValuesIxCols + > TestDefaultFieldValues() => new AssemblyDescriptor.Queries().TestDefaultFieldValues(); + } + } + + public readonly struct TestDuplicateTableNameCols + { + internal TestDuplicateTableNameCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public readonly struct TestDuplicateTableNameIxCols + { + internal TestDuplicateTableNameIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestDuplicateTableNameSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestDuplicateTableName" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestDuplicateTableNameSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestDuplicateTableName, + TestDuplicateTableNameCols, + TestDuplicateTableNameIxCols + > TestDuplicateTableName() + { + var tableName = TestDuplicateTableNameSqlNameCache.Name; + return new( + tableName, + new TestDuplicateTableNameCols(tableName), + new TestDuplicateTableNameIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestDuplicateTableName, + TestDuplicateTableNameCols, + TestDuplicateTableNameIxCols + > TestDuplicateTableName() => new AssemblyDescriptor.Queries().TestDuplicateTableName(); + } + } + + public readonly struct TestIndexIssuesCols + { + public readonly global::SpacetimeDB.Col SelfIndexingColumn; + public readonly global::SpacetimeDB.Col< + global::TestIndexIssues, + int + > SecondaryIndexingColumn; + + internal TestIndexIssuesCols(global::SpacetimeDB.SqlTableName tableName) + { + SelfIndexingColumn = new global::SpacetimeDB.Col( + tableName, + "SelfIndexingColumn" + ); + SecondaryIndexingColumn = new global::SpacetimeDB.Col( + tableName, + "SecondaryIndexingColumn" + ); + } + } + + public readonly struct TestIndexIssuesIxCols + { + public readonly global::SpacetimeDB.IxCol SelfIndexingColumn; + public readonly global::SpacetimeDB.IxCol< + global::TestIndexIssues, + int + > SecondaryIndexingColumn; + + internal TestIndexIssuesIxCols(global::SpacetimeDB.SqlTableName tableName) + { + SelfIndexingColumn = new global::SpacetimeDB.IxCol( + tableName, + "SelfIndexingColumn" + ); + SecondaryIndexingColumn = new global::SpacetimeDB.IxCol( + tableName, + "SecondaryIndexingColumn" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class TestIndexIssuesSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestIndexIssuesSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestIndexIssues, + TestIndexIssuesCols, + TestIndexIssuesIxCols + > TestIndexIssues() + { + var tableName = TestIndexIssuesSqlNameCache.Name; + return new( + tableName, + new TestIndexIssuesCols(tableName), + new TestIndexIssuesIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestIndexIssues, + TestIndexIssuesCols, + TestIndexIssuesIxCols + > TestIndexIssues() => new AssemblyDescriptor.Queries().TestIndexIssues(); + } + } + + public readonly struct TestScheduleWithoutPrimaryKeyCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithoutPrimaryKeyCols(global::SpacetimeDB.SqlTableName tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithoutPrimaryKeyIxCols + { + internal TestScheduleWithoutPrimaryKeyIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestScheduleWithoutPrimaryKeySqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithoutPrimaryKey" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithoutPrimaryKeySqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithoutPrimaryKeyCols, + TestScheduleWithoutPrimaryKeyIxCols + > TestScheduleWithoutPrimaryKey() + { + var tableName = TestScheduleWithoutPrimaryKeySqlNameCache.Name; + return new( + tableName, + new TestScheduleWithoutPrimaryKeyCols(tableName), + new TestScheduleWithoutPrimaryKeyIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithoutPrimaryKeyCols, + TestScheduleWithoutPrimaryKeyIxCols + > TestScheduleWithoutPrimaryKey() => + new AssemblyDescriptor.Queries().TestScheduleWithoutPrimaryKey(); + } + } + + public readonly struct TestScheduleWithWrongPrimaryKeyTypeCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithWrongPrimaryKeyTypeCols(global::SpacetimeDB.SqlTableName tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithWrongPrimaryKeyTypeIxCols + { + public readonly global::SpacetimeDB.IxCol IdWrongType; + + internal TestScheduleWithWrongPrimaryKeyTypeIxCols( + global::SpacetimeDB.SqlTableName tableName + ) + { + IdWrongType = new global::SpacetimeDB.IxCol( + tableName, + "IdWrongType" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class TestScheduleWithWrongPrimaryKeyTypeSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongPrimaryKeyType" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithWrongPrimaryKeyTypeSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithWrongPrimaryKeyTypeCols, + TestScheduleWithWrongPrimaryKeyTypeIxCols + > TestScheduleWithWrongPrimaryKeyType() + { + var tableName = TestScheduleWithWrongPrimaryKeyTypeSqlNameCache.Name; + return new( + tableName, + new TestScheduleWithWrongPrimaryKeyTypeCols(tableName), + new TestScheduleWithWrongPrimaryKeyTypeIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithWrongPrimaryKeyTypeCols, + TestScheduleWithWrongPrimaryKeyTypeIxCols + > TestScheduleWithWrongPrimaryKeyType() => + new AssemblyDescriptor.Queries().TestScheduleWithWrongPrimaryKeyType(); + } + } + + public readonly struct TestScheduleWithoutScheduleAtCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithoutScheduleAtCols(global::SpacetimeDB.SqlTableName tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithoutScheduleAtIxCols + { + public readonly global::SpacetimeDB.IxCol IdCorrectType; + + internal TestScheduleWithoutScheduleAtIxCols(global::SpacetimeDB.SqlTableName tableName) + { + IdCorrectType = new global::SpacetimeDB.IxCol( + tableName, + "IdCorrectType" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class TestScheduleWithoutScheduleAtSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithoutScheduleAt" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithoutScheduleAtSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithoutScheduleAtCols, + TestScheduleWithoutScheduleAtIxCols + > TestScheduleWithoutScheduleAt() + { + var tableName = TestScheduleWithoutScheduleAtSqlNameCache.Name; + return new( + tableName, + new TestScheduleWithoutScheduleAtCols(tableName), + new TestScheduleWithoutScheduleAtIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithoutScheduleAtCols, + TestScheduleWithoutScheduleAtIxCols + > TestScheduleWithoutScheduleAt() => + new AssemblyDescriptor.Queries().TestScheduleWithoutScheduleAt(); + } + } + + public readonly struct TestScheduleWithWrongScheduleAtTypeCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithWrongScheduleAtTypeCols(global::SpacetimeDB.SqlTableName tableName) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithWrongScheduleAtTypeIxCols + { + public readonly global::SpacetimeDB.IxCol IdCorrectType; + + internal TestScheduleWithWrongScheduleAtTypeIxCols( + global::SpacetimeDB.SqlTableName tableName + ) + { + IdCorrectType = new global::SpacetimeDB.IxCol( + tableName, + "IdCorrectType" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class TestScheduleWithWrongScheduleAtTypeSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongScheduleAtType" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithWrongScheduleAtTypeSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithWrongScheduleAtTypeCols, + TestScheduleWithWrongScheduleAtTypeIxCols + > TestScheduleWithWrongScheduleAtType() + { + var tableName = TestScheduleWithWrongScheduleAtTypeSqlNameCache.Name; + return new( + tableName, + new TestScheduleWithWrongScheduleAtTypeCols(tableName), + new TestScheduleWithWrongScheduleAtTypeIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithWrongScheduleAtTypeCols, + TestScheduleWithWrongScheduleAtTypeIxCols + > TestScheduleWithWrongScheduleAtType() => + new AssemblyDescriptor.Queries().TestScheduleWithWrongScheduleAtType(); + } + } + + public readonly struct TestScheduleWithMissingScheduleAtFieldCols + { + public readonly global::SpacetimeDB.Col IdWrongType; + public readonly global::SpacetimeDB.Col IdCorrectType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + int + > ScheduleAtWrongType; + public readonly global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + > ScheduleAtCorrectType; + + internal TestScheduleWithMissingScheduleAtFieldCols( + global::SpacetimeDB.SqlTableName tableName + ) + { + IdWrongType = new global::SpacetimeDB.Col( + tableName, + "IdWrongType" + ); + IdCorrectType = new global::SpacetimeDB.Col( + tableName, + "IdCorrectType" + ); + ScheduleAtWrongType = new global::SpacetimeDB.Col( + tableName, + "ScheduleAtWrongType" + ); + ScheduleAtCorrectType = new global::SpacetimeDB.Col< + global::TestScheduleIssues, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduleAtCorrectType"); + } + } + + public readonly struct TestScheduleWithMissingScheduleAtFieldIxCols + { + internal TestScheduleWithMissingScheduleAtFieldIxCols( + global::SpacetimeDB.SqlTableName tableName + ) { } + } + + public static partial class AssemblyDescriptor + { + private static class TestScheduleWithMissingScheduleAtFieldSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithMissingScheduleAtField" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithMissingScheduleAtFieldSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithMissingScheduleAtFieldCols, + TestScheduleWithMissingScheduleAtFieldIxCols + > TestScheduleWithMissingScheduleAtField() + { + var tableName = TestScheduleWithMissingScheduleAtFieldSqlNameCache.Name; + return new( + tableName, + new TestScheduleWithMissingScheduleAtFieldCols(tableName), + new TestScheduleWithMissingScheduleAtFieldIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestScheduleIssues, + TestScheduleWithMissingScheduleAtFieldCols, + TestScheduleWithMissingScheduleAtFieldIxCols + > TestScheduleWithMissingScheduleAtField() => + new AssemblyDescriptor.Queries().TestScheduleWithMissingScheduleAtField(); + } + } + + public readonly struct TestUniqueNotEquatableCols + { + public readonly global::SpacetimeDB.Col UniqueField; + public readonly global::SpacetimeDB.Col< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + > PrimaryKeyField; + + internal TestUniqueNotEquatableCols(global::SpacetimeDB.SqlTableName tableName) + { + UniqueField = new global::SpacetimeDB.Col( + tableName, + "UniqueField" + ); + PrimaryKeyField = new global::SpacetimeDB.Col< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + >(tableName, "PrimaryKeyField"); + } + } + + public readonly struct TestUniqueNotEquatableIxCols + { + public readonly global::SpacetimeDB.IxCol< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + > PrimaryKeyField; + + internal TestUniqueNotEquatableIxCols(global::SpacetimeDB.SqlTableName tableName) + { + PrimaryKeyField = new global::SpacetimeDB.IxCol< + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues + >(tableName, "PrimaryKeyField"); + } + } + + public static partial class AssemblyDescriptor + { + private static class TestUniqueNotEquatableSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestUniqueNotEquatable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestUniqueNotEquatableSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::TestUniqueNotEquatable, + TestUniqueNotEquatableCols, + TestUniqueNotEquatableIxCols + > TestUniqueNotEquatable() + { + var tableName = TestUniqueNotEquatableSqlNameCache.Name; + return new( + tableName, + new TestUniqueNotEquatableCols(tableName), + new TestUniqueNotEquatableIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::TestUniqueNotEquatable, + TestUniqueNotEquatableCols, + TestUniqueNotEquatableIxCols + > TestUniqueNotEquatable() => new AssemblyDescriptor.Queries().TestUniqueNotEquatable(); + } + } +} +#endif + +namespace SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles +{ + public readonly struct Player : global::SpacetimeDB.Internal.ITableView + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "Player" + ); + + public static global::Player ReadGenFields( + System.IO.BinaryReader reader, + global::Player row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(Player), + ProductTypeRef: (uint)new global::Player.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [], + Indexes: + [ + new( + SourceName: "Player_Identity_idx_btree", + AccessorName: "Identity", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + Player, + global::Player + >.MakeUniqueConstraint(0), + ], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView.DoIter(); + + public global::Player Insert(global::Player row) => + global::SpacetimeDB.Internal.ITableView.DoInsert(row); + + public bool Delete(global::Player row) => + global::SpacetimeDB.Internal.ITableView.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView.DoClear(); + + public sealed class IdentityUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + Player, + global::Player, + SpacetimeDB.Identity, + SpacetimeDB.Identity.BSATN + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "Player_Identity_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdentityUniqueIndex() { } + + internal IdentityUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::Player? Find(SpacetimeDB.Identity key) => FindSingle(key); + } + + private static IdentityUniqueIndex? __Identity; + public IdentityUniqueIndex Identity => __Identity ??= new(); + } + + public readonly struct TestAutoIncNotInteger + : global::SpacetimeDB.Internal.ITableView< + TestAutoIncNotInteger, + global::TestAutoIncNotInteger + > + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestAutoIncNotInteger" + ); + + public static global::TestAutoIncNotInteger ReadGenFields( + System.IO.BinaryReader reader, + global::TestAutoIncNotInteger row + ) + { + if (row.AutoIncField == default) + { + row.AutoIncField = global::TestAutoIncNotInteger.BSATN.AutoIncFieldRW.Read(reader); + } + if (row.IdentityField == default) + { + row.IdentityField = global::TestAutoIncNotInteger.BSATN.IdentityFieldRW.Read( + reader + ); + } + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestAutoIncNotInteger), + ProductTypeRef: (uint) + new global::TestAutoIncNotInteger.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [], + Indexes: + [ + new( + SourceName: "TestAutoIncNotInteger_IdentityField_idx_btree", + AccessorName: "IdentityField", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + TestAutoIncNotInteger, + global::TestAutoIncNotInteger + >.MakeUniqueConstraint(1), + ], + Sequences: + [ + global::SpacetimeDB.Internal.ITableView< + TestAutoIncNotInteger, + global::TestAutoIncNotInteger + >.MakeSequence(0), + global::SpacetimeDB.Internal.ITableView< + TestAutoIncNotInteger, + global::TestAutoIncNotInteger + >.MakeSequence(1), + ], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + TestAutoIncNotInteger, + global::TestAutoIncNotInteger + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + TestAutoIncNotInteger, + global::TestAutoIncNotInteger + >.DoIter(); + + public global::TestAutoIncNotInteger Insert(global::TestAutoIncNotInteger row) => + global::SpacetimeDB.Internal.ITableView< + TestAutoIncNotInteger, + global::TestAutoIncNotInteger + >.DoInsert(row); + + public bool Delete(global::TestAutoIncNotInteger row) => + global::SpacetimeDB.Internal.ITableView< + TestAutoIncNotInteger, + global::TestAutoIncNotInteger + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + TestAutoIncNotInteger, + global::TestAutoIncNotInteger + >.DoClear(); + + public sealed class IdentityFieldUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + TestAutoIncNotInteger, + global::TestAutoIncNotInteger, + string, + SpacetimeDB.BSATN.String + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestAutoIncNotInteger_IdentityField_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdentityFieldUniqueIndex() { } + + internal IdentityFieldUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::TestAutoIncNotInteger? Find(string key) => FindSingle(key); + } + + private static IdentityFieldUniqueIndex? __IdentityField; + public IdentityFieldUniqueIndex IdentityField => __IdentityField ??= new(); + } + + public readonly struct TestDefaultFieldValues + : global::SpacetimeDB.Internal.ITableView< + TestDefaultFieldValues, + global::TestDefaultFieldValues + > + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestDefaultFieldValues" + ); + + public static global::TestDefaultFieldValues ReadGenFields( + System.IO.BinaryReader reader, + global::TestDefaultFieldValues row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestDefaultFieldValues), + ProductTypeRef: (uint) + new global::TestDefaultFieldValues.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [], + Indexes: + [ + new( + SourceName: "TestDefaultFieldValues_UniqueField_idx_btree", + AccessorName: "UniqueField", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + TestDefaultFieldValues, + global::TestDefaultFieldValues + >.MakeUniqueConstraint(0), + ], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + TestDefaultFieldValues, + global::TestDefaultFieldValues + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + TestDefaultFieldValues, + global::TestDefaultFieldValues + >.DoIter(); + + public global::TestDefaultFieldValues Insert(global::TestDefaultFieldValues row) => + global::SpacetimeDB.Internal.ITableView< + TestDefaultFieldValues, + global::TestDefaultFieldValues + >.DoInsert(row); + + public bool Delete(global::TestDefaultFieldValues row) => + global::SpacetimeDB.Internal.ITableView< + TestDefaultFieldValues, + global::TestDefaultFieldValues + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + TestDefaultFieldValues, + global::TestDefaultFieldValues + >.DoClear(); + } + + public readonly struct TestDuplicateTableName + : global::SpacetimeDB.Internal.ITableView< + TestDuplicateTableName, + global::TestDuplicateTableName + > + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestDuplicateTableName" + ); + + public static global::TestDuplicateTableName ReadGenFields( + System.IO.BinaryReader reader, + global::TestDuplicateTableName row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestDuplicateTableName), + ProductTypeRef: (uint) + new global::TestDuplicateTableName.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [], + Indexes: [], + Constraints: [], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + TestDuplicateTableName, + global::TestDuplicateTableName + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + TestDuplicateTableName, + global::TestDuplicateTableName + >.DoIter(); + + public global::TestDuplicateTableName Insert(global::TestDuplicateTableName row) => + global::SpacetimeDB.Internal.ITableView< + TestDuplicateTableName, + global::TestDuplicateTableName + >.DoInsert(row); + + public bool Delete(global::TestDuplicateTableName row) => + global::SpacetimeDB.Internal.ITableView< + TestDuplicateTableName, + global::TestDuplicateTableName + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + TestDuplicateTableName, + global::TestDuplicateTableName + >.DoClear(); + } + + public readonly struct TestIndexIssues + : global::SpacetimeDB.Internal.ITableView + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues" + ); + + public static global::TestIndexIssues ReadGenFields( + System.IO.BinaryReader reader, + global::TestIndexIssues row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestIndexIssues), + ProductTypeRef: (uint) + new global::TestIndexIssues.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [], + Indexes: + [ + new( + SourceName: "TestIndexIssues__idx_btree", + AccessorName: "TestIndexWithoutColumns", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([]) + ), + new( + SourceName: "TestIndexIssues__idx_btree", + AccessorName: "TestIndexWithEmptyColumns", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([]) + ), + new( + SourceName: "TestIndexIssues__idx_btree", + AccessorName: "TestUnknownColumns", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([]) + ), + new( + SourceName: "TestIndexIssues_SelfIndexingColumn_idx_btree", + AccessorName: "SelfIndexingColumn", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + new( + SourceName: "TestIndexIssues_SecondaryIndexingColumn_idx_btree", + AccessorName: "SecondaryIndexingColumn", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) + ), + new( + SourceName: "TestIndexIssues_SelfIndexingColumn_idx_btree", + AccessorName: "TestUnexpectedColumns", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + ], + Constraints: [], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + TestIndexIssues, + global::TestIndexIssues + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + TestIndexIssues, + global::TestIndexIssues + >.DoIter(); + + public global::TestIndexIssues Insert(global::TestIndexIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestIndexIssues, + global::TestIndexIssues + >.DoInsert(row); + + public bool Delete(global::TestIndexIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestIndexIssues, + global::TestIndexIssues + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + TestIndexIssues, + global::TestIndexIssues + >.DoClear(); + + public sealed class TestIndexWithoutColumnsIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues__idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestIndexWithoutColumnsIndex() { } + } + + private static TestIndexWithoutColumnsIndex? __TestIndexWithoutColumns; + public TestIndexWithoutColumnsIndex TestIndexWithoutColumns => + __TestIndexWithoutColumns ??= new(); + + public sealed class TestIndexWithEmptyColumnsIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues__idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestIndexWithEmptyColumnsIndex() { } + } + + private static TestIndexWithEmptyColumnsIndex? __TestIndexWithEmptyColumns; + public TestIndexWithEmptyColumnsIndex TestIndexWithEmptyColumns => + __TestIndexWithEmptyColumns ??= new(); + + public sealed class TestUnknownColumnsIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues__idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestUnknownColumnsIndex() { } + } + + private static TestUnknownColumnsIndex? __TestUnknownColumns; + public TestUnknownColumnsIndex TestUnknownColumns => __TestUnknownColumns ??= new(); + + public sealed class SelfIndexingColumnIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues_SelfIndexingColumn_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static SelfIndexingColumnIndex() { } + + public IEnumerable Filter(int SelfIndexingColumn) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + + public ulong Delete(int SelfIndexingColumn) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound SelfIndexingColumn + ) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + + public ulong Delete(global::SpacetimeDB.Bound SelfIndexingColumn) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + } + + private static SelfIndexingColumnIndex? __SelfIndexingColumn; + public SelfIndexingColumnIndex SelfIndexingColumn => __SelfIndexingColumn ??= new(); + + public sealed class SecondaryIndexingColumnIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues_SecondaryIndexingColumn_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static SecondaryIndexingColumnIndex() { } + + public IEnumerable Filter(int SecondaryIndexingColumn) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds( + SecondaryIndexingColumn + ) + ); + + public ulong Delete(int SecondaryIndexingColumn) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds( + SecondaryIndexingColumn + ) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound SecondaryIndexingColumn + ) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds( + SecondaryIndexingColumn + ) + ); + + public ulong Delete(global::SpacetimeDB.Bound SecondaryIndexingColumn) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds( + SecondaryIndexingColumn + ) + ); + } + + private static SecondaryIndexingColumnIndex? __SecondaryIndexingColumn; + public SecondaryIndexingColumnIndex SecondaryIndexingColumn => + __SecondaryIndexingColumn ??= new(); + + public sealed class TestUnexpectedColumnsIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues_SelfIndexingColumn_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestUnexpectedColumnsIndex() { } + + public IEnumerable Filter(int SelfIndexingColumn) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + + public ulong Delete(int SelfIndexingColumn) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound SelfIndexingColumn + ) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + + public ulong Delete(global::SpacetimeDB.Bound SelfIndexingColumn) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + } + + private static TestUnexpectedColumnsIndex? __TestUnexpectedColumns; + public TestUnexpectedColumnsIndex TestUnexpectedColumns => + __TestUnexpectedColumns ??= new(); + } + + public readonly struct TestScheduleWithMissingScheduleAtField + : global::SpacetimeDB.Internal.ITableView< + TestScheduleWithMissingScheduleAtField, + global::TestScheduleIssues + > + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithMissingScheduleAtField" + ); + + public static global::TestScheduleIssues ReadGenFields( + System.IO.BinaryReader reader, + global::TestScheduleIssues row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestScheduleWithMissingScheduleAtField), + ProductTypeRef: (uint) + new global::TestScheduleIssues.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [], + Indexes: [], + Constraints: [], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithMissingScheduleAtField, + global::TestScheduleIssues + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithMissingScheduleAtField, + global::TestScheduleIssues + >.DoIter(); + + public global::TestScheduleIssues Insert(global::TestScheduleIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithMissingScheduleAtField, + global::TestScheduleIssues + >.DoInsert(row); + + public bool Delete(global::TestScheduleIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithMissingScheduleAtField, + global::TestScheduleIssues + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithMissingScheduleAtField, + global::TestScheduleIssues + >.DoClear(); + } + + public readonly struct TestScheduleWithoutPrimaryKey + : global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutPrimaryKey, + global::TestScheduleIssues + > + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithoutPrimaryKey" + ); + + public static global::TestScheduleIssues ReadGenFields( + System.IO.BinaryReader reader, + global::TestScheduleIssues row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestScheduleWithoutPrimaryKey), + ProductTypeRef: (uint) + new global::TestScheduleIssues.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [], + Indexes: [], + Constraints: [], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutPrimaryKey, + global::TestScheduleIssues + >.MakeSchedule("DummyScheduledReducer", 3); + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutPrimaryKey, + global::TestScheduleIssues + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutPrimaryKey, + global::TestScheduleIssues + >.DoIter(); + + public global::TestScheduleIssues Insert(global::TestScheduleIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutPrimaryKey, + global::TestScheduleIssues + >.DoInsert(row); + + public bool Delete(global::TestScheduleIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutPrimaryKey, + global::TestScheduleIssues + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutPrimaryKey, + global::TestScheduleIssues + >.DoClear(); + } + + public readonly struct TestScheduleWithoutScheduleAt + : global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutScheduleAt, + global::TestScheduleIssues + > + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithoutScheduleAt" + ); + + public static global::TestScheduleIssues ReadGenFields( + System.IO.BinaryReader reader, + global::TestScheduleIssues row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestScheduleWithoutScheduleAt), + ProductTypeRef: (uint) + new global::TestScheduleIssues.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [1], + Indexes: + [ + new( + SourceName: "TestScheduleWithoutScheduleAt_IdCorrectType_idx_btree", + AccessorName: "IdCorrectType", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutScheduleAt, + global::TestScheduleIssues + >.MakeUniqueConstraint(1), + ], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutScheduleAt, + global::TestScheduleIssues + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutScheduleAt, + global::TestScheduleIssues + >.DoIter(); + + public global::TestScheduleIssues Insert(global::TestScheduleIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutScheduleAt, + global::TestScheduleIssues + >.DoInsert(row); + + public bool Delete(global::TestScheduleIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutScheduleAt, + global::TestScheduleIssues + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithoutScheduleAt, + global::TestScheduleIssues + >.DoClear(); + + public sealed class IdCorrectTypeUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + TestScheduleWithoutScheduleAt, + global::TestScheduleIssues, + int, + SpacetimeDB.BSATN.I32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithoutScheduleAt_IdCorrectType_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdCorrectTypeUniqueIndex() { } + + internal IdCorrectTypeUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::TestScheduleIssues? Find(int key) => FindSingle(key); + + public global::TestScheduleIssues Update(global::TestScheduleIssues row) => + DoUpdate(row); + } + + private static IdCorrectTypeUniqueIndex? __IdCorrectType; + public IdCorrectTypeUniqueIndex IdCorrectType => __IdCorrectType ??= new(); + } + + public readonly struct TestScheduleWithWrongPrimaryKeyType + : global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongPrimaryKeyType, + global::TestScheduleIssues + > + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongPrimaryKeyType" + ); + + public static global::TestScheduleIssues ReadGenFields( + System.IO.BinaryReader reader, + global::TestScheduleIssues row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestScheduleWithWrongPrimaryKeyType), + ProductTypeRef: (uint) + new global::TestScheduleIssues.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [0], + Indexes: + [ + new( + SourceName: "TestScheduleWithWrongPrimaryKeyType_IdWrongType_idx_btree", + AccessorName: "IdWrongType", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongPrimaryKeyType, + global::TestScheduleIssues + >.MakeUniqueConstraint(0), + ], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongPrimaryKeyType, + global::TestScheduleIssues + >.MakeSchedule("DummyScheduledReducer", 3); + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongPrimaryKeyType, + global::TestScheduleIssues + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongPrimaryKeyType, + global::TestScheduleIssues + >.DoIter(); + + public global::TestScheduleIssues Insert(global::TestScheduleIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongPrimaryKeyType, + global::TestScheduleIssues + >.DoInsert(row); + + public bool Delete(global::TestScheduleIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongPrimaryKeyType, + global::TestScheduleIssues + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongPrimaryKeyType, + global::TestScheduleIssues + >.DoClear(); + + public sealed class IdWrongTypeUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + TestScheduleWithWrongPrimaryKeyType, + global::TestScheduleIssues, + string, + SpacetimeDB.BSATN.String + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongPrimaryKeyType_IdWrongType_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdWrongTypeUniqueIndex() { } + + internal IdWrongTypeUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::TestScheduleIssues? Find(string key) => FindSingle(key); + + public global::TestScheduleIssues Update(global::TestScheduleIssues row) => + DoUpdate(row); + } + + private static IdWrongTypeUniqueIndex? __IdWrongType; + public IdWrongTypeUniqueIndex IdWrongType => __IdWrongType ??= new(); + } + + public readonly struct TestScheduleWithWrongScheduleAtType + : global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongScheduleAtType, + global::TestScheduleIssues + > + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongScheduleAtType" + ); + + public static global::TestScheduleIssues ReadGenFields( + System.IO.BinaryReader reader, + global::TestScheduleIssues row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestScheduleWithWrongScheduleAtType), + ProductTypeRef: (uint) + new global::TestScheduleIssues.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [1], + Indexes: + [ + new( + SourceName: "TestScheduleWithWrongScheduleAtType_IdCorrectType_idx_btree", + AccessorName: "IdCorrectType", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongScheduleAtType, + global::TestScheduleIssues + >.MakeUniqueConstraint(1), + ], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongScheduleAtType, + global::TestScheduleIssues + >.MakeSchedule("DummyScheduledReducer", 2); + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongScheduleAtType, + global::TestScheduleIssues + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongScheduleAtType, + global::TestScheduleIssues + >.DoIter(); + + public global::TestScheduleIssues Insert(global::TestScheduleIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongScheduleAtType, + global::TestScheduleIssues + >.DoInsert(row); + + public bool Delete(global::TestScheduleIssues row) => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongScheduleAtType, + global::TestScheduleIssues + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + TestScheduleWithWrongScheduleAtType, + global::TestScheduleIssues + >.DoClear(); + + public sealed class IdCorrectTypeUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + TestScheduleWithWrongScheduleAtType, + global::TestScheduleIssues, + int, + SpacetimeDB.BSATN.I32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongScheduleAtType_IdCorrectType_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdCorrectTypeUniqueIndex() { } + + internal IdCorrectTypeUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::TestScheduleIssues? Find(int key) => FindSingle(key); + + public global::TestScheduleIssues Update(global::TestScheduleIssues row) => + DoUpdate(row); + } + + private static IdCorrectTypeUniqueIndex? __IdCorrectType; + public IdCorrectTypeUniqueIndex IdCorrectType => __IdCorrectType ??= new(); + } + + public readonly struct TestUniqueNotEquatable + : global::SpacetimeDB.Internal.ITableView< + TestUniqueNotEquatable, + global::TestUniqueNotEquatable + > + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestUniqueNotEquatable" + ); + + public static global::TestUniqueNotEquatable ReadGenFields( + System.IO.BinaryReader reader, + global::TestUniqueNotEquatable row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestUniqueNotEquatable), + ProductTypeRef: (uint) + new global::TestUniqueNotEquatable.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [1], + Indexes: + [ + new( + SourceName: "TestUniqueNotEquatable_UniqueField_idx_btree", + AccessorName: "UniqueField", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + new( + SourceName: "TestUniqueNotEquatable_PrimaryKeyField_idx_btree", + AccessorName: "PrimaryKeyField", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + TestUniqueNotEquatable, + global::TestUniqueNotEquatable + >.MakeUniqueConstraint(0), + global::SpacetimeDB.Internal.ITableView< + TestUniqueNotEquatable, + global::TestUniqueNotEquatable + >.MakeUniqueConstraint(1), + ], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + TestUniqueNotEquatable, + global::TestUniqueNotEquatable + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + TestUniqueNotEquatable, + global::TestUniqueNotEquatable + >.DoIter(); + + public global::TestUniqueNotEquatable Insert(global::TestUniqueNotEquatable row) => + global::SpacetimeDB.Internal.ITableView< + TestUniqueNotEquatable, + global::TestUniqueNotEquatable + >.DoInsert(row); + + public bool Delete(global::TestUniqueNotEquatable row) => + global::SpacetimeDB.Internal.ITableView< + TestUniqueNotEquatable, + global::TestUniqueNotEquatable + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + TestUniqueNotEquatable, + global::TestUniqueNotEquatable + >.DoClear(); + + public sealed class PrimaryKeyFieldUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + TestUniqueNotEquatable, + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues, + SpacetimeDB.BSATN.Enum + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestUniqueNotEquatable_PrimaryKeyField_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PrimaryKeyFieldUniqueIndex() { } + + internal PrimaryKeyFieldUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::TestUniqueNotEquatable? Find(TestEnumWithExplicitValues key) => + FindSingle(key); + + public global::TestUniqueNotEquatable Update(global::TestUniqueNotEquatable row) => + DoUpdate(row); + } + + private static PrimaryKeyFieldUniqueIndex? __PrimaryKeyField; + public PrimaryKeyFieldUniqueIndex PrimaryKeyField => __PrimaryKeyField ??= new(); + } +} + +sealed class view_def_ienumerable_return_from_filterViewDispatcher + : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_def_ienumerable_return_from_filter", + Index: 0, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.List< + TestScheduleIssues, + TestScheduleIssues.BSATN + >().GetAlgebraicType(registrar) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewDefIEnumerableReturnFromFilter( + (SpacetimeDB.ViewContext)ctx + ); + var listSerializer = new SpacetimeDB.BSATN.List< + TestScheduleIssues, + TestScheduleIssues.BSATN + >(); + var listValue = global::System.Linq.Enumerable.ToList(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error( + "Error in view 'view_def_ienumerable_return_from_filter': " + e + ); + throw; + } + } +} + +sealed class view_def_ienumerable_return_from_iterViewDispatcher + : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_def_ienumerable_return_from_iter", + Index: 1, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.List().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewDefIEnumerableReturnFromIter((SpacetimeDB.ViewContext)ctx); + var listSerializer = new SpacetimeDB.BSATN.List(); + var listValue = global::System.Linq.Enumerable.ToList(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error( + "Error in view 'view_def_ienumerable_return_from_iter': " + e + ); + throw; + } + } +} + +sealed class view_def_no_contextViewDispatcher : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_def_no_context", + Index: 2, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.List().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewDefNoContext((SpacetimeDB.ViewContext)ctx); + var listSerializer = new SpacetimeDB.BSATN.List(); + var listValue = global::System.Linq.Enumerable.ToList(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'view_def_no_context': " + e); + throw; + } + } +} + +sealed class view_def_no_publicViewDispatcher : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_def_no_public", + Index: 3, + IsPublic: false, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.List().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewDefNoPublic((SpacetimeDB.ViewContext)ctx); + var listSerializer = new SpacetimeDB.BSATN.List(); + var listValue = global::System.Linq.Enumerable.ToList(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'view_def_no_public': " + e); + throw; + } + } +} + +sealed class view_def_wrong_contextViewDispatcher : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_def_wrong_context", + Index: 4, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.List().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewDefWrongContext((SpacetimeDB.ViewContext)ctx); + var listSerializer = new SpacetimeDB.BSATN.List(); + var listValue = global::System.Linq.Enumerable.ToList(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'view_def_wrong_context': " + e); + throw; + } + } +} + +sealed class view_def_wrong_returnViewDispatcher : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_def_wrong_return", + Index: 5, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new Player.BSATN().GetAlgebraicType(registrar) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewDefWrongReturn((SpacetimeDB.ViewContext)ctx); + Player.BSATN returnRW = new(); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + returnRW.Write(writer, returnValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'view_def_wrong_return': " + e); + throw; + } + } +} + +sealed class view_no_deleteViewDispatcher : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_no_delete", + Index: 6, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.ValueOption().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewNoDelete((SpacetimeDB.ViewContext)ctx); + var listSerializer = SpacetimeDB.BSATN.ValueOption< + Player, + Player.BSATN + >.GetListSerializer(); + var listValue = ModuleRegistration.ToListOrEmpty(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'view_no_delete': " + e); + throw; + } + } +} + +sealed class view_no_insertViewDispatcher : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_no_insert", + Index: 7, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.ValueOption().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewNoInsert((SpacetimeDB.ViewContext)ctx); + var listSerializer = SpacetimeDB.BSATN.ValueOption< + Player, + Player.BSATN + >.GetListSerializer(); + var listValue = ModuleRegistration.ToListOrEmpty(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'view_no_insert': " + e); + throw; + } + } +} + +sealed class view_primary_key_missing_columnViewDispatcher : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_primary_key_missing_column", + Index: 8, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.List().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewPrimaryKeyMissingColumn((SpacetimeDB.ViewContext)ctx); + var listSerializer = new SpacetimeDB.BSATN.List(); + var listValue = global::System.Linq.Enumerable.ToList(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'view_primary_key_missing_column': " + e); + throw; + } + } +} + +sealed class view_primary_key_non_equatable_columnViewDispatcher + : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_primary_key_non_equatable_column", + Index: 9, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.List< + NonEquatableViewPrimaryKeyRow, + NonEquatableViewPrimaryKeyRow.BSATN + >().GetAlgebraicType(registrar) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewPrimaryKeyNonEquatableColumn((SpacetimeDB.ViewContext)ctx); + var listSerializer = new SpacetimeDB.BSATN.List< + NonEquatableViewPrimaryKeyRow, + NonEquatableViewPrimaryKeyRow.BSATN + >(); + var listValue = global::System.Linq.Enumerable.ToList(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error( + "Error in view 'view_primary_key_non_equatable_column': " + e + ); + throw; + } + } +} + +sealed class view_primary_key_uses_non_bsatn_partial_fieldViewDispatcher + : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_primary_key_uses_non_bsatn_partial_field", + Index: 10, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.List< + ViewPrimaryKeyPartialRow, + ViewPrimaryKeyPartialRow.BSATN + >().GetAlgebraicType(registrar) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewPrimaryKeyUsesNonBsatnPartialField( + (SpacetimeDB.ViewContext)ctx + ); + var listSerializer = new SpacetimeDB.BSATN.List< + ViewPrimaryKeyPartialRow, + ViewPrimaryKeyPartialRow.BSATN + >(); + var listValue = global::System.Linq.Enumerable.ToList(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error( + "Error in view 'view_primary_key_uses_non_bsatn_partial_field': " + e + ); + throw; + } + } +} + +sealed class view_primary_key_uses_wrong_source_nameViewDispatcher + : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_primary_key_uses_wrong_source_name", + Index: 11, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.List< + ViewPrimaryKeyRenamedRow, + ViewPrimaryKeyRenamedRow.BSATN + >().GetAlgebraicType(registrar) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.ViewPrimaryKeyUsesWrongSourceName( + (SpacetimeDB.ViewContext)ctx + ); + var listSerializer = new SpacetimeDB.BSATN.List< + ViewPrimaryKeyRenamedRow, + ViewPrimaryKeyRenamedRow.BSATN + >(); + var listValue = global::System.Linq.Enumerable.ToList(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error( + "Error in view 'view_primary_key_uses_wrong_source_name': " + e + ); + throw; + } + } +} + +sealed class view_def_index_no_mutationViewDispatcher : global::SpacetimeDB.Internal.IAnonymousView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeAnonymousViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_def_index_no_mutation", + Index: 0, + IsPublic: true, + IsAnonymous: true, + Params: [], + ReturnType: new SpacetimeDB.BSATN.ValueOption().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IAnonymousViewContext ctx + ) + { + try + { + var returnValue = Module.ViewDefIndexNoMutation((SpacetimeDB.AnonymousViewContext)ctx); + var listSerializer = SpacetimeDB.BSATN.ValueOption< + Player, + Player.BSATN + >.GetListSerializer(); + var listValue = ModuleRegistration.ToListOrEmpty(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'view_def_index_no_mutation': " + e); + throw; + } + } +} + +sealed class view_def_no_anon_identityViewDispatcher : global::SpacetimeDB.Internal.IAnonymousView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeAnonymousViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_def_no_anon_identity", + Index: 1, + IsPublic: true, + IsAnonymous: true, + Params: [], + ReturnType: new SpacetimeDB.BSATN.ValueOption().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IAnonymousViewContext ctx + ) + { + try + { + var returnValue = Module.ViewDefNoAnonIdentity((SpacetimeDB.AnonymousViewContext)ctx); + var listSerializer = SpacetimeDB.BSATN.ValueOption< + Player, + Player.BSATN + >.GetListSerializer(); + var listValue = ModuleRegistration.ToListOrEmpty(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'view_def_no_anon_identity': " + e); + throw; + } + } +} + +sealed class view_def_no_iterViewDispatcher : global::SpacetimeDB.Internal.IAnonymousView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeAnonymousViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_def_no_iter", + Index: 2, + IsPublic: true, + IsAnonymous: true, + Params: [], + ReturnType: new SpacetimeDB.BSATN.ValueOption().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IAnonymousViewContext ctx + ) + { + try + { + var returnValue = Module.ViewDefNoIter((SpacetimeDB.AnonymousViewContext)ctx); + var listSerializer = SpacetimeDB.BSATN.ValueOption< + Player, + Player.BSATN + >.GetListSerializer(); + var listValue = ModuleRegistration.ToListOrEmpty(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'view_def_no_iter': " + e); + throw; + } + } +} + +sealed class view_def_returns_not_a_spacetime_typeViewDispatcher + : global::SpacetimeDB.Internal.IAnonymousView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeAnonymousViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "view_def_returns_not_a_spacetime_type", + Index: 3, + IsPublic: true, + IsAnonymous: true, + Params: [], + ReturnType: new SpacetimeDB.BSATN.ValueOption< + NotSpacetimeType, + NotSpacetimeType.BSATN + >().GetAlgebraicType(registrar) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IAnonymousViewContext ctx + ) + { + try + { + var returnValue = Module.ViewDefReturnsNotASpacetimeType( + (SpacetimeDB.AnonymousViewContext)ctx + ); + var listSerializer = SpacetimeDB.BSATN.ValueOption< + NotSpacetimeType, + NotSpacetimeType.BSATN + >.GetListSerializer(); + var listValue = ModuleRegistration.ToListOrEmpty(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error( + "Error in view 'view_def_returns_not_a_spacetime_type': " + e + ); + throw; + } + } +} + +namespace SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles +{ + public sealed class PlayerReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "Player" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PlayerReadOnly() { } + + internal PlayerReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class IdentityIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.PlayerReadOnly, + global::Player, + SpacetimeDB.Identity, + SpacetimeDB.Identity.BSATN + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "Player_Identity_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdentityIndex() { } + + internal IdentityIndex() + : base(__resolvedName) { } + + public global::Player? Find(SpacetimeDB.Identity key) => FindSingle(key); + } + + private static IdentityIndex? __Identity; + public IdentityIndex Identity => __Identity ??= new(); + } + + public sealed class TestAutoIncNotIntegerReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestAutoIncNotInteger" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestAutoIncNotIntegerReadOnly() { } + + internal TestAutoIncNotIntegerReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class IdentityFieldIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestAutoIncNotIntegerReadOnly, + global::TestAutoIncNotInteger, + string, + SpacetimeDB.BSATN.String + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestAutoIncNotInteger_IdentityField_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdentityFieldIndex() { } + + internal IdentityFieldIndex() + : base(__resolvedName) { } + + public global::TestAutoIncNotInteger? Find(string key) => FindSingle(key); + } + + private static IdentityFieldIndex? __IdentityField; + public IdentityFieldIndex IdentityField => __IdentityField ??= new(); + } + + public sealed class TestDefaultFieldValuesReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestDefaultFieldValues" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestDefaultFieldValuesReadOnly() { } + + internal TestDefaultFieldValuesReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + } + + public sealed class TestDuplicateTableNameReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestDuplicateTableName" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestDuplicateTableNameReadOnly() { } + + internal TestDuplicateTableNameReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + } + + public sealed class TestIndexIssuesReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestIndexIssuesReadOnly() { } + + internal TestIndexIssuesReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class TestIndexWithoutColumnsIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues__idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestIndexWithoutColumnsIndex() { } + + internal TestIndexWithoutColumnsIndex() + : base(__resolvedName) { } + } + + private static TestIndexWithoutColumnsIndex? __TestIndexWithoutColumns; + public TestIndexWithoutColumnsIndex TestIndexWithoutColumns => + __TestIndexWithoutColumns ??= new(); + + public sealed class TestIndexWithEmptyColumnsIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues__idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestIndexWithEmptyColumnsIndex() { } + + internal TestIndexWithEmptyColumnsIndex() + : base(__resolvedName) { } + } + + private static TestIndexWithEmptyColumnsIndex? __TestIndexWithEmptyColumns; + public TestIndexWithEmptyColumnsIndex TestIndexWithEmptyColumns => + __TestIndexWithEmptyColumns ??= new(); + + public sealed class TestUnknownColumnsIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues__idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestUnknownColumnsIndex() { } + + internal TestUnknownColumnsIndex() + : base(__resolvedName) { } + } + + private static TestUnknownColumnsIndex? __TestUnknownColumns; + public TestUnknownColumnsIndex TestUnknownColumns => __TestUnknownColumns ??= new(); + + public sealed class SelfIndexingColumnIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues_SelfIndexingColumn_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static SelfIndexingColumnIndex() { } + + internal SelfIndexingColumnIndex() + : base(__resolvedName) { } + + public IEnumerable Filter(int SelfIndexingColumn) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound SelfIndexingColumn + ) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + } + + private static SelfIndexingColumnIndex? __SelfIndexingColumn; + public SelfIndexingColumnIndex SelfIndexingColumn => __SelfIndexingColumn ??= new(); + + public sealed class SecondaryIndexingColumnIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues_SecondaryIndexingColumn_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static SecondaryIndexingColumnIndex() { } + + internal SecondaryIndexingColumnIndex() + : base(__resolvedName) { } + + public IEnumerable Filter(int SecondaryIndexingColumn) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + SecondaryIndexingColumn + ) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound SecondaryIndexingColumn + ) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + SecondaryIndexingColumn + ) + ); + } + + private static SecondaryIndexingColumnIndex? __SecondaryIndexingColumn; + public SecondaryIndexingColumnIndex SecondaryIndexingColumn => + __SecondaryIndexingColumn ??= new(); + + public sealed class TestUnexpectedColumnsIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestIndexIssues_SelfIndexingColumn_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestUnexpectedColumnsIndex() { } + + internal TestUnexpectedColumnsIndex() + : base(__resolvedName) { } + + public IEnumerable Filter(int SelfIndexingColumn) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound SelfIndexingColumn + ) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + SelfIndexingColumn + ) + ); + } + + private static TestUnexpectedColumnsIndex? __TestUnexpectedColumns; + public TestUnexpectedColumnsIndex TestUnexpectedColumns => + __TestUnexpectedColumns ??= new(); + } + + public sealed class TestScheduleWithMissingScheduleAtFieldReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithMissingScheduleAtField" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithMissingScheduleAtFieldReadOnly() { } + + internal TestScheduleWithMissingScheduleAtFieldReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + } + + public sealed class TestScheduleWithoutPrimaryKeyReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithoutPrimaryKey" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithoutPrimaryKeyReadOnly() { } + + internal TestScheduleWithoutPrimaryKeyReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + } + + public sealed class TestScheduleWithoutScheduleAtReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithoutScheduleAt" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithoutScheduleAtReadOnly() { } + + internal TestScheduleWithoutScheduleAtReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class IdCorrectTypeIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithoutScheduleAtReadOnly, + global::TestScheduleIssues, + int, + SpacetimeDB.BSATN.I32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithoutScheduleAt_IdCorrectType_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdCorrectTypeIndex() { } + + internal IdCorrectTypeIndex() + : base(__resolvedName) { } + + public global::TestScheduleIssues? Find(int key) => FindSingle(key); + } + + private static IdCorrectTypeIndex? __IdCorrectType; + public IdCorrectTypeIndex IdCorrectType => __IdCorrectType ??= new(); + } + + public sealed class TestScheduleWithWrongPrimaryKeyTypeReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongPrimaryKeyType" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithWrongPrimaryKeyTypeReadOnly() { } + + internal TestScheduleWithWrongPrimaryKeyTypeReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class IdWrongTypeIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithWrongPrimaryKeyTypeReadOnly, + global::TestScheduleIssues, + string, + SpacetimeDB.BSATN.String + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongPrimaryKeyType_IdWrongType_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdWrongTypeIndex() { } + + internal IdWrongTypeIndex() + : base(__resolvedName) { } + + public global::TestScheduleIssues? Find(string key) => FindSingle(key); + } + + private static IdWrongTypeIndex? __IdWrongType; + public IdWrongTypeIndex IdWrongType => __IdWrongType ??= new(); + } + + public sealed class TestScheduleWithWrongScheduleAtTypeReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongScheduleAtType" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestScheduleWithWrongScheduleAtTypeReadOnly() { } + + internal TestScheduleWithWrongScheduleAtTypeReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class IdCorrectTypeIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithWrongScheduleAtTypeReadOnly, + global::TestScheduleIssues, + int, + SpacetimeDB.BSATN.I32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestScheduleWithWrongScheduleAtType_IdCorrectType_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdCorrectTypeIndex() { } + + internal IdCorrectTypeIndex() + : base(__resolvedName) { } + + public global::TestScheduleIssues? Find(int key) => FindSingle(key); + } + + private static IdCorrectTypeIndex? __IdCorrectType; + public IdCorrectTypeIndex IdCorrectType => __IdCorrectType ??= new(); + } + + public sealed class TestUniqueNotEquatableReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestUniqueNotEquatable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static TestUniqueNotEquatableReadOnly() { } + + internal TestUniqueNotEquatableReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class PrimaryKeyFieldIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestUniqueNotEquatableReadOnly, + global::TestUniqueNotEquatable, + TestEnumWithExplicitValues, + SpacetimeDB.BSATN.Enum + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "TestUniqueNotEquatable_PrimaryKeyField_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PrimaryKeyFieldIndex() { } + + internal PrimaryKeyFieldIndex() + : base(__resolvedName) { } + + public global::TestUniqueNotEquatable? Find(TestEnumWithExplicitValues key) => + FindSingle(key); + } + + private static PrimaryKeyFieldIndex? __PrimaryKeyField; + public PrimaryKeyFieldIndex PrimaryKeyField => __PrimaryKeyField ??= new(); + } +} + +#if !NET10_0_OR_GREATER +namespace SpacetimeDB.Internal +{ + public sealed partial class LocalReadOnly + { + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.PlayerReadOnly Player => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestAutoIncNotIntegerReadOnly TestAutoIncNotInteger => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestDefaultFieldValuesReadOnly TestDefaultFieldValues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestDuplicateTableNameReadOnly TestDuplicateTableName => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestIndexIssuesReadOnly TestIndexIssues => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithMissingScheduleAtFieldReadOnly TestScheduleWithMissingScheduleAtField => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithoutPrimaryKeyReadOnly TestScheduleWithoutPrimaryKey => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithoutScheduleAtReadOnly TestScheduleWithoutScheduleAt => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithWrongPrimaryKeyTypeReadOnly TestScheduleWithWrongPrimaryKeyType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestScheduleWithWrongScheduleAtTypeReadOnly TestScheduleWithWrongScheduleAtType => + new(); + public global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.ViewHandles.TestUniqueNotEquatableReadOnly TestUniqueNotEquatable => + new(); + } +} +#endif + +static class ModuleRegistration +{ + // Module host calls are single-threaded in Wasm today, so the generated + // entrypoints reuse buffers across calls to avoid per-invocation allocation. + private static byte[] reducerArgsBuffer = new byte[0x10_000]; + private static byte[] procedureArgsBuffer = new byte[0x10_000]; + private static byte[] httpRequestBuffer = new byte[0x10_000]; + private static byte[] httpRequestBodyBuffer = new byte[0x10_000]; + private static byte[] viewArgsBuffer = new byte[0x10_000]; + private static byte[] anonymousViewArgsBuffer = new byte[0x10_000]; + + sealed class __ReducerWithReservedPrefix : SpacetimeDB.Internal.IReducer + { + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(__ReducerWithReservedPrefix), + Params: [], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Reducers.__ReducerWithReservedPrefix((SpacetimeDB.ReducerContext)ctx); + } + } + + sealed class DummyScheduledReducer : SpacetimeDB.Internal.IReducer + { + private static readonly TestScheduleIssues.BSATN tableRW = new(); + + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(DummyScheduledReducer), + Params: [new("table", tableRW.GetAlgebraicType(registrar))], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + TestScheduleIssues.DummyScheduledReducer( + (SpacetimeDB.ReducerContext)ctx, + tableRW.Read(reader) + ); + } + } + + sealed class OnReducerWithReservedPrefix : SpacetimeDB.Internal.IReducer + { + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(OnReducerWithReservedPrefix), + Params: [], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Reducers.OnReducerWithReservedPrefix((SpacetimeDB.ReducerContext)ctx); + } + } + + sealed class TestDuplicateReducerKind1 : SpacetimeDB.Internal.IReducer + { + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestDuplicateReducerKind1), + Params: [], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => SpacetimeDB.Internal.Lifecycle.Init; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Reducers.TestDuplicateReducerKind1((SpacetimeDB.ReducerContext)ctx); + } + } + + sealed class TestDuplicateReducerKind2 : SpacetimeDB.Internal.IReducer + { + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestDuplicateReducerKind2), + Params: [], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => SpacetimeDB.Internal.Lifecycle.Init; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Reducers.TestDuplicateReducerKind2((SpacetimeDB.ReducerContext)ctx); + } + } + + sealed class TestDuplicateReducerName : SpacetimeDB.Internal.IReducer + { + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestDuplicateReducerName), + Params: [], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Reducers.TestDuplicateReducerName((SpacetimeDB.ReducerContext)ctx); + } + } + + sealed class TestReducerReturnType : SpacetimeDB.Internal.IReducer + { + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestReducerReturnType), + Params: [], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Reducers.TestReducerReturnType((SpacetimeDB.ReducerContext)ctx); + } + } + + sealed class TestReducerWithoutContext : SpacetimeDB.Internal.IReducer + { + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(TestReducerWithoutContext), + Params: [], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + throw new System.InvalidOperationException(); + } + } + + public static List ToListOrEmpty(T? value) + where T : struct => value is null ? new List() : new List { value.Value }; + + public static List ToListOrEmpty(T? value) + where T : class => value is null ? new List() : new List { value }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + // In AOT mode we're building a library. + // Main method won't be called automatically, so we need to export it as a preinit function. + [UnmanagedCallersOnly(EntryPoint = "__preinit__10_init_csharp")] +#else + // Prevent trimming of FFI exports that are invoked from C and not visible to C# trimmer. + [DynamicDependency(DynamicallyAccessedMemberTypes.PublicMethods, typeof(ModuleRegistration))] +#endif + public static void Main() => Initialize(); + + internal static void Initialize() + { +#if !NET10_0_OR_GREATER + SpacetimeDB.Internal.Module.SetReducerContextConstructor( + (identity, connectionId, random, time) => + new SpacetimeDB.ReducerContext(identity, connectionId, random, time) + ); + SpacetimeDB.Internal.Module.SetViewContextConstructor( + identity => new SpacetimeDB.ViewContext( + identity, + new SpacetimeDB.Internal.LocalReadOnly() + ) + ); + SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor(() => + new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly()) + ); + SpacetimeDB.Internal.Module.SetProcedureContextConstructor( + (identity, connectionId, random, time) => + new SpacetimeDB.ProcedureContext(identity, connectionId, random, time) + ); + SpacetimeDB.Internal.Module.SetHandlerContextConstructor( + (random, time) => new SpacetimeDB.HandlerContext(random, time) + ); +#endif + +#if NET10_0_OR_GREATER + global::SpacetimeDB.Internal.Module.InstallNamespaces( + new global::SpacetimeDB.Internal.NamespaceRegistry( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + global::SpacetimeDB.CaseConversionPolicy.SnakeCase, + new (string, string, string?, global::SpacetimeDB.CaseConversionPolicy)[] { } + ) + ); + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.Register( + global::SpacetimeDB.Internal.Module.RootBuilder + ); +#else + Register(global::SpacetimeDB.Internal.Module.RootBuilder); +#endif + } + + internal static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) + { + // HTTP routes retain the root routing API even for mounted modules. + httpBuilder ??= builder; + builder.SetCaseConversionPolicy(SpacetimeDB.CaseConversionPolicy.SnakeCase); + builder.RegisterExplicitIndexName( + "TestIndexIssues_SecondaryIndexingColumn_idx_btree", + "TestCanonicalNameWithoutAccessor" + ); + var __memoryStream = new MemoryStream(); + var __writer = new BinaryWriter(__memoryStream); + + builder.RegisterReducer<__ReducerWithReservedPrefix>(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + + // IMPORTANT: The order in which we register views matters. + // It must correspond to the order in which we call `GenerateDispatcherClass`. + // See the comment on `GenerateDispatcherClass` for more explanation. + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterAnonymousView(); + builder.RegisterAnonymousView(); + builder.RegisterAnonymousView(); + builder.RegisterAnonymousView(); + + builder.RegisterViewPrimaryKey("view_primary_key_missing_column", ["MissingIdentity"]); + builder.RegisterViewPrimaryKey("view_primary_key_non_equatable_column", ["Identity"]); + builder.RegisterViewPrimaryKey( + "view_primary_key_uses_non_bsatn_partial_field", + ["ExtraPartialIdentity"] + ); + builder.RegisterViewPrimaryKey( + "view_primary_key_uses_wrong_source_name", + ["renamed_identity"] + ); + + builder.RegisterTable< + global::Player, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.Player + >(); + builder.RegisterTable< + global::TestAutoIncNotInteger, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestAutoIncNotInteger + >(); + builder.RegisterTable< + global::TestDefaultFieldValues, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestDefaultFieldValues + >(); + builder.RegisterTable< + global::TestDuplicateTableName, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestDuplicateTableName + >(); + builder.RegisterTable< + global::TestIndexIssues, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestIndexIssues + >(); + builder.RegisterTable< + global::TestScheduleIssues, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithMissingScheduleAtField + >(); + builder.RegisterTable< + global::TestScheduleIssues, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithoutPrimaryKey + >(); + builder.RegisterTable< + global::TestScheduleIssues, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithoutScheduleAt + >(); + builder.RegisterTable< + global::TestScheduleIssues, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithWrongPrimaryKeyType + >(); + builder.RegisterTable< + global::TestScheduleIssues, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestScheduleWithWrongScheduleAtType + >(); + builder.RegisterTable< + global::TestUniqueNotEquatable, + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.TableHandles.TestUniqueNotEquatable + >(); + + builder.RegisterClientVisibilityFilter(global::Module.MY_FILTER); + builder.RegisterClientVisibilityFilter(global::Module.MY_FOURTH_FILTER); + builder.RegisterClientVisibilityFilter(global::Module.MY_SECOND_FILTER); + builder.RegisterClientVisibilityFilter(global::Module.MY_THIRD_FILTER); + { + var value = new SpacetimeDB.BSATN.String(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, "A default string set by attribute"); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 1, array); + } + + { + var value = new SpacetimeDB.BSATN.U64(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 10, array); + } + + { + var value = new SpacetimeDB.BSATN.I32(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 11, array); + } + + { + var value = new SpacetimeDB.BSATN.I32(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 12, array); + } + + { + var value = new SpacetimeDB.BSATN.F32(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2F); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 13, array); + } + + { + var value = new SpacetimeDB.BSATN.F64(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 14, array); + } + + { + var value = new SpacetimeDB.BSATN.Enum(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, (MyEnum)2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 15, array); + } + + { + var value = new SpacetimeDB.BSATN.ValueOption(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, null); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 16, array); + } + + { + var value = new SpacetimeDB.BSATN.Bool(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, true); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 2, array); + } + + { + var value = new SpacetimeDB.BSATN.I8(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 3, array); + } + + { + var value = new SpacetimeDB.BSATN.U8(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 4, array); + } + + { + var value = new SpacetimeDB.BSATN.I16(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 5, array); + } + + { + var value = new SpacetimeDB.BSATN.U16(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 6, array); + } + + { + var value = new SpacetimeDB.BSATN.I32(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 7, array); + } + + { + var value = new SpacetimeDB.BSATN.U32(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 8, array); + } + + { + var value = new SpacetimeDB.BSATN.I64(); + __memoryStream.Position = 0; + __memoryStream.SetLength(0); + value.Write(__writer, 2); + var array = __memoryStream.ToArray(); + builder.RegisterTableDefaultValue("TestDefaultFieldValues", 9, array); + } + } + + // Export entrypoints live in generated module code so all build modes can + // dispatch directly to concrete generated functions. +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__describe_module__")] +#endif + public static void __describe_module__(SpacetimeDB.Internal.BytesSink d) => + SpacetimeDB.Internal.Module.__describe_module__(d); + + private static SpacetimeDB.Internal.Errno __call_reducer_0( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + __ReducerWithReservedPrefix.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_1( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + DummyScheduledReducer.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_2( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + OnReducerWithReservedPrefix.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_3( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + TestDuplicateReducerKind1.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_4( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + TestDuplicateReducerKind2.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_5( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + TestDuplicateReducerName.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_6( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + TestReducerReturnType.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_7( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + TestReducerWithoutContext.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_view_0( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_def_ienumerable_return_from_filterViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_1( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_def_ienumerable_return_from_iterViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_2( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_def_no_contextViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_3( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_def_no_publicViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_4( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_def_wrong_contextViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_5( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_def_wrong_returnViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_6( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_no_deleteViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_7( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_no_insertViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_8( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_primary_key_missing_columnViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_9( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_primary_key_non_equatable_columnViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_10( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_primary_key_uses_non_bsatn_partial_fieldViewDispatcher.Invoke( + reader, + ctx + ); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_11( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_primary_key_uses_wrong_source_nameViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_anon_0( + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateAnonymousViewContext(); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref anonymousViewArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_def_index_no_mutationViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking anonymous view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_anon_1( + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateAnonymousViewContext(); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref anonymousViewArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_def_no_anon_identityViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking anonymous view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_anon_2( + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateAnonymousViewContext(); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref anonymousViewArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_def_no_iterViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking anonymous view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_anon_3( + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateAnonymousViewContext(); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref anonymousViewArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + var bytes = view_def_returns_not_a_spacetime_typeViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking anonymous view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_reducer__")] +#endif + public static SpacetimeDB.Internal.Errno __call_reducer__( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.ReducerCount + ) + return global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.CallLocalReducer( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + localId -= global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .ReducerCount; + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); +#else + return CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) => + id switch + { + 0 => __call_reducer_0( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 1 => __call_reducer_1( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 2 => __call_reducer_2( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 3 => __call_reducer_3( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 4 => __call_reducer_4( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 5 => __call_reducer_5( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 6 => __call_reducer_6( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 7 => __call_reducer_7( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + _ => SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_procedure__")] +#endif + public static SpacetimeDB.Internal.Errno __call_procedure__( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .ProcedureCount + ) + return global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.CallLocalProcedure( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + localId -= global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .ProcedureCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); +#else + return CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink + ) => + id switch + { + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown procedure id" + ), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_http_handler__")] +#endif + public static SpacetimeDB.Internal.Errno __call_http_handler__( + int id, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource request, + SpacetimeDB.Internal.BytesSource request_body, + SpacetimeDB.Internal.BytesSink response_sink, + SpacetimeDB.Internal.BytesSink response_body_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .HttpHandlerCount + ) + return global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.CallLocalHttpHandler( + localId, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + localId -= global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .HttpHandlerCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); +#else + return CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource request, + SpacetimeDB.Internal.BytesSource request_body, + SpacetimeDB.Internal.BytesSink response_sink, + SpacetimeDB.Internal.BytesSink response_body_sink + ) => + id switch + { + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown HTTP handler id" + ), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_view__")] +#endif + public static SpacetimeDB.Internal.Errno __call_view__( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint)global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.ViewCount + ) + return global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.CallLocalView( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + localId -= global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.ViewCount; + return UnknownViewId(id); +#else + return CallLocalView(id, sender_0, sender_1, sender_2, sender_3, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) => + id switch + { + 0 => __call_view_0(sender_0, sender_1, sender_2, sender_3, args, sink), + 1 => __call_view_1(sender_0, sender_1, sender_2, sender_3, args, sink), + 2 => __call_view_2(sender_0, sender_1, sender_2, sender_3, args, sink), + 3 => __call_view_3(sender_0, sender_1, sender_2, sender_3, args, sink), + 4 => __call_view_4(sender_0, sender_1, sender_2, sender_3, args, sink), + 5 => __call_view_5(sender_0, sender_1, sender_2, sender_3, args, sink), + 6 => __call_view_6(sender_0, sender_1, sender_2, sender_3, args, sink), + 7 => __call_view_7(sender_0, sender_1, sender_2, sender_3, args, sink), + 8 => __call_view_8(sender_0, sender_1, sender_2, sender_3, args, sink), + 9 => __call_view_9(sender_0, sender_1, sender_2, sender_3, args, sink), + 10 => __call_view_10(sender_0, sender_1, sender_2, sender_3, args, sink), + 11 => __call_view_11(sender_0, sender_1, sender_2, sender_3, args, sink), + _ => UnknownViewId(id), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_view_anon__")] +#endif + public static SpacetimeDB.Internal.Errno __call_view_anon__( + int id, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownAnonymousViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .AnonymousViewCount + ) + return global::SpacetimeDB.Generated.diag_4F830E2879BB50E3.AssemblyDescriptor.CallLocalAnonymousView( + localId, + args, + sink + ); + localId -= global::SpacetimeDB + .Generated + .diag_4F830E2879BB50E3 + .AssemblyDescriptor + .AnonymousViewCount; + return UnknownAnonymousViewId(id); +#else + return CallLocalAnonymousView(id, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) => + id switch + { + 0 => __call_view_anon_0(args, sink), + 1 => __call_view_anon_1(args, sink), + 2 => __call_view_anon_2(args, sink), + 3 => __call_view_anon_3(args, sink), + _ => UnknownAnonymousViewId(id), + }; + + private static SpacetimeDB.Internal.Errno UnknownViewId(int id) + { + SpacetimeDB.Log.Error($"Unknown view id: {id}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + + private static SpacetimeDB.Internal.Errno UnknownAnonymousViewId(int id) + { + SpacetimeDB.Log.Error($"Unknown anonymous view id: {id}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } +} + +#pragma warning restore STDB_UNSTABLE +#pragma warning restore CS0436 diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#InAnotherNamespace.TestDuplicateTableName.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#InAnotherNamespace.TestDuplicateTableName.verified.cs new file mode 100644 index 00000000000..c48b0e9e277 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#InAnotherNamespace.TestDuplicateTableName.verified.cs @@ -0,0 +1,104 @@ +//HintName: InAnotherNamespace.TestDuplicateTableName.cs +// +#nullable enable + +partial class InAnotherNamespace +{ + partial struct TestDuplicateTableName + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite + { + public void ReadFields(System.IO.BinaryReader reader) { } + + public void WriteFields(System.IO.BinaryWriter writer) { } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => $"TestDuplicateTableName {{ }}"; + + public readonly partial struct BSATN + : SpacetimeDB.BSATN.IReadWrite + { + public InAnotherNamespace.TestDuplicateTableName Read(System.IO.BinaryReader reader) + { + var ___result = new InAnotherNamespace.TestDuplicateTableName(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write( + System.IO.BinaryWriter writer, + InAnotherNamespace.TestDuplicateTableName value + ) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] { } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + return 0; + } + +#nullable enable + public bool Equals(InAnotherNamespace.TestDuplicateTableName that) + { + return true; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as InAnotherNamespace.TestDuplicateTableName?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==( + InAnotherNamespace.TestDuplicateTableName this_, + InAnotherNamespace.TestDuplicateTableName that + ) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=( + InAnotherNamespace.TestDuplicateTableName this_, + InAnotherNamespace.TestDuplicateTableName that + ) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore + } // TestDuplicateTableName +} // InAnotherNamespace diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Player.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Player.verified.cs new file mode 100644 index 00000000000..afcd60afc5b --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Player.verified.cs @@ -0,0 +1,101 @@ +//HintName: Player.cs +// +#nullable enable + +partial struct Player : System.IEquatable, SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + Identity = BSATN.IdentityRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.IdentityRW.Write(writer, Identity); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"Player {{ Identity = {SpacetimeDB.BSATN.StringUtil.GenericToString(Identity)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.Identity.BSATN IdentityRW = new(); + + public Player Read(System.IO.BinaryReader reader) + { + var ___result = new Player(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, Player value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType(_ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("Identity", IdentityRW.GetAlgebraicType(registrar)), + } + )); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashIdentity = Identity.GetHashCode(); + return ___hashIdentity; + } + +#nullable enable + public bool Equals(Player that) + { + var ___eqIdentity = this.Identity.Equals(that.Identity); + return ___eqIdentity; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as Player?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(Player this_, Player that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(Player this_, Player that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // Player diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.InAnotherNamespace.TestDuplicateReducerName.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.InAnotherNamespace.TestDuplicateReducerName.verified.cs new file mode 100644 index 00000000000..f8fde775eba --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.InAnotherNamespace.TestDuplicateReducerName.verified.cs @@ -0,0 +1,34 @@ +//HintName: Reducers.InAnotherNamespace.TestDuplicateReducerName.cs +// +#nullable enable + +partial class Reducers +{ + partial class InAnotherNamespace + { + private static class __ScheduleTestDuplicateReducerNameName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(TestDuplicateReducerName), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleTestDuplicateReducerNameName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateTestDuplicateReducerName() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleTestDuplicateReducerNameName.Name, + stream + ); + } + } // InAnotherNamespace +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.OnReducerWithReservedPrefix.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.OnReducerWithReservedPrefix.verified.cs new file mode 100644 index 00000000000..6a8071fa8dd --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.OnReducerWithReservedPrefix.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.OnReducerWithReservedPrefix.cs +// +#nullable enable + +partial class Reducers +{ + private static class __ScheduleOnReducerWithReservedPrefixName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(OnReducerWithReservedPrefix), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleOnReducerWithReservedPrefixName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateOnReducerWithReservedPrefix() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleOnReducerWithReservedPrefixName.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestDuplicateReducerKind1.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestDuplicateReducerKind1.verified.cs new file mode 100644 index 00000000000..05e5e398cba --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestDuplicateReducerKind1.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.TestDuplicateReducerKind1.cs +// +#nullable enable + +partial class Reducers +{ + private static class __ScheduleTestDuplicateReducerKind1Name + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(TestDuplicateReducerKind1), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleTestDuplicateReducerKind1Name() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateTestDuplicateReducerKind1() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleTestDuplicateReducerKind1Name.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestDuplicateReducerKind2.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestDuplicateReducerKind2.verified.cs new file mode 100644 index 00000000000..b1779d73fd8 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestDuplicateReducerKind2.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.TestDuplicateReducerKind2.cs +// +#nullable enable + +partial class Reducers +{ + private static class __ScheduleTestDuplicateReducerKind2Name + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(TestDuplicateReducerKind2), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleTestDuplicateReducerKind2Name() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateTestDuplicateReducerKind2() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleTestDuplicateReducerKind2Name.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestDuplicateReducerName.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestDuplicateReducerName.verified.cs new file mode 100644 index 00000000000..865a64341ea --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestDuplicateReducerName.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.TestDuplicateReducerName.cs +// +#nullable enable + +partial class Reducers +{ + private static class __ScheduleTestDuplicateReducerNameName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(TestDuplicateReducerName), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleTestDuplicateReducerNameName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateTestDuplicateReducerName() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleTestDuplicateReducerNameName.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestReducerReturnType.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestReducerReturnType.verified.cs new file mode 100644 index 00000000000..1bd50b93319 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestReducerReturnType.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.TestReducerReturnType.cs +// +#nullable enable + +partial class Reducers +{ + private static class __ScheduleTestReducerReturnTypeName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(TestReducerReturnType), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleTestReducerReturnTypeName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateTestReducerReturnType() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleTestReducerReturnTypeName.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestReducerWithoutContext.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestReducerWithoutContext.verified.cs new file mode 100644 index 00000000000..e1c79a74513 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.TestReducerWithoutContext.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.TestReducerWithoutContext.cs +// +#nullable enable + +partial class Reducers +{ + private static class __ScheduleTestReducerWithoutContextName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(TestReducerWithoutContext), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleTestReducerWithoutContextName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateTestReducerWithoutContext() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleTestReducerWithoutContextName.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.__ReducerWithReservedPrefix.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.__ReducerWithReservedPrefix.verified.cs new file mode 100644 index 00000000000..e6bc0fee962 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#Reducers.__ReducerWithReservedPrefix.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.__ReducerWithReservedPrefix.cs +// +#nullable enable + +partial class Reducers +{ + private static class __Schedule__ReducerWithReservedPrefixName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(__ReducerWithReservedPrefix), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __Schedule__ReducerWithReservedPrefixName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediate__ReducerWithReservedPrefix() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __Schedule__ReducerWithReservedPrefixName.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestAutoIncNotInteger.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestAutoIncNotInteger.verified.cs new file mode 100644 index 00000000000..089c7521c72 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestAutoIncNotInteger.verified.cs @@ -0,0 +1,114 @@ +//HintName: TestAutoIncNotInteger.cs +// +#nullable enable + +partial struct TestAutoIncNotInteger + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + AutoIncField = BSATN.AutoIncFieldRW.Read(reader); + IdentityField = BSATN.IdentityFieldRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.AutoIncFieldRW.Write(writer, AutoIncField); + BSATN.IdentityFieldRW.Write(writer, IdentityField); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"TestAutoIncNotInteger {{ AutoIncField = {SpacetimeDB.BSATN.StringUtil.GenericToString(AutoIncField)}, IdentityField = {SpacetimeDB.BSATN.StringUtil.GenericToString(IdentityField)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.F32 AutoIncFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.String IdentityFieldRW = new(); + + public TestAutoIncNotInteger Read(System.IO.BinaryReader reader) + { + var ___result = new TestAutoIncNotInteger(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, TestAutoIncNotInteger value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("AutoIncField", AutoIncFieldRW.GetAlgebraicType(registrar)), + new("IdentityField", IdentityFieldRW.GetAlgebraicType(registrar)), + } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashAutoIncField = AutoIncField.GetHashCode(); + var ___hashIdentityField = IdentityField == null ? 0 : IdentityField.GetHashCode(); + return ___hashAutoIncField ^ ___hashIdentityField; + } + +#nullable enable + public bool Equals(TestAutoIncNotInteger that) + { + var ___eqAutoIncField = this.AutoIncField.Equals(that.AutoIncField); + var ___eqIdentityField = + this.IdentityField == null + ? that.IdentityField == null + : this.IdentityField.Equals(that.IdentityField); + return ___eqAutoIncField && ___eqIdentityField; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as TestAutoIncNotInteger?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(TestAutoIncNotInteger this_, TestAutoIncNotInteger that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(TestAutoIncNotInteger this_, TestAutoIncNotInteger that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // TestAutoIncNotInteger diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestDefaultFieldValues.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestDefaultFieldValues.verified.cs new file mode 100644 index 00000000000..bf5c8f0b4fc --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestDefaultFieldValues.verified.cs @@ -0,0 +1,242 @@ +//HintName: TestDefaultFieldValues.cs +// +#nullable enable + +partial struct TestDefaultFieldValues + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + UniqueField = BSATN.UniqueFieldRW.Read(reader); + DefaultString = BSATN.DefaultStringRW.Read(reader); + DefaultBool = BSATN.DefaultBoolRW.Read(reader); + DefaultI8 = BSATN.DefaultI8RW.Read(reader); + DefaultU8 = BSATN.DefaultU8RW.Read(reader); + DefaultI16 = BSATN.DefaultI16RW.Read(reader); + DefaultU16 = BSATN.DefaultU16RW.Read(reader); + DefaultI32 = BSATN.DefaultI32RW.Read(reader); + DefaultU32 = BSATN.DefaultU32RW.Read(reader); + DefaultI64 = BSATN.DefaultI64RW.Read(reader); + DefaultU64 = BSATN.DefaultU64RW.Read(reader); + DefaultHex = BSATN.DefaultHexRW.Read(reader); + DefaultBin = BSATN.DefaultBinRW.Read(reader); + DefaultF32 = BSATN.DefaultF32RW.Read(reader); + DefaultF64 = BSATN.DefaultF64RW.Read(reader); + DefaultEnum = BSATN.DefaultEnumRW.Read(reader); + DefaultNull = BSATN.DefaultNullRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.UniqueFieldRW.Write(writer, UniqueField); + BSATN.DefaultStringRW.Write(writer, DefaultString); + BSATN.DefaultBoolRW.Write(writer, DefaultBool); + BSATN.DefaultI8RW.Write(writer, DefaultI8); + BSATN.DefaultU8RW.Write(writer, DefaultU8); + BSATN.DefaultI16RW.Write(writer, DefaultI16); + BSATN.DefaultU16RW.Write(writer, DefaultU16); + BSATN.DefaultI32RW.Write(writer, DefaultI32); + BSATN.DefaultU32RW.Write(writer, DefaultU32); + BSATN.DefaultI64RW.Write(writer, DefaultI64); + BSATN.DefaultU64RW.Write(writer, DefaultU64); + BSATN.DefaultHexRW.Write(writer, DefaultHex); + BSATN.DefaultBinRW.Write(writer, DefaultBin); + BSATN.DefaultF32RW.Write(writer, DefaultF32); + BSATN.DefaultF64RW.Write(writer, DefaultF64); + BSATN.DefaultEnumRW.Write(writer, DefaultEnum); + BSATN.DefaultNullRW.Write(writer, DefaultNull); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"TestDefaultFieldValues {{ UniqueField = {SpacetimeDB.BSATN.StringUtil.GenericToString(UniqueField)}, DefaultString = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultString)}, DefaultBool = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultBool)}, DefaultI8 = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultI8)}, DefaultU8 = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultU8)}, DefaultI16 = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultI16)}, DefaultU16 = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultU16)}, DefaultI32 = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultI32)}, DefaultU32 = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultU32)}, DefaultI64 = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultI64)}, DefaultU64 = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultU64)}, DefaultHex = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultHex)}, DefaultBin = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultBin)}, DefaultF32 = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultF32)}, DefaultF64 = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultF64)}, DefaultEnum = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultEnum)}, DefaultNull = {SpacetimeDB.BSATN.StringUtil.GenericToString(DefaultNull)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.ValueOption< + int, + SpacetimeDB.BSATN.I32 + > UniqueFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.String DefaultStringRW = new(); + internal static readonly SpacetimeDB.BSATN.Bool DefaultBoolRW = new(); + internal static readonly SpacetimeDB.BSATN.I8 DefaultI8RW = new(); + internal static readonly SpacetimeDB.BSATN.U8 DefaultU8RW = new(); + internal static readonly SpacetimeDB.BSATN.I16 DefaultI16RW = new(); + internal static readonly SpacetimeDB.BSATN.U16 DefaultU16RW = new(); + internal static readonly SpacetimeDB.BSATN.I32 DefaultI32RW = new(); + internal static readonly SpacetimeDB.BSATN.U32 DefaultU32RW = new(); + internal static readonly SpacetimeDB.BSATN.I64 DefaultI64RW = new(); + internal static readonly SpacetimeDB.BSATN.U64 DefaultU64RW = new(); + internal static readonly SpacetimeDB.BSATN.I32 DefaultHexRW = new(); + internal static readonly SpacetimeDB.BSATN.I32 DefaultBinRW = new(); + internal static readonly SpacetimeDB.BSATN.F32 DefaultF32RW = new(); + internal static readonly SpacetimeDB.BSATN.F64 DefaultF64RW = new(); + internal static readonly SpacetimeDB.BSATN.Enum DefaultEnumRW = new(); + internal static readonly SpacetimeDB.BSATN.ValueOption< + MyStruct, + MyStruct.BSATN + > DefaultNullRW = new(); + + public TestDefaultFieldValues Read(System.IO.BinaryReader reader) + { + var ___result = new TestDefaultFieldValues(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, TestDefaultFieldValues value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("UniqueField", UniqueFieldRW.GetAlgebraicType(registrar)), + new("DefaultString", DefaultStringRW.GetAlgebraicType(registrar)), + new("DefaultBool", DefaultBoolRW.GetAlgebraicType(registrar)), + new("DefaultI8", DefaultI8RW.GetAlgebraicType(registrar)), + new("DefaultU8", DefaultU8RW.GetAlgebraicType(registrar)), + new("DefaultI16", DefaultI16RW.GetAlgebraicType(registrar)), + new("DefaultU16", DefaultU16RW.GetAlgebraicType(registrar)), + new("DefaultI32", DefaultI32RW.GetAlgebraicType(registrar)), + new("DefaultU32", DefaultU32RW.GetAlgebraicType(registrar)), + new("DefaultI64", DefaultI64RW.GetAlgebraicType(registrar)), + new("DefaultU64", DefaultU64RW.GetAlgebraicType(registrar)), + new("DefaultHex", DefaultHexRW.GetAlgebraicType(registrar)), + new("DefaultBin", DefaultBinRW.GetAlgebraicType(registrar)), + new("DefaultF32", DefaultF32RW.GetAlgebraicType(registrar)), + new("DefaultF64", DefaultF64RW.GetAlgebraicType(registrar)), + new("DefaultEnum", DefaultEnumRW.GetAlgebraicType(registrar)), + new("DefaultNull", DefaultNullRW.GetAlgebraicType(registrar)), + } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashUniqueField = UniqueField.GetHashCode(); + var ___hashDefaultString = DefaultString == null ? 0 : DefaultString.GetHashCode(); + var ___hashDefaultBool = DefaultBool.GetHashCode(); + var ___hashDefaultI8 = DefaultI8.GetHashCode(); + var ___hashDefaultU8 = DefaultU8.GetHashCode(); + var ___hashDefaultI16 = DefaultI16.GetHashCode(); + var ___hashDefaultU16 = DefaultU16.GetHashCode(); + var ___hashDefaultI32 = DefaultI32.GetHashCode(); + var ___hashDefaultU32 = DefaultU32.GetHashCode(); + var ___hashDefaultI64 = DefaultI64.GetHashCode(); + var ___hashDefaultU64 = DefaultU64.GetHashCode(); + var ___hashDefaultHex = DefaultHex.GetHashCode(); + var ___hashDefaultBin = DefaultBin.GetHashCode(); + var ___hashDefaultF32 = DefaultF32.GetHashCode(); + var ___hashDefaultF64 = DefaultF64.GetHashCode(); + var ___hashDefaultEnum = DefaultEnum.GetHashCode(); + var ___hashDefaultNull = DefaultNull.GetHashCode(); + return ___hashUniqueField + ^ ___hashDefaultString + ^ ___hashDefaultBool + ^ ___hashDefaultI8 + ^ ___hashDefaultU8 + ^ ___hashDefaultI16 + ^ ___hashDefaultU16 + ^ ___hashDefaultI32 + ^ ___hashDefaultU32 + ^ ___hashDefaultI64 + ^ ___hashDefaultU64 + ^ ___hashDefaultHex + ^ ___hashDefaultBin + ^ ___hashDefaultF32 + ^ ___hashDefaultF64 + ^ ___hashDefaultEnum + ^ ___hashDefaultNull; + } + +#nullable enable + public bool Equals(TestDefaultFieldValues that) + { + var ___eqUniqueField = System.Nullable.Equals(this.UniqueField, that.UniqueField); + var ___eqDefaultString = + this.DefaultString == null + ? that.DefaultString == null + : this.DefaultString.Equals(that.DefaultString); + var ___eqDefaultBool = this.DefaultBool.Equals(that.DefaultBool); + var ___eqDefaultI8 = this.DefaultI8.Equals(that.DefaultI8); + var ___eqDefaultU8 = this.DefaultU8.Equals(that.DefaultU8); + var ___eqDefaultI16 = this.DefaultI16.Equals(that.DefaultI16); + var ___eqDefaultU16 = this.DefaultU16.Equals(that.DefaultU16); + var ___eqDefaultI32 = this.DefaultI32.Equals(that.DefaultI32); + var ___eqDefaultU32 = this.DefaultU32.Equals(that.DefaultU32); + var ___eqDefaultI64 = this.DefaultI64.Equals(that.DefaultI64); + var ___eqDefaultU64 = this.DefaultU64.Equals(that.DefaultU64); + var ___eqDefaultHex = this.DefaultHex.Equals(that.DefaultHex); + var ___eqDefaultBin = this.DefaultBin.Equals(that.DefaultBin); + var ___eqDefaultF32 = this.DefaultF32.Equals(that.DefaultF32); + var ___eqDefaultF64 = this.DefaultF64.Equals(that.DefaultF64); + var ___eqDefaultEnum = this.DefaultEnum == that.DefaultEnum; + var ___eqDefaultNull = System.Nullable.Equals(this.DefaultNull, that.DefaultNull); + return ___eqUniqueField + && ___eqDefaultString + && ___eqDefaultBool + && ___eqDefaultI8 + && ___eqDefaultU8 + && ___eqDefaultI16 + && ___eqDefaultU16 + && ___eqDefaultI32 + && ___eqDefaultU32 + && ___eqDefaultI64 + && ___eqDefaultU64 + && ___eqDefaultHex + && ___eqDefaultBin + && ___eqDefaultF32 + && ___eqDefaultF64 + && ___eqDefaultEnum + && ___eqDefaultNull; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as TestDefaultFieldValues?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(TestDefaultFieldValues this_, TestDefaultFieldValues that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(TestDefaultFieldValues this_, TestDefaultFieldValues that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // TestDefaultFieldValues diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestDuplicateTableName.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestDuplicateTableName.verified.cs new file mode 100644 index 00000000000..f745f9847c0 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestDuplicateTableName.verified.cs @@ -0,0 +1,91 @@ +//HintName: TestDuplicateTableName.cs +// +#nullable enable + +partial struct TestDuplicateTableName + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) { } + + public void WriteFields(System.IO.BinaryWriter writer) { } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => $"TestDuplicateTableName {{ }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + public TestDuplicateTableName Read(System.IO.BinaryReader reader) + { + var ___result = new TestDuplicateTableName(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, TestDuplicateTableName value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] { } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + return 0; + } + +#nullable enable + public bool Equals(TestDuplicateTableName that) + { + return true; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as TestDuplicateTableName?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(TestDuplicateTableName this_, TestDuplicateTableName that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(TestDuplicateTableName this_, TestDuplicateTableName that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // TestDuplicateTableName diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestIndexIssues.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestIndexIssues.verified.cs new file mode 100644 index 00000000000..3dd8a0a7425 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestIndexIssues.verified.cs @@ -0,0 +1,116 @@ +//HintName: TestIndexIssues.cs +// +#nullable enable + +partial struct TestIndexIssues + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + SelfIndexingColumn = BSATN.SelfIndexingColumnRW.Read(reader); + SecondaryIndexingColumn = BSATN.SecondaryIndexingColumnRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.SelfIndexingColumnRW.Write(writer, SelfIndexingColumn); + BSATN.SecondaryIndexingColumnRW.Write(writer, SecondaryIndexingColumn); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"TestIndexIssues {{ SelfIndexingColumn = {SpacetimeDB.BSATN.StringUtil.GenericToString(SelfIndexingColumn)}, SecondaryIndexingColumn = {SpacetimeDB.BSATN.StringUtil.GenericToString(SecondaryIndexingColumn)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.I32 SelfIndexingColumnRW = new(); + internal static readonly SpacetimeDB.BSATN.I32 SecondaryIndexingColumnRW = new(); + + public TestIndexIssues Read(System.IO.BinaryReader reader) + { + var ___result = new TestIndexIssues(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, TestIndexIssues value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("SelfIndexingColumn", SelfIndexingColumnRW.GetAlgebraicType(registrar)), + new( + "SecondaryIndexingColumn", + SecondaryIndexingColumnRW.GetAlgebraicType(registrar) + ), + } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashSelfIndexingColumn = SelfIndexingColumn.GetHashCode(); + var ___hashSecondaryIndexingColumn = SecondaryIndexingColumn.GetHashCode(); + return ___hashSelfIndexingColumn ^ ___hashSecondaryIndexingColumn; + } + +#nullable enable + public bool Equals(TestIndexIssues that) + { + var ___eqSelfIndexingColumn = this.SelfIndexingColumn.Equals(that.SelfIndexingColumn); + var ___eqSecondaryIndexingColumn = this.SecondaryIndexingColumn.Equals( + that.SecondaryIndexingColumn + ); + return ___eqSelfIndexingColumn && ___eqSecondaryIndexingColumn; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as TestIndexIssues?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(TestIndexIssues this_, TestIndexIssues that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(TestIndexIssues this_, TestIndexIssues that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // TestIndexIssues diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestScheduleIssues.DummyScheduledReducer.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestScheduleIssues.DummyScheduledReducer.verified.cs new file mode 100644 index 00000000000..58d0fe081e9 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestScheduleIssues.DummyScheduledReducer.verified.cs @@ -0,0 +1,33 @@ +//HintName: TestScheduleIssues.DummyScheduledReducer.cs +// +#nullable enable + +partial struct TestScheduleIssues +{ + private static class __ScheduleDummyScheduledReducerName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "diag, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(DummyScheduledReducer), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleDummyScheduledReducerName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateDummyScheduledReducer( + TestScheduleIssues table + ) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + new TestScheduleIssues.BSATN().Write(writer, table); + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleDummyScheduledReducerName.Name, + stream + ); + } +} // TestScheduleIssues diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestScheduleIssues.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestScheduleIssues.verified.cs new file mode 100644 index 00000000000..cfbfc151870 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestScheduleIssues.verified.cs @@ -0,0 +1,142 @@ +//HintName: TestScheduleIssues.cs +// +#nullable enable + +partial struct TestScheduleIssues + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + IdWrongType = BSATN.IdWrongTypeRW.Read(reader); + IdCorrectType = BSATN.IdCorrectTypeRW.Read(reader); + ScheduleAtWrongType = BSATN.ScheduleAtWrongTypeRW.Read(reader); + ScheduleAtCorrectType = BSATN.ScheduleAtCorrectTypeRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.IdWrongTypeRW.Write(writer, IdWrongType); + BSATN.IdCorrectTypeRW.Write(writer, IdCorrectType); + BSATN.ScheduleAtWrongTypeRW.Write(writer, ScheduleAtWrongType); + BSATN.ScheduleAtCorrectTypeRW.Write(writer, ScheduleAtCorrectType); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"TestScheduleIssues {{ IdWrongType = {SpacetimeDB.BSATN.StringUtil.GenericToString(IdWrongType)}, IdCorrectType = {SpacetimeDB.BSATN.StringUtil.GenericToString(IdCorrectType)}, ScheduleAtWrongType = {SpacetimeDB.BSATN.StringUtil.GenericToString(ScheduleAtWrongType)}, ScheduleAtCorrectType = {SpacetimeDB.BSATN.StringUtil.GenericToString(ScheduleAtCorrectType)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.String IdWrongTypeRW = new(); + internal static readonly SpacetimeDB.BSATN.I32 IdCorrectTypeRW = new(); + internal static readonly SpacetimeDB.BSATN.I32 ScheduleAtWrongTypeRW = new(); + internal static readonly SpacetimeDB.ScheduleAt.BSATN ScheduleAtCorrectTypeRW = new(); + + public TestScheduleIssues Read(System.IO.BinaryReader reader) + { + var ___result = new TestScheduleIssues(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, TestScheduleIssues value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("IdWrongType", IdWrongTypeRW.GetAlgebraicType(registrar)), + new("IdCorrectType", IdCorrectTypeRW.GetAlgebraicType(registrar)), + new( + "ScheduleAtWrongType", + ScheduleAtWrongTypeRW.GetAlgebraicType(registrar) + ), + new( + "ScheduleAtCorrectType", + ScheduleAtCorrectTypeRW.GetAlgebraicType(registrar) + ), + } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashIdWrongType = IdWrongType == null ? 0 : IdWrongType.GetHashCode(); + var ___hashIdCorrectType = IdCorrectType.GetHashCode(); + var ___hashScheduleAtWrongType = ScheduleAtWrongType.GetHashCode(); + var ___hashScheduleAtCorrectType = + ScheduleAtCorrectType == null ? 0 : ScheduleAtCorrectType.GetHashCode(); + return ___hashIdWrongType + ^ ___hashIdCorrectType + ^ ___hashScheduleAtWrongType + ^ ___hashScheduleAtCorrectType; + } + +#nullable enable + public bool Equals(TestScheduleIssues that) + { + var ___eqIdWrongType = + this.IdWrongType == null + ? that.IdWrongType == null + : this.IdWrongType.Equals(that.IdWrongType); + var ___eqIdCorrectType = this.IdCorrectType.Equals(that.IdCorrectType); + var ___eqScheduleAtWrongType = this.ScheduleAtWrongType.Equals(that.ScheduleAtWrongType); + var ___eqScheduleAtCorrectType = + this.ScheduleAtCorrectType == null + ? that.ScheduleAtCorrectType == null + : this.ScheduleAtCorrectType.Equals(that.ScheduleAtCorrectType); + return ___eqIdWrongType + && ___eqIdCorrectType + && ___eqScheduleAtWrongType + && ___eqScheduleAtCorrectType; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as TestScheduleIssues?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(TestScheduleIssues this_, TestScheduleIssues that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(TestScheduleIssues this_, TestScheduleIssues that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // TestScheduleIssues diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestTableTaggedEnum.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestTableTaggedEnum.verified.cs new file mode 100644 index 00000000000..38190b0b5f7 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestTableTaggedEnum.verified.cs @@ -0,0 +1,83 @@ +//HintName: TestTableTaggedEnum.cs +// +#nullable enable + +partial record TestTableTaggedEnum : System.IEquatable +{ + public sealed record X(int X_) : TestTableTaggedEnum + { + public override string ToString() => + $"X({SpacetimeDB.BSATN.StringUtil.GenericToString(X_)})"; + } + + public sealed record Y(int Y_) : TestTableTaggedEnum + { + public override string ToString() => + $"Y({SpacetimeDB.BSATN.StringUtil.GenericToString(Y_)})"; + } + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.I32 XRW = new(); + internal static readonly SpacetimeDB.BSATN.I32 YRW = new(); + + public TestTableTaggedEnum Read(System.IO.BinaryReader reader) + { + return reader.ReadByte() switch + { + 0 => new X(XRW.Read(reader)), + 1 => new Y(YRW.Read(reader)), + _ => throw new System.InvalidOperationException( + "Invalid tag value, this state should be unreachable." + ), + }; + } + + public void Write(System.IO.BinaryWriter writer, TestTableTaggedEnum value) + { + switch (value) + { + case X(var inner): + writer.Write((byte)0); + XRW.Write(writer, inner); + break; + case Y(var inner): + writer.Write((byte)1); + YRW.Write(writer, inner); + break; + } + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Sum( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("X", XRW.GetAlgebraicType(registrar)), + new("Y", YRW.GetAlgebraicType(registrar)), + } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + switch (this) + { + case X(var inner): + var ___hashX = inner.GetHashCode(); + return ___hashX; + case Y(var inner): + var ___hashY = inner.GetHashCode(); + return ___hashY; + default: + return 0; + } + } +} // TestTableTaggedEnum diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestUniqueNotEquatable.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestUniqueNotEquatable.verified.cs new file mode 100644 index 00000000000..c635f1a06ee --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10#TestUniqueNotEquatable.verified.cs @@ -0,0 +1,115 @@ +//HintName: TestUniqueNotEquatable.cs +// +#nullable enable + +partial struct TestUniqueNotEquatable + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + UniqueField = BSATN.UniqueFieldRW.Read(reader); + PrimaryKeyField = BSATN.PrimaryKeyFieldRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.UniqueFieldRW.Write(writer, UniqueField); + BSATN.PrimaryKeyFieldRW.Write(writer, PrimaryKeyField); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"TestUniqueNotEquatable {{ UniqueField = {SpacetimeDB.BSATN.StringUtil.GenericToString(UniqueField)}, PrimaryKeyField = {SpacetimeDB.BSATN.StringUtil.GenericToString(PrimaryKeyField)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.ValueOption< + int, + SpacetimeDB.BSATN.I32 + > UniqueFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.Enum PrimaryKeyFieldRW = + new(); + + public TestUniqueNotEquatable Read(System.IO.BinaryReader reader) + { + var ___result = new TestUniqueNotEquatable(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, TestUniqueNotEquatable value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("UniqueField", UniqueFieldRW.GetAlgebraicType(registrar)), + new("PrimaryKeyField", PrimaryKeyFieldRW.GetAlgebraicType(registrar)), + } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashUniqueField = UniqueField.GetHashCode(); + var ___hashPrimaryKeyField = PrimaryKeyField.GetHashCode(); + return ___hashUniqueField ^ ___hashPrimaryKeyField; + } + +#nullable enable + public bool Equals(TestUniqueNotEquatable that) + { + var ___eqUniqueField = System.Nullable.Equals(this.UniqueField, that.UniqueField); + var ___eqPrimaryKeyField = this.PrimaryKeyField == that.PrimaryKeyField; + return ___eqUniqueField && ___eqPrimaryKeyField; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as TestUniqueNotEquatable?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(TestUniqueNotEquatable this_, TestUniqueNotEquatable that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(TestUniqueNotEquatable this_, TestUniqueNotEquatable that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // TestUniqueNotEquatable diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10.verified.txt b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10.verified.txt new file mode 100644 index 00000000000..3c87c799228 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Module.net10.verified.txt @@ -0,0 +1,629 @@ +{ + Diagnostics: [ + {/* + [AutoInc] + public float AutoIncField; + ^^^^^^^^^^^^ + +*/ + Message: Field AutoIncField is marked as AutoInc but it has a non-integer type float., + Severity: Error, + Descriptor: { + Id: STDB0002, + Title: AutoInc fields must be of integer type, + MessageFormat: Field {0} is marked as AutoInc but it has a non-integer type {1}., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [AutoInc] + public string IdentityField; + ^^^^^^^^^^^^^ +} +*/ + Message: Field IdentityField is marked as AutoInc but it has a non-integer type string., + Severity: Error, + Descriptor: { + Id: STDB0002, + Title: AutoInc fields must be of integer type, + MessageFormat: Field {0} is marked as AutoInc but it has a non-integer type {1}., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [Unique] + public int? UniqueField; + ^^^^^^^^^^^ + +*/ + Message: Field UniqueField is marked as Unique but it has a type int? which is not an equatable primitive., + Severity: Error, + Descriptor: { + Id: STDB0003, + Title: Unique fields must be equatable, + MessageFormat: Field {0} is marked as Unique but it has a type {1} which is not an equatable primitive., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +[SpacetimeDB.Table] +public partial record TestTableTaggedEnum : SpacetimeDB.TaggedEnum<(int X, int Y)> { } + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +*/ + Message: Table TestTableTaggedEnum is a tagged enum, which is not allowed., + Severity: Error, + Descriptor: { + Id: STDB0006, + Title: Tables cannot be tagged enums, + MessageFormat: Table {0} is a tagged enum, which is not allowed., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [Unique] + public int? UniqueField; + ^^^^^^^^^^^ + +*/ + Message: Field UniqueField is marked as Unique but it has a type int? which is not an equatable primitive., + Severity: Error, + Descriptor: { + Id: STDB0003, + Title: Unique fields must be equatable, + MessageFormat: Field {0} is marked as Unique but it has a type {1} which is not an equatable primitive., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +{ + [SpacetimeDB.Index.BTree(Accessor = "TestUnexpectedColumns", Columns = ["UnexpectedColumn"])] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + public int SelfIndexingColumn; +*/ + Message: Index attribute on a field applies directly to that field, so it doesn't accept the Columns parameter., + Severity: Error, + Descriptor: { + Id: STDB0015, + Title: Index attribute on a field must not specify Columns, + MessageFormat: Index attribute on a field applies directly to that field, so it doesn't accept the Columns parameter., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +[SpacetimeDB.Table] +[SpacetimeDB.Index.BTree(Accessor = "TestIndexWithoutColumns")] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +[SpacetimeDB.Index.BTree(Accessor = "TestIndexWithEmptyColumns", Columns = [])] +*/ + Message: Index attribute doesn't specify columns., + Severity: Error, + Descriptor: { + Id: STDB0004, + Title: Index attribute must specify Columns, + MessageFormat: Index attribute doesn't specify columns., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +[SpacetimeDB.Index.BTree(Accessor = "TestIndexWithoutColumns")] +[SpacetimeDB.Index.BTree(Accessor = "TestIndexWithEmptyColumns", Columns = [])] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +[SpacetimeDB.Index.BTree(Accessor = "TestUnknownColumns", Columns = ["UnknownColumn"])] +*/ + Message: Index attribute doesn't specify columns., + Severity: Error, + Descriptor: { + Id: STDB0004, + Title: Index attribute must specify Columns, + MessageFormat: Index attribute doesn't specify columns., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +[SpacetimeDB.Index.BTree(Accessor = "TestIndexWithEmptyColumns", Columns = [])] +[SpacetimeDB.Index.BTree(Accessor = "TestUnknownColumns", Columns = ["UnknownColumn"])] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +[SpacetimeDB.Index.BTree(Columns = ["SelfIndexingColumn"])] +*/ + Message: Could not find the specified column UnknownColumn in TestIndexIssues., + Severity: Error, + Descriptor: { + Id: STDB0016, + Title: Unknown column, + MessageFormat: Could not find the specified column {0} in {1}., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +[SpacetimeDB.Index.BTree(Accessor = "TestUnknownColumns", Columns = ["UnknownColumn"])] +[SpacetimeDB.Index.BTree(Columns = ["SelfIndexingColumn"])] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +[SpacetimeDB.Index.BTree( +*/ + Message: Index attribute on a table declaration must specify Accessor. Field-level index attributes may omit Accessor and default to the field name., + Severity: Error, + Descriptor: { + Id: STDB0029, + Title: Table-level index attributes must specify Accessor, + MessageFormat: Index attribute on a table declaration must specify Accessor. Field-level index attributes may omit Accessor and default to the field name., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +[SpacetimeDB.Index.BTree(Columns = ["SelfIndexingColumn"])] +[SpacetimeDB.Index.BTree( + ^^^^^^^^^^^^^^^^^^^^^^^^ + Name = "TestCanonicalNameWithoutAccessor", +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Columns = ["SecondaryIndexingColumn"] +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +)] +^ +public partial struct TestIndexIssues +*/ + Message: Index attribute on a table declaration must specify Accessor. Field-level index attributes may omit Accessor and default to the field name., + Severity: Error, + Descriptor: { + Id: STDB0029, + Title: Table-level index attributes must specify Accessor, + MessageFormat: Index attribute on a table declaration must specify Accessor. Field-level index attributes may omit Accessor and default to the field name., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + +[SpacetimeDB.Table( + ^^^^^^^^^^^^^^^^^^ + Accessor = "TestScheduleWithoutPrimaryKey", +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Scheduled = "DummyScheduledReducer", +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ScheduledAt = nameof(ScheduleAtCorrectType) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +)] +^ +[SpacetimeDB.Table( +*/ + Message: TestScheduleWithoutPrimaryKey is a scheduled table but doesn't have a primary key of type `ulong`., + Severity: Error, + Descriptor: { + Id: STDB0014, + Title: Invalid scheduled table declaration, + MessageFormat: {0}, + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +)] +[SpacetimeDB.Table( + ^^^^^^^^^^^^^^^^^^ + Accessor = "TestScheduleWithWrongPrimaryKeyType", +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Scheduled = "DummyScheduledReducer", +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ScheduledAt = nameof(ScheduleAtCorrectType) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +)] +^ +[SpacetimeDB.Table(Accessor = "TestScheduleWithoutScheduleAt", Scheduled = "DummyScheduledReducer")] +*/ + Message: TestScheduleWithWrongPrimaryKeyType is a scheduled table but doesn't have a primary key of type `ulong`., + Severity: Error, + Descriptor: { + Id: STDB0014, + Title: Invalid scheduled table declaration, + MessageFormat: {0}, + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +)] +[SpacetimeDB.Table(Accessor = "TestScheduleWithoutScheduleAt", Scheduled = "DummyScheduledReducer")] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +[SpacetimeDB.Table( +*/ + Message: Could not find the specified column ScheduledAt in TestScheduleIssues., + Severity: Error, + Descriptor: { + Id: STDB0016, + Title: Unknown column, + MessageFormat: Could not find the specified column {0} in {1}., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +[SpacetimeDB.Table(Accessor = "TestScheduleWithoutScheduleAt", Scheduled = "DummyScheduledReducer")] +[SpacetimeDB.Table( + ^^^^^^^^^^^^^^^^^^ + Accessor = "TestScheduleWithWrongScheduleAtType", +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Scheduled = "DummyScheduledReducer", +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ScheduledAt = nameof(ScheduleAtWrongType) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +)] +^ +[SpacetimeDB.Table( +*/ + Message: TestScheduleWithWrongScheduleAtType is a scheduled table but doesn't have a primary key of type `ulong`., + Severity: Error, + Descriptor: { + Id: STDB0014, + Title: Invalid scheduled table declaration, + MessageFormat: {0}, + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* +)] +[SpacetimeDB.Table( + ^^^^^^^^^^^^^^^^^^ + Accessor = "TestScheduleWithMissingScheduleAtField", +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Scheduled = "DummyScheduledReducer", +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ScheduledAt = "MissingField" +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +)] +^ +public partial struct TestScheduleIssues +*/ + Message: Could not find the specified column MissingField in TestScheduleIssues., + Severity: Error, + Descriptor: { + Id: STDB0016, + Title: Unknown column, + MessageFormat: Could not find the specified column {0} in {1}., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + // Invalid: View definition missing Public=true + [SpacetimeDB.View(Accessor = "view_def_no_public")] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + public static List ViewDefNoPublic(ViewContext ctx) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + { +^^^^^ + return new List(); +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + } +^^^^^ + +*/ + Message: View 'ViewDefNoPublic' must have Public = true. Views are always public in SpacetimeDB., + Severity: Error, + Descriptor: { + Id: STDB0025, + Title: Views must be public, + MessageFormat: View '{0}' must have Public = true. Views are always public in SpacetimeDB., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [SpacetimeDB.View(Accessor = "view_def_no_context", Public = true)] + public static List ViewDefNoContext() + ^^ + { +*/ + Message: View method ViewDefNoContext must have a first parameter of type ViewContext or AnonymousViewContext., + Severity: Error, + Descriptor: { + Id: STDB0022, + Title: Views must start with ViewContext or AnonymousViewContext, + MessageFormat: View method {0} must have a first parameter of type ViewContext or AnonymousViewContext., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [SpacetimeDB.View(Accessor = "view_def_wrong_context", Public = true)] + public static List ViewDefWrongContext(ReducerContext ctx) + ^^^^^^^^^^^^^^^^^^^^ + { +*/ + Message: View method ViewDefWrongContext must have a first parameter of type ViewContext or AnonymousViewContext., + Severity: Error, + Descriptor: { + Id: STDB0022, + Title: Views must start with ViewContext or AnonymousViewContext, + MessageFormat: View method {0} must have a first parameter of type ViewContext or AnonymousViewContext., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [SpacetimeDB.View(Accessor = "view_def_wrong_return", Public = true)] + public static Player ViewDefWrongReturn(ViewContext ctx) + ^^^^^^ + { +*/ + Message: View 'ViewDefWrongReturn' must return T?, List, IQuery, or IEnumerable., + Severity: Error, + Descriptor: { + Id: STDB0024, + Title: Views must return T?, List, IQuery, or IEnumerable, + MessageFormat: View '{0}' must return T?, List, IQuery, or IEnumerable., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + Public = true, + PrimaryKey = "MissingIdentity" + ^^^^^^^^^^^^^^^^^ + )] +*/ + Message: View 'ViewPrimaryKeyMissingColumn' declares primary key 'MissingIdentity', but row type 'Player' does not have a field with that source name., + Severity: Error, + Descriptor: { + Id: STDB0037, + Title: View primary key column not found, + MessageFormat: View '{0}' declares primary key '{1}', but row type '{2}' does not have a field with that source name., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + Public = true, + PrimaryKey = "renamed_identity" + ^^^^^^^^^^^^^^^^^^ + )] +*/ + Message: View 'ViewPrimaryKeyUsesWrongSourceName' declares primary key 'renamed_identity', but row type 'ViewPrimaryKeyRenamedRow' does not have a field with that source name., + Severity: Error, + Descriptor: { + Id: STDB0037, + Title: View primary key column not found, + MessageFormat: View '{0}' declares primary key '{1}', but row type '{2}' does not have a field with that source name., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + Public = true, + PrimaryKey = "ExtraPartialIdentity" + ^^^^^^^^^^^^^^^^^^^^^^ + )] +*/ + Message: View 'ViewPrimaryKeyUsesNonBsatnPartialField' declares primary key 'ExtraPartialIdentity', but row type 'ViewPrimaryKeyPartialRow' does not have a field with that source name., + Severity: Error, + Descriptor: { + Id: STDB0037, + Title: View primary key column not found, + MessageFormat: View '{0}' declares primary key '{1}', but row type '{2}' does not have a field with that source name., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + Public = true, + PrimaryKey = "Identity" + ^^^^^^^^^^ + )] +*/ + Message: View 'ViewPrimaryKeyNonEquatableColumn' declares primary key 'Identity', but its type 'NonEquatableViewPrimaryKey' is not supported for view primary keys., + Severity: Error, + Descriptor: { + Id: STDB0038, + Title: View primary key column type is not supported, + MessageFormat: View '{0}' declares primary key '{1}', but its type '{2}' is not supported for view primary keys., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [SpacetimeDB.Reducer] + public static int TestReducerReturnType(ReducerContext ctx) => 0; + ^^^ + +*/ + Message: Reducer method TestReducerReturnType returns int instead of void., + Severity: Error, + Descriptor: { + Id: STDB0001, + Title: [SpacetimeDB.Reducer] methods must return void, + MessageFormat: Reducer method {0} returns {1} instead of void., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [SpacetimeDB.Reducer] + public static void TestReducerWithoutContext() { } + ^^ + +*/ + Message: Reducer method TestReducerWithoutContext does not have a ReducerContext parameter., + Severity: Error, + Descriptor: { + Id: STDB0008, + Title: Reducers must have a first argument of type ReducerContext, + MessageFormat: Reducer method {0} does not have a ReducerContext parameter., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [SpacetimeDB.Reducer] + public static void OnReducerWithReservedPrefix(ReducerContext ctx) { } + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +*/ + Message: Reducer method OnReducerWithReservedPrefix starts with 'On', which is a reserved prefix., + Severity: Error, + Descriptor: { + Id: STDB0010, + Title: Reducer method has a reserved name prefix, + MessageFormat: Reducer method {0} starts with '{1}', which is a reserved prefix., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [SpacetimeDB.Reducer] + public static void __ReducerWithReservedPrefix(ReducerContext ctx) { } + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +} +*/ + Message: Reducer method __ReducerWithReservedPrefix starts with '__', which is a reserved prefix., + Severity: Error, + Descriptor: { + Id: STDB0010, + Title: Reducer method has a reserved name prefix, + MessageFormat: Reducer method {0} starts with '{1}', which is a reserved prefix., + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + { + Location: , + Message: Several reducers are assigned to the same lifecycle kind Init: Reducers.TestDuplicateReducerKind1, Reducers.TestDuplicateReducerKind2, + Severity: Error, + Descriptor: { + Id: STDB0013, + Title: Multiple reducers of the same kind, + MessageFormat: Several reducers are assigned to the same lifecycle kind {0}: {1}, + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + { + Location: , + Message: Reducer with the same export name TestDuplicateReducerName is registered in multiple places: Reducers.TestDuplicateReducerName, Reducers.InAnotherNamespace.TestDuplicateReducerName, + Severity: Error, + Descriptor: { + Id: STDB0007, + Title: Duplicate exports, + MessageFormat: {0} with the same export name {1} is registered in multiple places: {2}, + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + { + Location: , + Message: Table with the same export name TestDuplicateTableName is registered in multiple places: global::TestDuplicateTableName, global::InAnotherNamespace.TestDuplicateTableName, + Severity: Error, + Descriptor: { + Id: STDB0007, + Title: Duplicate exports, + MessageFormat: {0} with the same export name {1} is registered in multiple places: {2}, + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + { + Location: , + Message: TableReadOnly with the same export name TestDuplicateTableNameReadOnly is registered in multiple places: global::TestDuplicateTableName, global::InAnotherNamespace.TestDuplicateTableName, + Severity: Error, + Descriptor: { + Id: STDB0007, + Title: Duplicate exports, + MessageFormat: {0} with the same export name {1} is registered in multiple places: {2}, + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [SpacetimeDB.ClientVisibilityFilter] + private Filter MY_FILTER = new Filter.Sql("SELECT * FROM TestAutoIncNotInteger"); + ^^^^^^^^^ + +*/ + Message: Field MY_FILTER is marked as [ClientVisibilityFilter] but it is not public static readonly, + Severity: Error, + Descriptor: { + Id: STDB0018, + Title: ClientVisibilityFilters must be public static readonly, + MessageFormat: Field {0} is marked as [ClientVisibilityFilter] but it is not public static readonly, + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [SpacetimeDB.ClientVisibilityFilter] + public static Filter MY_SECOND_FILTER = new Filter.Sql("SELECT * FROM TestAutoIncNotInteger"); + ^^^^^^^^^^^^^^^^ + +*/ + Message: Field MY_SECOND_FILTER is marked as [ClientVisibilityFilter] but it is not public static readonly, + Severity: Error, + Descriptor: { + Id: STDB0018, + Title: ClientVisibilityFilters must be public static readonly, + MessageFormat: Field {0} is marked as [ClientVisibilityFilter] but it is not public static readonly, + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + }, + {/* + [SpacetimeDB.ClientVisibilityFilter] + public static readonly string MY_THIRD_FILTER = "SELECT * FROM TestAutoIncNotInteger"; + ^^^^^^^^^^^^^^^ + +*/ + Message: Field MY_THIRD_FILTER is marked as ClientVisibilityFilter but it has type string which is not SpacetimeDB.Filter, + Severity: Error, + Descriptor: { + Id: STDB0017, + Title: ClientVisibilityFilters must be Filters, + MessageFormat: Field {0} is marked as ClientVisibilityFilter but it has type {1} which is not SpacetimeDB.Filter, + Category: SpacetimeDB, + DefaultSeverity: Error, + IsEnabledByDefault: true + } + } + ] +} \ No newline at end of file diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#MyStruct.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#MyStruct.verified.cs index ab145aab509..41cd8c2b038 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#MyStruct.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#MyStruct.verified.cs @@ -44,7 +44,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar registrar.RegisterType(_ => new SpacetimeDB.BSATN.AlgebraicType.Product( new SpacetimeDB.BSATN.AggregateElement[] { - new("x", xRW.GetAlgebraicType(registrar)) + new("x", xRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#NonEquatableViewPrimaryKey.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#NonEquatableViewPrimaryKey.verified.cs index b4d6dd416f9..9bbc641a529 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#NonEquatableViewPrimaryKey.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#NonEquatableViewPrimaryKey.verified.cs @@ -47,7 +47,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar _ => new SpacetimeDB.BSATN.AlgebraicType.Product( new SpacetimeDB.BSATN.AggregateElement[] { - new("Value", ValueRW.GetAlgebraicType(registrar)) + new("Value", ValueRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#NonEquatableViewPrimaryKeyRow.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#NonEquatableViewPrimaryKeyRow.verified.cs index fad8680539f..b9c056ee796 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#NonEquatableViewPrimaryKeyRow.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#NonEquatableViewPrimaryKeyRow.verified.cs @@ -48,7 +48,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar _ => new SpacetimeDB.BSATN.AlgebraicType.Product( new SpacetimeDB.BSATN.AggregateElement[] { - new("Identity", IdentityRW.GetAlgebraicType(registrar)) + new("Identity", IdentityRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTaggedEnumField.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTaggedEnumField.verified.cs index 9f0584e348e..780ddd42135 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTaggedEnumField.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTaggedEnumField.verified.cs @@ -27,10 +27,9 @@ public TestTaggedEnumField Read(System.IO.BinaryReader reader) { 0 => new X(XRW.Read(reader)), 1 => new Y(YRW.Read(reader)), - _ - => throw new System.InvalidOperationException( - "Invalid tag value, this state should be unreachable." - ) + _ => throw new System.InvalidOperationException( + "Invalid tag value, this state should be unreachable." + ), }; } @@ -57,7 +56,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new SpacetimeDB.BSATN.AggregateElement[] { new("X", XRW.GetAlgebraicType(registrar)), - new("Y", YRW.GetAlgebraicType(registrar)) + new("Y", YRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTaggedEnumInlineTuple.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTaggedEnumInlineTuple.verified.cs index 761bdacb92e..4a7c01f40f2 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTaggedEnumInlineTuple.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTaggedEnumInlineTuple.verified.cs @@ -19,10 +19,9 @@ public TestTaggedEnumInlineTuple Read(System.IO.BinaryReader reader) return reader.ReadByte() switch { 0 => new Item1(Item1RW.Read(reader)), - _ - => throw new System.InvalidOperationException( - "Invalid tag value, this state should be unreachable." - ) + _ => throw new System.InvalidOperationException( + "Invalid tag value, this state should be unreachable." + ), }; } @@ -44,7 +43,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar _ => new SpacetimeDB.BSATN.AlgebraicType.Sum( new SpacetimeDB.BSATN.AggregateElement[] { - new("Item1", Item1RW.GetAlgebraicType(registrar)) + new("Item1", Item1RW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTypeParams_T_.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTypeParams_T_.verified.cs index 8558fa804b3..abbf7b396af 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTypeParams_T_.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestTypeParams_T_.verified.cs @@ -47,7 +47,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar _ => new SpacetimeDB.BSATN.AlgebraicType.Product( new SpacetimeDB.BSATN.AggregateElement[] { - new("Field", FieldRW.GetAlgebraicType(registrar)) + new("Field", FieldRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestUnsupportedType.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestUnsupportedType.verified.cs index 83e1269067f..afa81298881 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestUnsupportedType.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#TestUnsupportedType.verified.cs @@ -67,7 +67,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar UnsupportedSystemTypeRW.GetAlgebraicType(registrar) ), new("UnresolvedType", UnresolvedTypeRW.GetAlgebraicType(registrar)), - new("UnsupportedEnum", UnsupportedEnumRW.GetAlgebraicType(registrar)) + new("UnsupportedEnum", UnsupportedEnumRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#ViewPrimaryKeyPartialRow.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#ViewPrimaryKeyPartialRow.verified.cs index 4ce530acedf..657b472a823 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#ViewPrimaryKeyPartialRow.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#ViewPrimaryKeyPartialRow.verified.cs @@ -47,7 +47,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar _ => new SpacetimeDB.BSATN.AlgebraicType.Product( new SpacetimeDB.BSATN.AggregateElement[] { - new("DeclaredIdentity", DeclaredIdentityRW.GetAlgebraicType(registrar)) + new("DeclaredIdentity", DeclaredIdentityRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#ViewPrimaryKeyRenamedRow.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#ViewPrimaryKeyRenamedRow.verified.cs index bc6c6faed44..7478b6d8c3f 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#ViewPrimaryKeyRenamedRow.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/diag/snapshots/Type#ViewPrimaryKeyRenamedRow.verified.cs @@ -47,7 +47,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar _ => new SpacetimeDB.BSATN.AlgebraicType.Product( new SpacetimeDB.BSATN.AggregateElement[] { - new("RenamedIdentity", RenamedIdentityRW.GetAlgebraicType(registrar)) + new("RenamedIdentity", RenamedIdentityRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#DemoTable.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#DemoTable.verified.cs index c43a88b3f68..07460ecb9af 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#DemoTable.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#DemoTable.verified.cs @@ -48,7 +48,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new SpacetimeDB.BSATN.AggregateElement[] { new("Id", IdRW.GetAlgebraicType(registrar)), - new("Value", ValueRW.GetAlgebraicType(registrar)) + new("Value", ValueRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#FFI.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#FFI.verified.cs index ad729dadac1..34632653434 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#FFI.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#FFI.verified.cs @@ -1,20 +1,28 @@ //HintName: FFI.cs // #nullable enable -// The runtime already defines SpacetimeDB.Internal.LocalReadOnly in Runtime\Internal\Module.cs as an empty partial type. -// This is needed so every module build doesn't generate a full LocalReadOnly type, but just adds on to the existing. -// We extend it here with generated table accessors, and just need to suppress the duplicate-type warning. +// .NET 8 generates a module-local LocalReadOnly which shadows the runtime shell. #pragma warning disable CS0436 #pragma warning disable STDB_UNSTABLE +#if NET10_0_OR_GREATER +global using SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31; +#endif using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal = SpacetimeDB.Internal; using TxContext = SpacetimeDB.Internal.TxContext; +#if NET10_0_OR_GREATER +[assembly: global::SpacetimeDB.ModuleDescriptorAttribute( + typeof(global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor) +)] + +#endif namespace SpacetimeDB { +#if !NET10_0_OR_GREATER public readonly struct DemoTableCols { public readonly global::SpacetimeDB.Col Id; @@ -46,9 +54,11 @@ public readonly partial struct QueryBuilder > DemoTable() => new("DemoTable", new DemoTableCols("DemoTable"), new DemoTableIxCols("DemoTable")); } +#endif - public static class Handlers { } + internal static class Handlers { } +#if !NET10_0_OR_GREATER public sealed record ReducerContext : DbContext, Internal.IReducerContext { public global::SpacetimeDB.ModuleEnvironment Env => default; @@ -302,7 +312,216 @@ public sealed record AnonymousViewContext internal AnonymousViewContext(Internal.LocalReadOnly db) : base(db) { } } +#endif +} + +#if NET10_0_OR_GREATER +namespace SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31 +{ + public static partial class AssemblyDescriptor + { + public const string? CaseConversionPolicy = "SnakeCase"; + public const string RootOnlyDeclarations = ""; + public const int ReducerCount = 1; + public const int ProcedureCount = 1; + public const int HttpHandlerCount = 0; + public const int ViewCount = 1; + public const int AnonymousViewCount = 0; + + public static global::SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink error + ) => + global::ModuleRegistration.CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink result_sink + ) => + global::ModuleRegistration.CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource request, + global::SpacetimeDB.Internal.BytesSource request_body, + global::SpacetimeDB.Internal.BytesSink response_sink, + global::SpacetimeDB.Internal.BytesSink response_body_sink + ) => + global::ModuleRegistration.CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => + global::ModuleRegistration.CallLocalView( + id, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => global::ModuleRegistration.CallLocalAnonymousView(id, args, sink); + + public static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) => global::ModuleRegistration.Register(builder, httpBuilder); + + public readonly struct Tables + { + public global::SpacetimeDB.Internal.TableHandles.DemoTable DemoTable => new(); + } + + public readonly struct ReadOnlyTables + { + public global::SpacetimeDB.Internal.ViewHandles.DemoTableReadOnly DemoTable => new(); + } + + public readonly partial struct Queries { } + } + + public static class LocalTableExtensions + { + extension(global::SpacetimeDB.Local db) + { + public global::SpacetimeDB.Internal.TableHandles.DemoTable DemoTable => new(); + } + } + + public static class ReadOnlyTableExtensions + { + extension(global::SpacetimeDB.Internal.LocalReadOnly db) + { + public global::SpacetimeDB.Internal.ViewHandles.DemoTableReadOnly DemoTable => new(); + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) { } + } + + public readonly struct DemoTableCols + { + public readonly global::SpacetimeDB.Col Id; + public readonly global::SpacetimeDB.Col Value; + + internal DemoTableCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "Id"); + Value = new global::SpacetimeDB.Col(tableName, "Value"); + } + } + + public readonly struct DemoTableIxCols + { + public readonly global::SpacetimeDB.IxCol Id; + + internal DemoTableIxCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "Id"); + } + } + + public static partial class AssemblyDescriptor + { + private static class DemoTableSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "DemoTable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static DemoTableSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::DemoTable, + DemoTableCols, + DemoTableIxCols + > DemoTable() + { + var tableName = DemoTableSqlNameCache.Name; + return new(tableName, new DemoTableCols(tableName), new DemoTableIxCols(tableName)); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::DemoTable, + DemoTableCols, + DemoTableIxCols + > DemoTable() => new AssemblyDescriptor.Queries().DemoTable(); + } + } } +#endif namespace SpacetimeDB.Internal.TableHandles { @@ -336,14 +555,14 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "DemoTable_Id_idx_btree", AccessorName: "ById", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< DemoTable, global::DemoTable - >.MakeUniqueConstraint(0) + >.MakeUniqueConstraint(0), ], Sequences: [], TableType: SpacetimeDB.Internal.TableType.User, @@ -376,7 +595,12 @@ public ulong Clear() => global::SpacetimeDB.Internal.ITableView.DoClear(); public sealed class IdUniqueIndex - : UniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + DemoTable, + global::DemoTable, + int, + SpacetimeDB.BSATN.I32 + > { internal IdUniqueIndex() : base("DemoTable_Id_idx_btree") { } @@ -510,6 +734,7 @@ internal ByIdIndex() } } +#if !NET10_0_OR_GREATER namespace SpacetimeDB.Internal { public sealed partial class LocalReadOnly @@ -517,6 +742,7 @@ public sealed partial class LocalReadOnly public global::SpacetimeDB.Internal.ViewHandles.DemoTableReadOnly DemoTable => new(); } } +#endif static class ModuleRegistration { @@ -585,8 +811,11 @@ public static List ToListOrEmpty(T? value) // Prevent trimming of FFI exports that are invoked from C and not visible to C# trimmer. [DynamicDependency(DynamicallyAccessedMemberTypes.PublicMethods, typeof(ModuleRegistration))] #endif - public static void Main() + public static void Main() => Initialize(); + + internal static void Initialize() { +#if !NET10_0_OR_GREATER SpacetimeDB.Internal.Module.SetReducerContextConstructor( (identity, connectionId, random, time) => new SpacetimeDB.ReducerContext(identity, connectionId, random, time) @@ -597,48 +826,61 @@ public static void Main() new SpacetimeDB.Internal.LocalReadOnly() ) ); - SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor( - () => new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly()) + SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor(() => + new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly()) ); SpacetimeDB.Internal.Module.SetProcedureContextConstructor( (identity, connectionId, random, time) => new SpacetimeDB.ProcedureContext(identity, connectionId, random, time) ); - SpacetimeDB.Internal.Module.SetCaseConversionPolicy( - SpacetimeDB.CaseConversionPolicy.SnakeCase - ); - SpacetimeDB.Internal.Module.RegisterExplicitTableName("DemoTable", "canonical_table"); - SpacetimeDB.Internal.Module.RegisterExplicitFunctionName( - "DemoReducer", - "canonical_reducer" + SpacetimeDB.Internal.Module.SetHandlerContextConstructor( + (random, time) => new SpacetimeDB.HandlerContext(random, time) ); - SpacetimeDB.Internal.Module.RegisterExplicitFunctionName( - "DemoProcedure", - "canonical_procedure" +#endif + +#if NET10_0_OR_GREATER + global::SpacetimeDB.Internal.Module.InstallNamespaces( + new global::SpacetimeDB.Internal.NamespaceRegistry( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + global::SpacetimeDB.CaseConversionPolicy.SnakeCase, + new (string, string, string?, global::SpacetimeDB.CaseConversionPolicy)[] { } + ) ); - SpacetimeDB.Internal.Module.RegisterExplicitFunctionName("demo_view", "canonical_view"); - SpacetimeDB.Internal.Module.RegisterExplicitIndexName( - "DemoTable_Id_idx_btree", - "canonical_index" + global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.Register( + global::SpacetimeDB.Internal.Module.RootBuilder ); +#else + Register(global::SpacetimeDB.Internal.Module.RootBuilder); +#endif + } - SpacetimeDB.Internal.Module.SetHandlerContextConstructor( - (random, time) => new SpacetimeDB.HandlerContext(random, time) - ); + internal static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) + { + // HTTP routes retain the root routing API even for mounted modules. + httpBuilder ??= builder; + builder.SetCaseConversionPolicy(SpacetimeDB.CaseConversionPolicy.SnakeCase); + builder.RegisterExplicitTableName("DemoTable", "canonical_table"); + builder.RegisterExplicitFunctionName("DemoReducer", "canonical_reducer"); + builder.RegisterExplicitFunctionName("DemoProcedure", "canonical_procedure"); + builder.RegisterExplicitFunctionName("demo_view", "canonical_view"); + builder.RegisterExplicitIndexName("DemoTable_Id_idx_btree", "canonical_index"); var __memoryStream = new MemoryStream(); var __writer = new BinaryWriter(__memoryStream); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterProcedure(); + builder.RegisterReducer(); + builder.RegisterProcedure(); // IMPORTANT: The order in which we register views matters. // It must correspond to the order in which we call `GenerateDispatcherClass`. // See the comment on `GenerateDispatcherClass` for more explanation. - SpacetimeDB.Internal.Module.RegisterView(); + builder.RegisterView(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::DemoTable, - SpacetimeDB.Internal.TableHandles.DemoTable + global::SpacetimeDB.Internal.TableHandles.DemoTable >(); } @@ -772,26 +1014,92 @@ public static SpacetimeDB.Internal.Errno __call_reducer__( SpacetimeDB.Timestamp timestamp, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink error + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ReducerCount + ) + return global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.CallLocalReducer( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + localId -= global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ReducerCount; + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); +#else + return CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error ) => id switch { - 0 - => __call_reducer_0( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - _ - => SpacetimeDB.Internal.Module.WriteReducerError( - error, - new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") - ) + 0 => __call_reducer_0( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + _ => SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -808,27 +1116,87 @@ public static SpacetimeDB.Internal.Errno __call_procedure__( SpacetimeDB.Timestamp timestamp, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink result_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ProcedureCount + ) + return global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.CallLocalProcedure( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + localId -= global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ProcedureCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); +#else + return CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink ) => id switch { - 0 - => __call_procedure_0( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - result_sink - ), - _ - => throw new System.ArgumentOutOfRangeException( - nameof(id), - id, - "Unknown procedure id" - ) + 0 => __call_procedure_0( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ), + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown procedure id" + ), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -841,15 +1209,64 @@ public static SpacetimeDB.Internal.Errno __call_http_handler__( SpacetimeDB.Internal.BytesSource request_body, SpacetimeDB.Internal.BytesSink response_sink, SpacetimeDB.Internal.BytesSink response_body_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .HttpHandlerCount + ) + return global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.CallLocalHttpHandler( + localId, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + localId -= global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .HttpHandlerCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); +#else + return CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource request, + SpacetimeDB.Internal.BytesSource request_body, + SpacetimeDB.Internal.BytesSink response_sink, + SpacetimeDB.Internal.BytesSink response_body_sink ) => id switch { - _ - => throw new System.ArgumentOutOfRangeException( - nameof(id), - id, - "Unknown HTTP handler id" - ) + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown HTTP handler id" + ), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -863,11 +1280,56 @@ public static SpacetimeDB.Internal.Errno __call_view__( ulong sender_3, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ViewCount + ) + return global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.CallLocalView( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + localId -= global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ViewCount; + return UnknownViewId(id); +#else + return CallLocalView(id, sender_0, sender_1, sender_2, sender_3, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink ) => id switch { 0 => __call_view_0(sender_0, sender_1, sender_2, sender_3, args, sink), - _ => UnknownViewId(id) + _ => UnknownViewId(id), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -877,10 +1339,47 @@ public static SpacetimeDB.Internal.Errno __call_view_anon__( int id, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownAnonymousViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .AnonymousViewCount + ) + return global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.CallLocalAnonymousView( + localId, + args, + sink + ); + localId -= global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .AnonymousViewCount; + return UnknownAnonymousViewId(id); +#else + return CallLocalAnonymousView(id, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink ) => id switch { - _ => UnknownAnonymousViewId(id) + _ => UnknownAnonymousViewId(id), }; private static SpacetimeDB.Internal.Errno UnknownViewId(int id) diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#Reducers.DemoProcedure.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#Reducers.DemoProcedure.verified.cs index ce3fd066748..72f24562fe9 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#Reducers.DemoProcedure.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#Reducers.DemoProcedure.verified.cs @@ -11,7 +11,7 @@ public static void VolatileNonatomicScheduleImmediateDemoProcedure() using var writer = new BinaryWriter(stream); SpacetimeDB.Internal.ProcedureExtensions.VolatileNonatomicScheduleImmediate( - nameof(DemoProcedure), + "canonical_procedure", stream ); } diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#Reducers.DemoReducer.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#Reducers.DemoReducer.verified.cs index 85af7c9566c..52c920a182c 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#Reducers.DemoReducer.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module#Reducers.DemoReducer.verified.cs @@ -11,7 +11,7 @@ public static void VolatileNonatomicScheduleImmediateDemoReducer(int value) using var writer = new BinaryWriter(stream); new SpacetimeDB.BSATN.I32().Write(writer, value); SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( - nameof(DemoReducer), + "canonical_reducer", stream ); } diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#DemoTable.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#DemoTable.verified.cs new file mode 100644 index 00000000000..07460ecb9af --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#DemoTable.verified.cs @@ -0,0 +1,107 @@ +//HintName: DemoTable.cs +// +#nullable enable + +partial struct DemoTable : System.IEquatable, SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + Id = BSATN.IdRW.Read(reader); + Value = BSATN.ValueRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.IdRW.Write(writer, Id); + BSATN.ValueRW.Write(writer, Value); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"DemoTable {{ Id = {SpacetimeDB.BSATN.StringUtil.GenericToString(Id)}, Value = {SpacetimeDB.BSATN.StringUtil.GenericToString(Value)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.I32 IdRW = new(); + internal static readonly SpacetimeDB.BSATN.I32 ValueRW = new(); + + public DemoTable Read(System.IO.BinaryReader reader) + { + var ___result = new DemoTable(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, DemoTable value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType(_ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("Id", IdRW.GetAlgebraicType(registrar)), + new("Value", ValueRW.GetAlgebraicType(registrar)), + } + )); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashId = Id.GetHashCode(); + var ___hashValue = Value.GetHashCode(); + return ___hashId ^ ___hashValue; + } + +#nullable enable + public bool Equals(DemoTable that) + { + var ___eqId = this.Id.Equals(that.Id); + var ___eqValue = this.Value.Equals(that.Value); + return ___eqId && ___eqValue; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as DemoTable?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(DemoTable this_, DemoTable that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(DemoTable this_, DemoTable that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // DemoTable diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#FFI.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#FFI.verified.cs new file mode 100644 index 00000000000..71c39126665 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#FFI.verified.cs @@ -0,0 +1,1460 @@ +//HintName: FFI.cs +// +#nullable enable +// .NET 8 generates a module-local LocalReadOnly which shadows the runtime shell. +#pragma warning disable CS0436 +#pragma warning disable STDB_UNSTABLE + +#if NET10_0_OR_GREATER +global using SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31; +#endif +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Internal = SpacetimeDB.Internal; +using TxContext = SpacetimeDB.Internal.TxContext; +#if NET10_0_OR_GREATER +[assembly: global::SpacetimeDB.ModuleDescriptorAttribute( + typeof(global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor) +)] + +#endif + +namespace SpacetimeDB +{ +#if !NET10_0_OR_GREATER + public readonly struct DemoTableCols + { + public readonly global::SpacetimeDB.Col Id; + public readonly global::SpacetimeDB.Col Value; + + internal DemoTableCols(string tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "Id"); + Value = new global::SpacetimeDB.Col(tableName, "Value"); + } + } + + public readonly struct DemoTableIxCols + { + public readonly global::SpacetimeDB.IxCol Id; + + internal DemoTableIxCols(string tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "Id"); + } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::DemoTable, + DemoTableCols, + DemoTableIxCols + > DemoTable() => + new("DemoTable", new DemoTableCols("DemoTable"), new DemoTableIxCols("DemoTable")); + } +#endif + + internal static class Handlers { } + +#if !NET10_0_OR_GREATER + public sealed record ReducerContext : DbContext, Internal.IReducerContext + { + public global::SpacetimeDB.ModuleEnvironment Env => default; + public readonly Identity Sender; + public readonly ConnectionId? ConnectionId; + public readonly Random Rng; + public readonly Timestamp Timestamp; + public readonly AuthCtx SenderAuth; + + // **Note:** must be 0..=u32::MAX + internal int CounterUuid; + public Identity DatabaseIdentity => Internal.IReducerContext.GetDatabaseIdentity(); + + // We keep this property for compatibility with existing module code. + [global::System.Obsolete( + "ReducerContext.Identity is deprecated. Use DatabaseIdentity instead." + )] + public Identity Identity => DatabaseIdentity; + + internal ReducerContext( + Identity identity, + ConnectionId? connectionId, + Random random, + Timestamp time, + AuthCtx? senderAuth = null + ) + { + Sender = identity; + ConnectionId = connectionId; + Rng = random; + Timestamp = time; + SenderAuth = senderAuth ?? AuthCtx.BuildFromSystemTables(connectionId, identity); + CounterUuid = 0; + } + + /// + /// Create a new random `v4` using the built-in RNG. + /// + /// + /// This method fills the random bytes using the context RNG. + /// + /// + /// + /// var uuid = ctx.NewUuidV4(); + /// Log.Info(uuid); + /// + /// + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + /// + /// Create a new sortable `v7` using the built-in RNG, monotonic counter, + /// and timestamp. + /// + /// + /// A newly generated `v7` that is monotonically ordered + /// and suitable for use as a primary key or for ordered storage. + /// + /// + /// Thrown if generation fails. + /// + /// + /// + /// [SpacetimeDB.Reducer] + /// public static Guid GenerateUuidV7(ReducerContext ctx) + /// { + /// Guid uuid = ctx.NewUuidV7(); + /// Log.Info(uuid); + /// } + /// + /// + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } + } + + public sealed partial class ProcedureContext : global::SpacetimeDB.ProcedureContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + private readonly Local _db = new(); + + internal ProcedureContext( + Identity identity, + ConnectionId? connectionId, + Random random, + Timestamp time + ) + : base(identity, connectionId, random, time) { } + + protected override global::SpacetimeDB.LocalBase CreateLocal() => _db; + + protected override global::SpacetimeDB.ProcedureTxContextBase CreateTxContext( + Internal.TxContext inner + ) => _cached ??= new ProcedureTxContext(inner); + + private ProcedureTxContext? _cached; + + public Local Db => _db; + + public TResult WithTx(Func body) => + base.WithTx(tx => body((ProcedureTxContext)tx)); + + public TxOutcome TryWithTx( + Func> body + ) + where TError : Exception => base.TryWithTx(tx => body((ProcedureTxContext)tx)); + + /// + /// Create a new random `v4` using the built-in RNG. + /// + /// + /// This method fills the random bytes using the context RNG. + /// + /// + /// + /// var uuid = ctx.NewUuidV4(); + /// Log.Info(uuid); + /// + /// + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + /// + /// Create a new sortable `v7` using the built-in RNG, monotonic counter, + /// and timestamp. + /// + /// + /// A newly generated `v7` that is monotonically ordered + /// and suitable for use as a primary key or for ordered storage. + /// + /// + /// Thrown if UUID generation fails. + /// + /// + /// + /// [SpacetimeDB.Procedure] + /// public static Guid GenerateUuidV7(ReducerContext ctx) + /// { + /// Guid uuid = ctx.NewUuidV7(); + /// Log.Info(uuid); + /// } + /// + /// + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } + } + + public sealed partial class HandlerContext : global::SpacetimeDB.HandlerContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + private readonly Local _db = new(); + + internal HandlerContext(Random random, Timestamp time) + : base(random, time) { } + + protected override global::SpacetimeDB.LocalBase CreateLocal() => _db; + + protected override global::SpacetimeDB.HandlerTxContextBase CreateTxContext( + Internal.TxContext inner + ) => _cached ??= new HandlerTxContext(inner); + + private HandlerTxContext? _cached; + + [Experimental("STDB_UNSTABLE")] + public TResult WithTx(Func body) => + base.WithTx(tx => body((HandlerTxContext)tx)); + + [Experimental("STDB_UNSTABLE")] + public TxOutcome TryWithTx( + Func> body + ) + where TError : Exception => base.TryWithTx(tx => body((HandlerTxContext)tx)); + + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } + } + + public sealed class ProcedureTxContext : global::SpacetimeDB.ProcedureTxContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + + internal ProcedureTxContext(Internal.TxContext inner) + : base(inner) { } + + public new Local Db => (Local)base.Db; + } + + [Experimental("STDB_UNSTABLE")] + public sealed class HandlerTxContext : global::SpacetimeDB.HandlerTxContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + + internal HandlerTxContext(Internal.TxContext inner) + : base(inner) { } + + public new Local Db => (Local)base.Db; + } + + public sealed class Local : global::SpacetimeDB.LocalBase + { + public global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.TableHandles.DemoTable DemoTable => + new(); + } + + public sealed record ViewContext : DbContext, Internal.IViewContext + { + public Identity Sender { get; } + + public global::SpacetimeDB.ModuleEnvironment Env => default; + public QueryBuilder From => default; + + internal ViewContext(Identity sender, Internal.LocalReadOnly db) + : base(db) + { + Sender = sender; + } + } + + public sealed record AnonymousViewContext + : DbContext, + Internal.IAnonymousViewContext + { + public global::SpacetimeDB.ModuleEnvironment Env => default; + public QueryBuilder From => default; + + internal AnonymousViewContext(Internal.LocalReadOnly db) + : base(db) { } + } +#endif +} + +#if NET10_0_OR_GREATER +namespace SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31 +{ + public static partial class AssemblyDescriptor + { + public const string? CaseConversionPolicy = "SnakeCase"; + public const string RootOnlyDeclarations = ""; + public const int ReducerCount = 1; + public const int ProcedureCount = 1; + public const int HttpHandlerCount = 0; + public const int ViewCount = 1; + public const int AnonymousViewCount = 0; + + public static global::SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink error + ) => + global::ModuleRegistration.CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink result_sink + ) => + global::ModuleRegistration.CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource request, + global::SpacetimeDB.Internal.BytesSource request_body, + global::SpacetimeDB.Internal.BytesSink response_sink, + global::SpacetimeDB.Internal.BytesSink response_body_sink + ) => + global::ModuleRegistration.CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => + global::ModuleRegistration.CallLocalView( + id, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => global::ModuleRegistration.CallLocalAnonymousView(id, args, sink); + + public static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) => global::ModuleRegistration.Register(builder, httpBuilder); + + public readonly struct Tables + { + public global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.TableHandles.DemoTable DemoTable => + new(); + } + + public readonly struct ReadOnlyTables + { + public global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.ViewHandles.DemoTableReadOnly DemoTable => + new(); + } + + public readonly partial struct Queries { } + } + + public static class LocalTableExtensions + { + extension(global::SpacetimeDB.Local db) + { + public global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.TableHandles.DemoTable DemoTable => + new(); + } + } + + public static class ReadOnlyTableExtensions + { + extension(global::SpacetimeDB.Internal.LocalReadOnly db) + { + public global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.ViewHandles.DemoTableReadOnly DemoTable => + new(); + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) { } + } + + public readonly struct DemoTableCols + { + public readonly global::SpacetimeDB.Col Id; + public readonly global::SpacetimeDB.Col Value; + + internal DemoTableCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "Id"); + Value = new global::SpacetimeDB.Col(tableName, "Value"); + } + } + + public readonly struct DemoTableIxCols + { + public readonly global::SpacetimeDB.IxCol Id; + + internal DemoTableIxCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "Id"); + } + } + + public static partial class AssemblyDescriptor + { + private static class DemoTableSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "DemoTable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static DemoTableSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::DemoTable, + DemoTableCols, + DemoTableIxCols + > DemoTable() + { + var tableName = DemoTableSqlNameCache.Name; + return new(tableName, new DemoTableCols(tableName), new DemoTableIxCols(tableName)); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::DemoTable, + DemoTableCols, + DemoTableIxCols + > DemoTable() => new AssemblyDescriptor.Queries().DemoTable(); + } + } +} +#endif + +namespace SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.TableHandles +{ + public readonly struct DemoTable + : global::SpacetimeDB.Internal.ITableView + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "DemoTable" + ); + + public static global::DemoTable ReadGenFields( + System.IO.BinaryReader reader, + global::DemoTable row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(DemoTable), + ProductTypeRef: (uint) + new global::DemoTable.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [0], + Indexes: + [ + new( + SourceName: "DemoTable_Id_idx_btree", + AccessorName: "Id", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + new( + SourceName: "DemoTable_Id_idx_btree", + AccessorName: "ById", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + DemoTable, + global::DemoTable + >.MakeUniqueConstraint(0), + ], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Public, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView.DoIter(); + + public global::DemoTable Insert(global::DemoTable row) => + global::SpacetimeDB.Internal.ITableView.DoInsert(row); + + public bool Delete(global::DemoTable row) => + global::SpacetimeDB.Internal.ITableView.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView.DoClear(); + + public sealed class IdUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + DemoTable, + global::DemoTable, + int, + SpacetimeDB.BSATN.I32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "DemoTable_Id_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdUniqueIndex() { } + + internal IdUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::DemoTable? Find(int key) => FindSingle(key); + + public global::DemoTable Update(global::DemoTable row) => DoUpdate(row); + } + + private static IdUniqueIndex? __Id; + public IdUniqueIndex Id => __Id ??= new(); + + public sealed class ByIdIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "DemoTable_Id_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static ByIdIndex() { } + + public IEnumerable Filter(int Id) => + DoFilter(new SpacetimeDB.Internal.BTreeIndexBounds(Id)); + + public ulong Delete(int Id) => + DoDelete(new SpacetimeDB.Internal.BTreeIndexBounds(Id)); + + public IEnumerable Filter(global::SpacetimeDB.Bound Id) => + DoFilter(new SpacetimeDB.Internal.BTreeIndexBounds(Id)); + + public ulong Delete(global::SpacetimeDB.Bound Id) => + DoDelete(new SpacetimeDB.Internal.BTreeIndexBounds(Id)); + } + + private static ByIdIndex? __ById; + public ByIdIndex ById => __ById ??= new(); + } +} + +sealed class demo_viewViewDispatcher : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "demo_view", + Index: 0, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.List().GetAlgebraicType( + registrar + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Reducers.DemoView((SpacetimeDB.ViewContext)ctx); + var listSerializer = new SpacetimeDB.BSATN.List(); + var listValue = global::System.Linq.Enumerable.ToList(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'demo_view': " + e); + throw; + } + } +} + +namespace SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.ViewHandles +{ + public sealed class DemoTableReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "DemoTable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static DemoTableReadOnly() { } + + internal DemoTableReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class IdIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.ViewHandles.DemoTableReadOnly, + global::DemoTable, + int, + SpacetimeDB.BSATN.I32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "DemoTable_Id_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdIndex() { } + + internal IdIndex() + : base(__resolvedName) { } + + public global::DemoTable? Find(int key) => FindSingle(key); + } + + private static IdIndex? __Id; + public IdIndex Id => __Id ??= new(); + + public sealed class ByIdIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "DemoTable_Id_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static ByIdIndex() { } + + internal ByIdIndex() + : base(__resolvedName) { } + + public IEnumerable Filter(int Id) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + Id + ) + ); + + public IEnumerable Filter(global::SpacetimeDB.Bound Id) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + Id + ) + ); + } + + private static ByIdIndex? __ById; + public ByIdIndex ById => __ById ??= new(); + } +} + +#if !NET10_0_OR_GREATER +namespace SpacetimeDB.Internal +{ + public sealed partial class LocalReadOnly + { + public global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.ViewHandles.DemoTableReadOnly DemoTable => + new(); + } +} +#endif + +static class ModuleRegistration +{ + // Module host calls are single-threaded in Wasm today, so the generated + // entrypoints reuse buffers across calls to avoid per-invocation allocation. + private static byte[] reducerArgsBuffer = new byte[0x10_000]; + private static byte[] procedureArgsBuffer = new byte[0x10_000]; + private static byte[] httpRequestBuffer = new byte[0x10_000]; + private static byte[] httpRequestBodyBuffer = new byte[0x10_000]; + private static byte[] viewArgsBuffer = new byte[0x10_000]; + private static byte[] anonymousViewArgsBuffer = new byte[0x10_000]; + + sealed class DemoReducer : SpacetimeDB.Internal.IReducer + { + private static readonly SpacetimeDB.BSATN.I32 valueRW = new(); + + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(DemoReducer), + Params: [new("value", valueRW.GetAlgebraicType(registrar))], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Reducers.DemoReducer((SpacetimeDB.ReducerContext)ctx, valueRW.Read(reader)); + } + } + + sealed class DemoProcedure : SpacetimeDB.Internal.IProcedure + { + public SpacetimeDB.Internal.RawProcedureDefV10 MakeProcedureDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(DemoProcedure), + Params: [], + ReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable + ); + + public static byte[] Invoke(BinaryReader reader, SpacetimeDB.Internal.IProcedureContext ctx) + { + Reducers.DemoProcedure((SpacetimeDB.ProcedureContext)ctx); + return System.Array.Empty(); + } + } + + public static List ToListOrEmpty(T? value) + where T : struct => value is null ? new List() : new List { value.Value }; + + public static List ToListOrEmpty(T? value) + where T : class => value is null ? new List() : new List { value }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + // In AOT mode we're building a library. + // Main method won't be called automatically, so we need to export it as a preinit function. + [UnmanagedCallersOnly(EntryPoint = "__preinit__10_init_csharp")] +#else + // Prevent trimming of FFI exports that are invoked from C and not visible to C# trimmer. + [DynamicDependency(DynamicallyAccessedMemberTypes.PublicMethods, typeof(ModuleRegistration))] +#endif + public static void Main() => Initialize(); + + internal static void Initialize() + { +#if !NET10_0_OR_GREATER + SpacetimeDB.Internal.Module.SetReducerContextConstructor( + (identity, connectionId, random, time) => + new SpacetimeDB.ReducerContext(identity, connectionId, random, time) + ); + SpacetimeDB.Internal.Module.SetViewContextConstructor( + identity => new SpacetimeDB.ViewContext( + identity, + new SpacetimeDB.Internal.LocalReadOnly() + ) + ); + SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor(() => + new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly()) + ); + SpacetimeDB.Internal.Module.SetProcedureContextConstructor( + (identity, connectionId, random, time) => + new SpacetimeDB.ProcedureContext(identity, connectionId, random, time) + ); + SpacetimeDB.Internal.Module.SetHandlerContextConstructor( + (random, time) => new SpacetimeDB.HandlerContext(random, time) + ); +#endif + +#if NET10_0_OR_GREATER + global::SpacetimeDB.Internal.Module.InstallNamespaces( + new global::SpacetimeDB.Internal.NamespaceRegistry( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + global::SpacetimeDB.CaseConversionPolicy.SnakeCase, + new (string, string, string?, global::SpacetimeDB.CaseConversionPolicy)[] { } + ) + ); + global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.Register( + global::SpacetimeDB.Internal.Module.RootBuilder + ); +#else + Register(global::SpacetimeDB.Internal.Module.RootBuilder); +#endif + } + + internal static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) + { + // HTTP routes retain the root routing API even for mounted modules. + httpBuilder ??= builder; + builder.SetCaseConversionPolicy(SpacetimeDB.CaseConversionPolicy.SnakeCase); + builder.RegisterExplicitTableName("DemoTable", "canonical_table"); + builder.RegisterExplicitFunctionName("DemoReducer", "canonical_reducer"); + builder.RegisterExplicitFunctionName("DemoProcedure", "canonical_procedure"); + builder.RegisterExplicitFunctionName("demo_view", "canonical_view"); + builder.RegisterExplicitIndexName("DemoTable_Id_idx_btree", "canonical_index"); + var __memoryStream = new MemoryStream(); + var __writer = new BinaryWriter(__memoryStream); + + builder.RegisterReducer(); + builder.RegisterProcedure(); + + // IMPORTANT: The order in which we register views matters. + // It must correspond to the order in which we call `GenerateDispatcherClass`. + // See the comment on `GenerateDispatcherClass` for more explanation. + builder.RegisterView(); + + builder.RegisterTable< + global::DemoTable, + global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.TableHandles.DemoTable + >(); + } + + // Export entrypoints live in generated module code so all build modes can + // dispatch directly to concrete generated functions. +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__describe_module__")] +#endif + public static void __describe_module__(SpacetimeDB.Internal.BytesSink d) => + SpacetimeDB.Internal.Module.__describe_module__(d); + + private static SpacetimeDB.Internal.Errno __call_reducer_0( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + DemoReducer.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_procedure_0( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateProcedureContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref procedureArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + var bytes = DemoProcedure.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "procedure arguments"); + SpacetimeDB.Internal.Module.WriteBytes(result_sink, bytes); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking procedure: {e}"); + throw; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_0( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = demo_viewViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_reducer__")] +#endif + public static SpacetimeDB.Internal.Errno __call_reducer__( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ReducerCount + ) + return global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.CallLocalReducer( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + localId -= global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ReducerCount; + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); +#else + return CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) => + id switch + { + 0 => __call_reducer_0( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + _ => SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_procedure__")] +#endif + public static SpacetimeDB.Internal.Errno __call_procedure__( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ProcedureCount + ) + return global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.CallLocalProcedure( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + localId -= global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ProcedureCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); +#else + return CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink + ) => + id switch + { + 0 => __call_procedure_0( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ), + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown procedure id" + ), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_http_handler__")] +#endif + public static SpacetimeDB.Internal.Errno __call_http_handler__( + int id, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource request, + SpacetimeDB.Internal.BytesSource request_body, + SpacetimeDB.Internal.BytesSink response_sink, + SpacetimeDB.Internal.BytesSink response_body_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .HttpHandlerCount + ) + return global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.CallLocalHttpHandler( + localId, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + localId -= global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .HttpHandlerCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); +#else + return CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource request, + SpacetimeDB.Internal.BytesSource request_body, + SpacetimeDB.Internal.BytesSink response_sink, + SpacetimeDB.Internal.BytesSink response_body_sink + ) => + id switch + { + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown HTTP handler id" + ), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_view__")] +#endif + public static SpacetimeDB.Internal.Errno __call_view__( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ViewCount + ) + return global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.CallLocalView( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + localId -= global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .ViewCount; + return UnknownViewId(id); +#else + return CallLocalView(id, sender_0, sender_1, sender_2, sender_3, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) => + id switch + { + 0 => __call_view_0(sender_0, sender_1, sender_2, sender_3, args, sink), + _ => UnknownViewId(id), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_view_anon__")] +#endif + public static SpacetimeDB.Internal.Errno __call_view_anon__( + int id, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownAnonymousViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .AnonymousViewCount + ) + return global::SpacetimeDB.Generated.explicitnames_7C0F8C6449994F31.AssemblyDescriptor.CallLocalAnonymousView( + localId, + args, + sink + ); + localId -= global::SpacetimeDB + .Generated + .explicitnames_7C0F8C6449994F31 + .AssemblyDescriptor + .AnonymousViewCount; + return UnknownAnonymousViewId(id); +#else + return CallLocalAnonymousView(id, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) => + id switch + { + _ => UnknownAnonymousViewId(id), + }; + + private static SpacetimeDB.Internal.Errno UnknownViewId(int id) + { + SpacetimeDB.Log.Error($"Unknown view id: {id}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + + private static SpacetimeDB.Internal.Errno UnknownAnonymousViewId(int id) + { + SpacetimeDB.Log.Error($"Unknown anonymous view id: {id}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } +} + +#pragma warning restore STDB_UNSTABLE +#pragma warning restore CS0436 diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#Reducers.DemoProcedure.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#Reducers.DemoProcedure.verified.cs new file mode 100644 index 00000000000..4db9a55c612 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#Reducers.DemoProcedure.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.DemoProcedure.cs +// +#nullable enable + +partial class Reducers +{ + private static class __ScheduleDemoProcedureName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(DemoProcedure), + "canonical_procedure" + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleDemoProcedureName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateDemoProcedure() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + + SpacetimeDB.Internal.ProcedureExtensions.VolatileNonatomicScheduleImmediate( + __ScheduleDemoProcedureName.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#Reducers.DemoReducer.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#Reducers.DemoReducer.verified.cs new file mode 100644 index 00000000000..775f8b87ce6 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Module.net10#Reducers.DemoReducer.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.DemoReducer.cs +// +#nullable enable + +partial class Reducers +{ + private static class __ScheduleDemoReducerName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "explicitnames, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(DemoReducer), + "canonical_reducer" + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleDemoReducerName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateDemoReducer(int value) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + new SpacetimeDB.BSATN.I32().Write(writer, value); + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleDemoReducerName.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Type#DemoType.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Type#DemoType.verified.cs index 8c54a028122..e51b981b009 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Type#DemoType.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/explicitnames/snapshots/Type#DemoType.verified.cs @@ -44,7 +44,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar registrar.RegisterType(_ => new SpacetimeDB.BSATN.AlgebraicType.Product( new SpacetimeDB.BSATN.AggregateElement[] { - new("A", ARW.GetAlgebraicType(registrar)) + new("A", ARW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/Lib.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/Lib.cs index 0a7ba3693eb..fd6945985f3 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/Lib.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/Lib.cs @@ -4,6 +4,16 @@ #pragma warning disable CA1050 // Declare types in namespaces - this is a test fixture, no need for a namespace. #pragma warning disable STDB_UNSTABLE // Enable experimental SpacetimeDB features +[SpacetimeDB.Env] +public struct EnvironmentSchema +{ + public string REQUIRED; + public string? OPTIONAL; + + [SpacetimeDB.EnvValues("dev", "prod")] + public string MODE; +} + [SpacetimeDB.Type] public partial struct CustomStruct { diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/EnvironmentGenerator#Environment.g.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/EnvironmentGenerator#Environment.g.verified.cs new file mode 100644 index 00000000000..43a64d42e94 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/EnvironmentGenerator#Environment.g.verified.cs @@ -0,0 +1,46 @@ +//HintName: Environment.g.cs +// +#nullable enable +#pragma warning disable CS0436 +namespace SpacetimeDB +{ + public readonly struct ModuleEnvironment + { + public string? Get(string key) => default(global::SpacetimeDB.DatabaseEnvironment).Get(key); + + public string @REQUIRED => + Get("REQUIRED") + ?? throw new global::System.InvalidOperationException( + "Required environment value is absent" + ); + public string? @OPTIONAL => Get("OPTIONAL"); + public string @MODE => + Get("MODE") + ?? throw new global::System.InvalidOperationException( + "Required environment value is absent" + ); + } + + internal static class EnvironmentRegistration + { + [global::System.Runtime.CompilerServices.ModuleInitializer] + internal static void Register() + { + global::SpacetimeDB.Internal.Module.RegisterEnvironment( + new("REQUIRED", new global::SpacetimeDB.Internal.EnvVarType.String(default), false) + ); + global::SpacetimeDB.Internal.Module.RegisterEnvironment( + new("OPTIONAL", new global::SpacetimeDB.Internal.EnvVarType.String(default), true) + ); + global::SpacetimeDB.Internal.Module.RegisterEnvironment( + new( + "MODE", + new global::SpacetimeDB.Internal.EnvVarType.Union( + new global::System.Collections.Generic.List { "dev", "prod" } + ), + false + ) + ); + } + } +} diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/EnvironmentGenerator.net10#Environment.g.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/EnvironmentGenerator.net10#Environment.g.verified.cs new file mode 100644 index 00000000000..4ce133f61e1 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/EnvironmentGenerator.net10#Environment.g.verified.cs @@ -0,0 +1,23 @@ +//HintName: Environment.g.cs +// +#nullable enable +namespace SpacetimeDB.Generated.server_D513E4815F57969C +{ + public static class EnvironmentExtensions + { + extension(global::SpacetimeDB.DatabaseEnvironment env) + { + public string @REQUIRED => + env.Get("REQUIRED") + ?? throw new global::System.InvalidOperationException( + "Required environment value is absent" + ); + public string? @OPTIONAL => env.Get("OPTIONAL"); + public string @MODE => + env.Get("MODE") + ?? throw new global::System.InvalidOperationException( + "Required environment value is absent" + ); + } + } +} diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#BTreeMultiColumn.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#BTreeMultiColumn.verified.cs index f3bef07e88c..6b55693551c 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#BTreeMultiColumn.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#BTreeMultiColumn.verified.cs @@ -55,7 +55,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar { new("X", XRW.GetAlgebraicType(registrar)), new("Y", YRW.GetAlgebraicType(registrar)), - new("Z", ZRW.GetAlgebraicType(registrar)) + new("Z", ZRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#BTreeViews.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#BTreeViews.verified.cs index 4f2ba4e758e..c31ba82463d 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#BTreeViews.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#BTreeViews.verified.cs @@ -56,7 +56,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new("Id", IdRW.GetAlgebraicType(registrar)), new("X", XRW.GetAlgebraicType(registrar)), new("Y", YRW.GetAlgebraicType(registrar)), - new("Faction", FactionRW.GetAlgebraicType(registrar)) + new("Faction", FactionRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#FFI.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#FFI.verified.cs index 95bbf9c0516..b0436b146e4 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#FFI.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#FFI.verified.cs @@ -1,20 +1,28 @@ //HintName: FFI.cs // #nullable enable -// The runtime already defines SpacetimeDB.Internal.LocalReadOnly in Runtime\Internal\Module.cs as an empty partial type. -// This is needed so every module build doesn't generate a full LocalReadOnly type, but just adds on to the existing. -// We extend it here with generated table accessors, and just need to suppress the duplicate-type warning. +// .NET 8 generates a module-local LocalReadOnly which shadows the runtime shell. #pragma warning disable CS0436 #pragma warning disable STDB_UNSTABLE +#if NET10_0_OR_GREATER +global using SpacetimeDB.Generated.server_D513E4815F57969C; +#endif using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal = SpacetimeDB.Internal; using TxContext = SpacetimeDB.Internal.TxContext; +#if NET10_0_OR_GREATER +[assembly: global::SpacetimeDB.ModuleDescriptorAttribute( + typeof(global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor) +)] + +#endif namespace SpacetimeDB { +#if !NET10_0_OR_GREATER internal readonly struct BTreeMultiColumnCols { public readonly global::SpacetimeDB.Col X; @@ -488,9 +496,11 @@ public readonly partial struct QueryBuilder new SendMessageTimerIxCols("SendMessageTimer") ); } +#endif - public static class Handlers { } + internal static class Handlers { } +#if !NET10_0_OR_GREATER public sealed record ReducerContext : DbContext, Internal.IReducerContext { public global::SpacetimeDB.ModuleEnvironment Env => default; @@ -715,45 +725,962 @@ internal HandlerTxContext(Internal.TxContext inner) public new Local Db => (Local)base.Db; } - public sealed class Local : global::SpacetimeDB.LocalBase + public sealed class Local : global::SpacetimeDB.LocalBase + { + internal global::SpacetimeDB.Internal.TableHandles.BTreeMultiColumn BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Internal.TableHandles.BTreeViews BTreeViews => new(); + public global::SpacetimeDB.Internal.TableHandles.MultiTable1 MultiTable1 => new(); + public global::SpacetimeDB.Internal.TableHandles.MultiTable2 MultiTable2 => new(); + public global::SpacetimeDB.Internal.TableHandles.PrivateTable PrivateTable => new(); + public global::SpacetimeDB.Internal.TableHandles.PublicTable PublicTable => new(); + internal global::SpacetimeDB.Internal.TableHandles.RegressionMultipleUniqueIndexesHadSameName RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Internal.TableHandles.SendMessageTimer SendMessageTimer => new(); + } + + public sealed record ViewContext : DbContext, Internal.IViewContext + { + public Identity Sender { get; } + + public global::SpacetimeDB.ModuleEnvironment Env => default; + public QueryBuilder From => default; + + internal ViewContext(Identity sender, Internal.LocalReadOnly db) + : base(db) + { + Sender = sender; + } + } + + public sealed record AnonymousViewContext + : DbContext, + Internal.IAnonymousViewContext + { + public global::SpacetimeDB.ModuleEnvironment Env => default; + public QueryBuilder From => default; + + internal AnonymousViewContext(Internal.LocalReadOnly db) + : base(db) { } + } +#endif +} + +#if NET10_0_OR_GREATER +namespace SpacetimeDB.Generated.server_D513E4815F57969C +{ + public static partial class AssemblyDescriptor + { + public const string? CaseConversionPolicy = null; + public const string RootOnlyDeclarations = + "row-level security filters, environment variables, lifecycle reducer Timers.Init (Init)"; + public const int ReducerCount = 6; + public const int ProcedureCount = 0; + public const int HttpHandlerCount = 0; + public const int ViewCount = 2; + public const int AnonymousViewCount = 1; + + public static global::SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink error + ) => + global::ModuleRegistration.CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink result_sink + ) => + global::ModuleRegistration.CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource request, + global::SpacetimeDB.Internal.BytesSource request_body, + global::SpacetimeDB.Internal.BytesSink response_sink, + global::SpacetimeDB.Internal.BytesSink response_body_sink + ) => + global::ModuleRegistration.CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => + global::ModuleRegistration.CallLocalView( + id, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => global::ModuleRegistration.CallLocalAnonymousView(id, args, sink); + + public static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) => global::ModuleRegistration.Register(builder, httpBuilder); + + public readonly struct Tables + { + internal global::SpacetimeDB.Internal.TableHandles.BTreeMultiColumn BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Internal.TableHandles.BTreeViews BTreeViews => new(); + public global::SpacetimeDB.Internal.TableHandles.MultiTable1 MultiTable1 => new(); + public global::SpacetimeDB.Internal.TableHandles.MultiTable2 MultiTable2 => new(); + public global::SpacetimeDB.Internal.TableHandles.PrivateTable PrivateTable => new(); + public global::SpacetimeDB.Internal.TableHandles.PublicTable PublicTable => new(); + internal global::SpacetimeDB.Internal.TableHandles.RegressionMultipleUniqueIndexesHadSameName RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Internal.TableHandles.SendMessageTimer SendMessageTimer => + new(); + } + + public readonly struct ReadOnlyTables + { + internal global::SpacetimeDB.Internal.ViewHandles.BTreeMultiColumnReadOnly BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Internal.ViewHandles.BTreeViewsReadOnly BTreeViews => + new(); + public global::SpacetimeDB.Internal.ViewHandles.MultiTable1ReadOnly MultiTable1 => + new(); + public global::SpacetimeDB.Internal.ViewHandles.MultiTable2ReadOnly MultiTable2 => + new(); + public global::SpacetimeDB.Internal.ViewHandles.PrivateTableReadOnly PrivateTable => + new(); + public global::SpacetimeDB.Internal.ViewHandles.PublicTableReadOnly PublicTable => + new(); + internal global::SpacetimeDB.Internal.ViewHandles.RegressionMultipleUniqueIndexesHadSameNameReadOnly RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Internal.ViewHandles.SendMessageTimerReadOnly SendMessageTimer => + new(); + } + + public readonly partial struct Queries { } + } + + public static class LocalTableExtensions + { + extension(global::SpacetimeDB.Local db) + { + internal global::SpacetimeDB.Internal.TableHandles.BTreeMultiColumn BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Internal.TableHandles.BTreeViews BTreeViews => new(); + public global::SpacetimeDB.Internal.TableHandles.MultiTable1 MultiTable1 => new(); + public global::SpacetimeDB.Internal.TableHandles.MultiTable2 MultiTable2 => new(); + public global::SpacetimeDB.Internal.TableHandles.PrivateTable PrivateTable => new(); + public global::SpacetimeDB.Internal.TableHandles.PublicTable PublicTable => new(); + internal global::SpacetimeDB.Internal.TableHandles.RegressionMultipleUniqueIndexesHadSameName RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Internal.TableHandles.SendMessageTimer SendMessageTimer => + new(); + } + } + + public static class ReadOnlyTableExtensions + { + extension(global::SpacetimeDB.Internal.LocalReadOnly db) + { + internal global::SpacetimeDB.Internal.ViewHandles.BTreeMultiColumnReadOnly BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Internal.ViewHandles.BTreeViewsReadOnly BTreeViews => + new(); + public global::SpacetimeDB.Internal.ViewHandles.MultiTable1ReadOnly MultiTable1 => + new(); + public global::SpacetimeDB.Internal.ViewHandles.MultiTable2ReadOnly MultiTable2 => + new(); + public global::SpacetimeDB.Internal.ViewHandles.PrivateTableReadOnly PrivateTable => + new(); + public global::SpacetimeDB.Internal.ViewHandles.PublicTableReadOnly PublicTable => + new(); + internal global::SpacetimeDB.Internal.ViewHandles.RegressionMultipleUniqueIndexesHadSameNameReadOnly RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Internal.ViewHandles.SendMessageTimerReadOnly SendMessageTimer => + new(); + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) { } + } + + internal readonly struct BTreeMultiColumnCols + { + public readonly global::SpacetimeDB.Col X; + public readonly global::SpacetimeDB.Col Y; + public readonly global::SpacetimeDB.Col Z; + + internal BTreeMultiColumnCols(global::SpacetimeDB.SqlTableName tableName) + { + X = new global::SpacetimeDB.Col(tableName, "X"); + Y = new global::SpacetimeDB.Col(tableName, "Y"); + Z = new global::SpacetimeDB.Col(tableName, "Z"); + } + } + + internal readonly struct BTreeMultiColumnIxCols + { + public readonly global::SpacetimeDB.IxCol X; + public readonly global::SpacetimeDB.IxCol Y; + public readonly global::SpacetimeDB.IxCol Z; + + internal BTreeMultiColumnIxCols(global::SpacetimeDB.SqlTableName tableName) + { + X = new global::SpacetimeDB.IxCol(tableName, "X"); + Y = new global::SpacetimeDB.IxCol(tableName, "Y"); + Z = new global::SpacetimeDB.IxCol(tableName, "Z"); + } + } + + public static partial class AssemblyDescriptor + { + private static class BTreeMultiColumnSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeMultiColumn" + ); + + // Prevent eager initialization before the root installs namespace placements. + static BTreeMultiColumnSqlNameCache() { } + } + + public readonly partial struct Queries + { + internal global::SpacetimeDB.Table< + global::BTreeMultiColumn, + BTreeMultiColumnCols, + BTreeMultiColumnIxCols + > BTreeMultiColumn() + { + var tableName = BTreeMultiColumnSqlNameCache.Name; + return new( + tableName, + new BTreeMultiColumnCols(tableName), + new BTreeMultiColumnIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + internal global::SpacetimeDB.Table< + global::BTreeMultiColumn, + BTreeMultiColumnCols, + BTreeMultiColumnIxCols + > BTreeMultiColumn() => new AssemblyDescriptor.Queries().BTreeMultiColumn(); + } + } + + internal readonly struct BTreeViewsCols + { + public readonly global::SpacetimeDB.Col Id; + public readonly global::SpacetimeDB.Col X; + public readonly global::SpacetimeDB.Col Y; + public readonly global::SpacetimeDB.Col Faction; + + internal BTreeViewsCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col( + tableName, + "Id" + ); + X = new global::SpacetimeDB.Col(tableName, "X"); + Y = new global::SpacetimeDB.Col(tableName, "Y"); + Faction = new global::SpacetimeDB.Col(tableName, "Faction"); + } + } + + internal readonly struct BTreeViewsIxCols + { + public readonly global::SpacetimeDB.IxCol Id; + public readonly global::SpacetimeDB.IxCol X; + public readonly global::SpacetimeDB.IxCol Y; + public readonly global::SpacetimeDB.IxCol Faction; + + internal BTreeViewsIxCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.IxCol( + tableName, + "Id" + ); + X = new global::SpacetimeDB.IxCol(tableName, "X"); + Y = new global::SpacetimeDB.IxCol(tableName, "Y"); + Faction = new global::SpacetimeDB.IxCol( + tableName, + "Faction" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class BTreeViewsSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeViews" + ); + + // Prevent eager initialization before the root installs namespace placements. + static BTreeViewsSqlNameCache() { } + } + + public readonly partial struct Queries + { + internal global::SpacetimeDB.Table< + global::BTreeViews, + BTreeViewsCols, + BTreeViewsIxCols + > BTreeViews() + { + var tableName = BTreeViewsSqlNameCache.Name; + return new( + tableName, + new BTreeViewsCols(tableName), + new BTreeViewsIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + internal global::SpacetimeDB.Table< + global::BTreeViews, + BTreeViewsCols, + BTreeViewsIxCols + > BTreeViews() => new AssemblyDescriptor.Queries().BTreeViews(); + } + } + + public readonly struct MultiTable1Cols + { + public readonly global::SpacetimeDB.Col Name; + public readonly global::SpacetimeDB.Col Foo; + public readonly global::SpacetimeDB.Col Bar; + + internal MultiTable1Cols(global::SpacetimeDB.SqlTableName tableName) + { + Name = new global::SpacetimeDB.Col(tableName, "Name"); + Foo = new global::SpacetimeDB.Col(tableName, "Foo"); + Bar = new global::SpacetimeDB.Col(tableName, "Bar"); + } + } + + public readonly struct MultiTable1IxCols + { + public readonly global::SpacetimeDB.IxCol Name; + public readonly global::SpacetimeDB.IxCol Foo; + + internal MultiTable1IxCols(global::SpacetimeDB.SqlTableName tableName) + { + Name = new global::SpacetimeDB.IxCol(tableName, "Name"); + Foo = new global::SpacetimeDB.IxCol(tableName, "Foo"); + } + } + + public static partial class AssemblyDescriptor + { + private static class MultiTable1SqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable1" + ); + + // Prevent eager initialization before the root installs namespace placements. + static MultiTable1SqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::MultiTableRow, + MultiTable1Cols, + MultiTable1IxCols + > MultiTable1() + { + var tableName = MultiTable1SqlNameCache.Name; + return new( + tableName, + new MultiTable1Cols(tableName), + new MultiTable1IxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::MultiTableRow, + MultiTable1Cols, + MultiTable1IxCols + > MultiTable1() => new AssemblyDescriptor.Queries().MultiTable1(); + } + } + + public readonly struct MultiTable2Cols + { + public readonly global::SpacetimeDB.Col Name; + public readonly global::SpacetimeDB.Col Foo; + public readonly global::SpacetimeDB.Col Bar; + + internal MultiTable2Cols(global::SpacetimeDB.SqlTableName tableName) + { + Name = new global::SpacetimeDB.Col(tableName, "Name"); + Foo = new global::SpacetimeDB.Col(tableName, "Foo"); + Bar = new global::SpacetimeDB.Col(tableName, "Bar"); + } + } + + public readonly struct MultiTable2IxCols + { + internal MultiTable2IxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class MultiTable2SqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable2" + ); + + // Prevent eager initialization before the root installs namespace placements. + static MultiTable2SqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::MultiTableRow, + MultiTable2Cols, + MultiTable2IxCols + > MultiTable2() + { + var tableName = MultiTable2SqlNameCache.Name; + return new( + tableName, + new MultiTable2Cols(tableName), + new MultiTable2IxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::MultiTableRow, + MultiTable2Cols, + MultiTable2IxCols + > MultiTable2() => new AssemblyDescriptor.Queries().MultiTable2(); + } + } + + public readonly struct PrivateTableCols + { + internal PrivateTableCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public readonly struct PrivateTableIxCols + { + internal PrivateTableIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class PrivateTableSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "PrivateTable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PrivateTableSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::PrivateTable, + PrivateTableCols, + PrivateTableIxCols + > PrivateTable() + { + var tableName = PrivateTableSqlNameCache.Name; + return new( + tableName, + new PrivateTableCols(tableName), + new PrivateTableIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::PrivateTable, + PrivateTableCols, + PrivateTableIxCols + > PrivateTable() => new AssemblyDescriptor.Queries().PrivateTable(); + } + } + + public readonly struct PublicTableCols + { + public readonly global::SpacetimeDB.Col Id; + public readonly global::SpacetimeDB.Col ByteField; + public readonly global::SpacetimeDB.Col UshortField; + public readonly global::SpacetimeDB.Col UintField; + public readonly global::SpacetimeDB.Col UlongField; + public readonly global::SpacetimeDB.Col UInt128Field; + public readonly global::SpacetimeDB.Col U128Field; + public readonly global::SpacetimeDB.Col U256Field; + public readonly global::SpacetimeDB.Col SbyteField; + public readonly global::SpacetimeDB.Col ShortField; + public readonly global::SpacetimeDB.Col IntField; + public readonly global::SpacetimeDB.Col LongField; + public readonly global::SpacetimeDB.Col Int128Field; + public readonly global::SpacetimeDB.Col I128Field; + public readonly global::SpacetimeDB.Col I256Field; + public readonly global::SpacetimeDB.Col BoolField; + public readonly global::SpacetimeDB.Col FloatField; + public readonly global::SpacetimeDB.Col DoubleField; + public readonly global::SpacetimeDB.Col StringField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + SpacetimeDB.Identity + > IdentityField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + SpacetimeDB.ConnectionId + > ConnectionIdField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + CustomStruct + > CustomStructField; + public readonly global::SpacetimeDB.Col CustomClassField; + public readonly global::SpacetimeDB.Col CustomEnumField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + CustomTaggedEnum + > CustomTaggedEnumField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + System.Collections.Generic.List + > ListField; + public readonly global::SpacetimeDB.Col NullableValueField; + public readonly global::SpacetimeDB.Col NullableReferenceField; + + internal PublicTableCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "Id"); + ByteField = new global::SpacetimeDB.Col( + tableName, + "ByteField" + ); + UshortField = new global::SpacetimeDB.Col( + tableName, + "UshortField" + ); + UintField = new global::SpacetimeDB.Col( + tableName, + "UintField" + ); + UlongField = new global::SpacetimeDB.Col( + tableName, + "UlongField" + ); + UInt128Field = new global::SpacetimeDB.Col( + tableName, + "UInt128Field" + ); + U128Field = new global::SpacetimeDB.Col( + tableName, + "U128Field" + ); + U256Field = new global::SpacetimeDB.Col( + tableName, + "U256Field" + ); + SbyteField = new global::SpacetimeDB.Col( + tableName, + "SbyteField" + ); + ShortField = new global::SpacetimeDB.Col( + tableName, + "ShortField" + ); + IntField = new global::SpacetimeDB.Col(tableName, "IntField"); + LongField = new global::SpacetimeDB.Col( + tableName, + "LongField" + ); + Int128Field = new global::SpacetimeDB.Col( + tableName, + "Int128Field" + ); + I128Field = new global::SpacetimeDB.Col( + tableName, + "I128Field" + ); + I256Field = new global::SpacetimeDB.Col( + tableName, + "I256Field" + ); + BoolField = new global::SpacetimeDB.Col( + tableName, + "BoolField" + ); + FloatField = new global::SpacetimeDB.Col( + tableName, + "FloatField" + ); + DoubleField = new global::SpacetimeDB.Col( + tableName, + "DoubleField" + ); + StringField = new global::SpacetimeDB.Col( + tableName, + "StringField" + ); + IdentityField = new global::SpacetimeDB.Col( + tableName, + "IdentityField" + ); + ConnectionIdField = new global::SpacetimeDB.Col< + global::PublicTable, + SpacetimeDB.ConnectionId + >(tableName, "ConnectionIdField"); + CustomStructField = new global::SpacetimeDB.Col( + tableName, + "CustomStructField" + ); + CustomClassField = new global::SpacetimeDB.Col( + tableName, + "CustomClassField" + ); + CustomEnumField = new global::SpacetimeDB.Col( + tableName, + "CustomEnumField" + ); + CustomTaggedEnumField = new global::SpacetimeDB.Col< + global::PublicTable, + CustomTaggedEnum + >(tableName, "CustomTaggedEnumField"); + ListField = new global::SpacetimeDB.Col< + global::PublicTable, + System.Collections.Generic.List + >(tableName, "ListField"); + NullableValueField = new global::SpacetimeDB.Col( + tableName, + "NullableValueField" + ); + NullableReferenceField = new global::SpacetimeDB.Col( + tableName, + "NullableReferenceField" + ); + } + } + + public readonly struct PublicTableIxCols + { + public readonly global::SpacetimeDB.IxCol Id; + + internal PublicTableIxCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "Id"); + } + } + + public static partial class AssemblyDescriptor + { + private static class PublicTableSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "PublicTable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PublicTableSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::PublicTable, + PublicTableCols, + PublicTableIxCols + > PublicTable() + { + var tableName = PublicTableSqlNameCache.Name; + return new( + tableName, + new PublicTableCols(tableName), + new PublicTableIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::PublicTable, + PublicTableCols, + PublicTableIxCols + > PublicTable() => new AssemblyDescriptor.Queries().PublicTable(); + } + } + + internal readonly struct RegressionMultipleUniqueIndexesHadSameNameCols + { + public readonly global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + > Unique1; + public readonly global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + > Unique2; + + internal RegressionMultipleUniqueIndexesHadSameNameCols( + global::SpacetimeDB.SqlTableName tableName + ) + { + Unique1 = new global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + >(tableName, "Unique1"); + Unique2 = new global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + >(tableName, "Unique2"); + } + } + + internal readonly struct RegressionMultipleUniqueIndexesHadSameNameIxCols + { + internal RegressionMultipleUniqueIndexesHadSameNameIxCols( + global::SpacetimeDB.SqlTableName tableName + ) { } + } + + public static partial class AssemblyDescriptor + { + private static class RegressionMultipleUniqueIndexesHadSameNameSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "RegressionMultipleUniqueIndexesHadSameName" + ); + + // Prevent eager initialization before the root installs namespace placements. + static RegressionMultipleUniqueIndexesHadSameNameSqlNameCache() { } + } + + public readonly partial struct Queries + { + internal global::SpacetimeDB.Table< + global::RegressionMultipleUniqueIndexesHadSameName, + RegressionMultipleUniqueIndexesHadSameNameCols, + RegressionMultipleUniqueIndexesHadSameNameIxCols + > RegressionMultipleUniqueIndexesHadSameName() + { + var tableName = RegressionMultipleUniqueIndexesHadSameNameSqlNameCache.Name; + return new( + tableName, + new RegressionMultipleUniqueIndexesHadSameNameCols(tableName), + new RegressionMultipleUniqueIndexesHadSameNameIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + internal global::SpacetimeDB.Table< + global::RegressionMultipleUniqueIndexesHadSameName, + RegressionMultipleUniqueIndexesHadSameNameCols, + RegressionMultipleUniqueIndexesHadSameNameIxCols + > RegressionMultipleUniqueIndexesHadSameName() => + new AssemblyDescriptor.Queries().RegressionMultipleUniqueIndexesHadSameName(); + } + } + + public readonly struct SendMessageTimerCols + { + public readonly global::SpacetimeDB.Col ScheduledId; + public readonly global::SpacetimeDB.Col< + global::Timers.SendMessageTimer, + SpacetimeDB.ScheduleAt + > ScheduledAt; + public readonly global::SpacetimeDB.Col Text; + + internal SendMessageTimerCols(global::SpacetimeDB.SqlTableName tableName) + { + ScheduledId = new global::SpacetimeDB.Col( + tableName, + "ScheduledId" + ); + ScheduledAt = new global::SpacetimeDB.Col< + global::Timers.SendMessageTimer, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduledAt"); + Text = new global::SpacetimeDB.Col( + tableName, + "Text" + ); + } + } + + public readonly struct SendMessageTimerIxCols { - internal global::SpacetimeDB.Internal.TableHandles.BTreeMultiColumn BTreeMultiColumn => - new(); - internal global::SpacetimeDB.Internal.TableHandles.BTreeViews BTreeViews => new(); - public global::SpacetimeDB.Internal.TableHandles.MultiTable1 MultiTable1 => new(); - public global::SpacetimeDB.Internal.TableHandles.MultiTable2 MultiTable2 => new(); - public global::SpacetimeDB.Internal.TableHandles.PrivateTable PrivateTable => new(); - public global::SpacetimeDB.Internal.TableHandles.PublicTable PublicTable => new(); - internal global::SpacetimeDB.Internal.TableHandles.RegressionMultipleUniqueIndexesHadSameName RegressionMultipleUniqueIndexesHadSameName => - new(); - public global::SpacetimeDB.Internal.TableHandles.SendMessageTimer SendMessageTimer => new(); + public readonly global::SpacetimeDB.IxCol< + global::Timers.SendMessageTimer, + ulong + > ScheduledId; + + internal SendMessageTimerIxCols(global::SpacetimeDB.SqlTableName tableName) + { + ScheduledId = new global::SpacetimeDB.IxCol( + tableName, + "ScheduledId" + ); + } } - public sealed record ViewContext : DbContext, Internal.IViewContext + public static partial class AssemblyDescriptor { - public Identity Sender { get; } + private static class SendMessageTimerSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "SendMessageTimer" + ); - public global::SpacetimeDB.ModuleEnvironment Env => default; - public QueryBuilder From => default; + // Prevent eager initialization before the root installs namespace placements. + static SendMessageTimerSqlNameCache() { } + } - internal ViewContext(Identity sender, Internal.LocalReadOnly db) - : base(db) + public readonly partial struct Queries { - Sender = sender; + public global::SpacetimeDB.Table< + global::Timers.SendMessageTimer, + SendMessageTimerCols, + SendMessageTimerIxCols + > SendMessageTimer() + { + var tableName = SendMessageTimerSqlNameCache.Name; + return new( + tableName, + new SendMessageTimerCols(tableName), + new SendMessageTimerIxCols(tableName) + ); + } } } - public sealed record AnonymousViewContext - : DbContext, - Internal.IAnonymousViewContext + public static partial class QueryTableExtensions { - public global::SpacetimeDB.ModuleEnvironment Env => default; - public QueryBuilder From => default; - - internal AnonymousViewContext(Internal.LocalReadOnly db) - : base(db) { } + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::Timers.SendMessageTimer, + SendMessageTimerCols, + SendMessageTimerIxCols + > SendMessageTimer() => new AssemblyDescriptor.Queries().SendMessageTimer(); + } } } +#endif namespace SpacetimeDB.Internal.TableHandles { @@ -782,7 +1709,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "BTreeMultiColumn_X_Y_Z_idx_btree", AccessorName: "Location", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0, 1, 2]) - ) + ), ], Constraints: [], Sequences: [], @@ -980,14 +1907,14 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "BTreeViews_Faction_idx_btree", AccessorName: "Faction", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([3]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< BTreeViews, global::BTreeViews - >.MakeUniqueConstraint(0) + >.MakeUniqueConstraint(0), ], Sequences: [], TableType: SpacetimeDB.Internal.TableType.User, @@ -1020,7 +1947,7 @@ public ulong Clear() => global::SpacetimeDB.Internal.ITableView.DoClear(); internal sealed class IdUniqueIndex - : UniqueIndex< + : global::SpacetimeDB.Internal.UniqueIndex< BTreeViews, global::BTreeViews, SpacetimeDB.Identity, @@ -1171,21 +2098,21 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "MultiTable1_Name_idx_btree", AccessorName: "Name", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< MultiTable1, global::MultiTableRow - >.MakeUniqueConstraint(1) + >.MakeUniqueConstraint(1), ], Sequences: [ global::SpacetimeDB.Internal.ITableView< MultiTable1, global::MultiTableRow - >.MakeSequence(1) + >.MakeSequence(1), ], TableType: SpacetimeDB.Internal.TableType.User, TableAccess: SpacetimeDB.Internal.TableAccess.Public, @@ -1221,7 +2148,12 @@ public ulong Clear() => global::SpacetimeDB.Internal.ITableView.DoClear(); public sealed class FooUniqueIndex - : UniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + MultiTable1, + global::MultiTableRow, + uint, + SpacetimeDB.BSATN.U32 + > { internal FooUniqueIndex() : base("MultiTable1_Foo_idx_btree") { } @@ -1302,21 +2234,21 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "MultiTable2_Bar_idx_btree", AccessorName: "Bar", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([2]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< MultiTable2, global::MultiTableRow - >.MakeUniqueConstraint(2) + >.MakeUniqueConstraint(2), ], Sequences: [ global::SpacetimeDB.Internal.ITableView< MultiTable2, global::MultiTableRow - >.MakeSequence(1) + >.MakeSequence(1), ], TableType: SpacetimeDB.Internal.TableType.User, TableAccess: SpacetimeDB.Internal.TableAccess.Private, @@ -1352,7 +2284,12 @@ public ulong Clear() => global::SpacetimeDB.Internal.ITableView.DoClear(); public sealed class BarUniqueIndex - : UniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + MultiTable2, + global::MultiTableRow, + uint, + SpacetimeDB.BSATN.U32 + > { internal BarUniqueIndex() : base("MultiTable2_Bar_idx_btree") { } @@ -1451,21 +2388,21 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "PublicTable_Id_idx_btree", AccessorName: "Id", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< PublicTable, global::PublicTable - >.MakeUniqueConstraint(0) + >.MakeUniqueConstraint(0), ], Sequences: [ global::SpacetimeDB.Internal.ITableView< PublicTable, global::PublicTable - >.MakeSequence(0) + >.MakeSequence(0), ], TableType: SpacetimeDB.Internal.TableType.User, TableAccess: SpacetimeDB.Internal.TableAccess.Public, @@ -1497,7 +2434,12 @@ public ulong Clear() => global::SpacetimeDB.Internal.ITableView.DoClear(); public sealed class IdUniqueIndex - : UniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + PublicTable, + global::PublicTable, + int, + SpacetimeDB.BSATN.I32 + > { internal IdUniqueIndex() : base("PublicTable_Id_idx_btree") { } @@ -1548,7 +2490,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "RegressionMultipleUniqueIndexesHadSameName_Unique2_idx_btree", AccessorName: "Unique2", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) - ) + ), ], Constraints: [ @@ -1559,7 +2501,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar global::SpacetimeDB.Internal.ITableView< RegressionMultipleUniqueIndexesHadSameName, global::RegressionMultipleUniqueIndexesHadSameName - >.MakeUniqueConstraint(1) + >.MakeUniqueConstraint(1), ], Sequences: [], TableType: SpacetimeDB.Internal.TableType.User, @@ -1609,7 +2551,7 @@ public ulong Clear() => >.DoClear(); internal sealed class Unique1UniqueIndex - : UniqueIndex< + : global::SpacetimeDB.Internal.UniqueIndex< RegressionMultipleUniqueIndexesHadSameName, global::RegressionMultipleUniqueIndexesHadSameName, uint, @@ -1629,7 +2571,7 @@ internal Unique1UniqueIndex() internal Unique1UniqueIndex Unique1 => new(); internal sealed class Unique2UniqueIndex - : UniqueIndex< + : global::SpacetimeDB.Internal.UniqueIndex< RegressionMultipleUniqueIndexesHadSameName, global::RegressionMultipleUniqueIndexesHadSameName, uint, @@ -1678,21 +2620,21 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar SourceName: "SendMessageTimer_ScheduledId_idx_btree", AccessorName: "ScheduledId", Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) - ) + ), ], Constraints: [ global::SpacetimeDB.Internal.ITableView< SendMessageTimer, global::Timers.SendMessageTimer - >.MakeUniqueConstraint(0) + >.MakeUniqueConstraint(0), ], Sequences: [ global::SpacetimeDB.Internal.ITableView< SendMessageTimer, global::Timers.SendMessageTimer - >.MakeSequence(0) + >.MakeSequence(0), ], TableType: SpacetimeDB.Internal.TableType.User, TableAccess: SpacetimeDB.Internal.TableAccess.Private, @@ -1743,7 +2685,7 @@ public ulong Clear() => >.DoClear(); public sealed class ScheduledIdUniqueIndex - : UniqueIndex< + : global::SpacetimeDB.Internal.UniqueIndex< SendMessageTimer, global::Timers.SendMessageTimer, ulong, @@ -2311,6 +3253,7 @@ internal ScheduledIdIndex() } } +#if !NET10_0_OR_GREATER namespace SpacetimeDB.Internal { public sealed partial class LocalReadOnly @@ -2328,6 +3271,7 @@ public sealed partial class LocalReadOnly new(); } } +#endif static class ModuleRegistration { @@ -2493,8 +3437,11 @@ public static List ToListOrEmpty(T? value) // Prevent trimming of FFI exports that are invoked from C and not visible to C# trimmer. [DynamicDependency(DynamicallyAccessedMemberTypes.PublicMethods, typeof(ModuleRegistration))] #endif - public static void Main() + public static void Main() => Initialize(); + + internal static void Initialize() { +#if !NET10_0_OR_GREATER SpacetimeDB.Internal.Module.SetReducerContextConstructor( (identity, connectionId, random, time) => new SpacetimeDB.ReducerContext(identity, connectionId, random, time) @@ -2505,8 +3452,8 @@ public static void Main() new SpacetimeDB.Internal.LocalReadOnly() ) ); - SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor( - () => new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly()) + SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor(() => + new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly()) ); SpacetimeDB.Internal.Module.SetProcedureContextConstructor( (identity, connectionId, random, time) => @@ -2515,59 +3462,83 @@ public static void Main() SpacetimeDB.Internal.Module.SetHandlerContextConstructor( (random, time) => new SpacetimeDB.HandlerContext(random, time) ); +#endif + +#if NET10_0_OR_GREATER + global::SpacetimeDB.Internal.Module.InstallNamespaces( + new global::SpacetimeDB.Internal.NamespaceRegistry( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + global::SpacetimeDB.CaseConversionPolicy.SnakeCase, + new (string, string, string?, global::SpacetimeDB.CaseConversionPolicy)[] { } + ) + ); + global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.Register( + global::SpacetimeDB.Internal.Module.RootBuilder + ); +#else + Register(global::SpacetimeDB.Internal.Module.RootBuilder); +#endif + } + + internal static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) + { + // HTTP routes retain the root routing API even for mounted modules. + httpBuilder ??= builder; + var __memoryStream = new MemoryStream(); var __writer = new BinaryWriter(__memoryStream); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); - SpacetimeDB.Internal.Module.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); // IMPORTANT: The order in which we register views matters. // It must correspond to the order in which we call `GenerateDispatcherClass`. // See the comment on `GenerateDispatcherClass` for more explanation. - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterView(); - SpacetimeDB.Internal.Module.RegisterAnonymousView(); + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterAnonymousView(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::BTreeMultiColumn, - SpacetimeDB.Internal.TableHandles.BTreeMultiColumn + global::SpacetimeDB.Internal.TableHandles.BTreeMultiColumn >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::BTreeViews, - SpacetimeDB.Internal.TableHandles.BTreeViews + global::SpacetimeDB.Internal.TableHandles.BTreeViews >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::MultiTableRow, - SpacetimeDB.Internal.TableHandles.MultiTable1 + global::SpacetimeDB.Internal.TableHandles.MultiTable1 >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::MultiTableRow, - SpacetimeDB.Internal.TableHandles.MultiTable2 + global::SpacetimeDB.Internal.TableHandles.MultiTable2 >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::PrivateTable, - SpacetimeDB.Internal.TableHandles.PrivateTable + global::SpacetimeDB.Internal.TableHandles.PrivateTable >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::PublicTable, - SpacetimeDB.Internal.TableHandles.PublicTable + global::SpacetimeDB.Internal.TableHandles.PublicTable >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::RegressionMultipleUniqueIndexesHadSameName, - SpacetimeDB.Internal.TableHandles.RegressionMultipleUniqueIndexesHadSameName + global::SpacetimeDB.Internal.TableHandles.RegressionMultipleUniqueIndexesHadSameName >(); - SpacetimeDB.Internal.Module.RegisterTable< + builder.RegisterTable< global::Timers.SendMessageTimer, - SpacetimeDB.Internal.TableHandles.SendMessageTimer + global::SpacetimeDB.Internal.TableHandles.SendMessageTimer >(); - SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter( - global::Module.ALL_PUBLIC_TABLES - ); + builder.RegisterClientVisibilityFilter(global::Module.ALL_PUBLIC_TABLES); } // Export entrypoints live in generated module code so all build modes can @@ -2904,86 +3875,147 @@ public static SpacetimeDB.Internal.Errno __call_reducer__( SpacetimeDB.Timestamp timestamp, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink error + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .ReducerCount + ) + return global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.CallLocalReducer( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + localId -= global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .ReducerCount; + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); +#else + return CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error ) => id switch { - 0 - => __call_reducer_0( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 1 - => __call_reducer_1( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 2 - => __call_reducer_2( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 3 - => __call_reducer_3( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 4 - => __call_reducer_4( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - 5 - => __call_reducer_5( - sender_0, - sender_1, - sender_2, - sender_3, - conn_id_0, - conn_id_1, - timestamp, - args, - error - ), - _ - => SpacetimeDB.Internal.Module.WriteReducerError( - error, - new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") - ) + 0 => __call_reducer_0( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 1 => __call_reducer_1( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 2 => __call_reducer_2( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 3 => __call_reducer_3( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 4 => __call_reducer_4( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 5 => __call_reducer_5( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + _ => SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -3000,15 +4032,76 @@ public static SpacetimeDB.Internal.Errno __call_procedure__( SpacetimeDB.Timestamp timestamp, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink result_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .ProcedureCount + ) + return global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.CallLocalProcedure( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + localId -= global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .ProcedureCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); +#else + return CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink ) => id switch { - _ - => throw new System.ArgumentOutOfRangeException( - nameof(id), - id, - "Unknown procedure id" - ) + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown procedure id" + ), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -3021,15 +4114,64 @@ public static SpacetimeDB.Internal.Errno __call_http_handler__( SpacetimeDB.Internal.BytesSource request_body, SpacetimeDB.Internal.BytesSink response_sink, SpacetimeDB.Internal.BytesSink response_body_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .HttpHandlerCount + ) + return global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.CallLocalHttpHandler( + localId, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + localId -= global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .HttpHandlerCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); +#else + return CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource request, + SpacetimeDB.Internal.BytesSource request_body, + SpacetimeDB.Internal.BytesSink response_sink, + SpacetimeDB.Internal.BytesSink response_body_sink ) => id switch { - _ - => throw new System.ArgumentOutOfRangeException( - nameof(id), - id, - "Unknown HTTP handler id" - ) + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown HTTP handler id" + ), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -3043,12 +4185,53 @@ public static SpacetimeDB.Internal.Errno __call_view__( ulong sender_3, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.ViewCount + ) + return global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.CallLocalView( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + localId -= global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .ViewCount; + return UnknownViewId(id); +#else + return CallLocalView(id, sender_0, sender_1, sender_2, sender_3, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink ) => id switch { 0 => __call_view_0(sender_0, sender_1, sender_2, sender_3, args, sink), 1 => __call_view_1(sender_0, sender_1, sender_2, sender_3, args, sink), - _ => UnknownViewId(id) + _ => UnknownViewId(id), }; #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER @@ -3058,11 +4241,48 @@ public static SpacetimeDB.Internal.Errno __call_view_anon__( int id, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownAnonymousViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .AnonymousViewCount + ) + return global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.CallLocalAnonymousView( + localId, + args, + sink + ); + localId -= global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .AnonymousViewCount; + return UnknownAnonymousViewId(id); +#else + return CallLocalAnonymousView(id, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink ) => id switch { 0 => __call_view_anon_0(args, sink), - _ => UnknownAnonymousViewId(id) + _ => UnknownAnonymousViewId(id), }; private static SpacetimeDB.Internal.Errno UnknownViewId(int id) diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#MultiTableRow.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#MultiTableRow.verified.cs index 7a801bc3b6e..d5786199b4b 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#MultiTableRow.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#MultiTableRow.verified.cs @@ -54,7 +54,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar { new("Name", NameRW.GetAlgebraicType(registrar)), new("Foo", FooRW.GetAlgebraicType(registrar)), - new("Bar", BarRW.GetAlgebraicType(registrar)) + new("Bar", BarRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#PublicTable.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#PublicTable.verified.cs index f30b7f9d6a6..66eb1f4dfe6 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#PublicTable.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#PublicTable.verified.cs @@ -165,7 +165,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new( "NullableReferenceField", NullableReferenceFieldRW.GetAlgebraicType(registrar) - ) + ), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#RegressionMultipleUniqueIndexesHadSameName.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#RegressionMultipleUniqueIndexesHadSameName.verified.cs index bf52d45ea00..08d5589debd 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#RegressionMultipleUniqueIndexesHadSameName.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#RegressionMultipleUniqueIndexesHadSameName.verified.cs @@ -55,7 +55,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new SpacetimeDB.BSATN.AggregateElement[] { new("Unique1", Unique1RW.GetAlgebraicType(registrar)), - new("Unique2", Unique2RW.GetAlgebraicType(registrar)) + new("Unique2", Unique2RW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#Timers.SendMessageTimer.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#Timers.SendMessageTimer.verified.cs index de0599768a1..90065b14a30 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#Timers.SendMessageTimer.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module#Timers.SendMessageTimer.verified.cs @@ -57,7 +57,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar { new("ScheduledId", ScheduledIdRW.GetAlgebraicType(registrar)), new("ScheduledAt", ScheduledAtRW.GetAlgebraicType(registrar)), - new("Text", TextRW.GetAlgebraicType(registrar)) + new("Text", TextRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#BTreeMultiColumn.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#BTreeMultiColumn.verified.cs new file mode 100644 index 00000000000..6b55693551c --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#BTreeMultiColumn.verified.cs @@ -0,0 +1,117 @@ +//HintName: BTreeMultiColumn.cs +// +#nullable enable + +partial struct BTreeMultiColumn + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + X = BSATN.XRW.Read(reader); + Y = BSATN.YRW.Read(reader); + Z = BSATN.ZRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.XRW.Write(writer, X); + BSATN.YRW.Write(writer, Y); + BSATN.ZRW.Write(writer, Z); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"BTreeMultiColumn {{ X = {SpacetimeDB.BSATN.StringUtil.GenericToString(X)}, Y = {SpacetimeDB.BSATN.StringUtil.GenericToString(Y)}, Z = {SpacetimeDB.BSATN.StringUtil.GenericToString(Z)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.U32 XRW = new(); + internal static readonly SpacetimeDB.BSATN.U32 YRW = new(); + internal static readonly SpacetimeDB.BSATN.U32 ZRW = new(); + + public BTreeMultiColumn Read(System.IO.BinaryReader reader) + { + var ___result = new BTreeMultiColumn(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, BTreeMultiColumn value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("X", XRW.GetAlgebraicType(registrar)), + new("Y", YRW.GetAlgebraicType(registrar)), + new("Z", ZRW.GetAlgebraicType(registrar)), + } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashX = X.GetHashCode(); + var ___hashY = Y.GetHashCode(); + var ___hashZ = Z.GetHashCode(); + return ___hashX ^ ___hashY ^ ___hashZ; + } + +#nullable enable + public bool Equals(BTreeMultiColumn that) + { + var ___eqX = this.X.Equals(that.X); + var ___eqY = this.Y.Equals(that.Y); + var ___eqZ = this.Z.Equals(that.Z); + return ___eqX && ___eqY && ___eqZ; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as BTreeMultiColumn?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(BTreeMultiColumn this_, BTreeMultiColumn that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(BTreeMultiColumn this_, BTreeMultiColumn that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // BTreeMultiColumn diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#BTreeViews.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#BTreeViews.verified.cs new file mode 100644 index 00000000000..c31ba82463d --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#BTreeViews.verified.cs @@ -0,0 +1,120 @@ +//HintName: BTreeViews.cs +// +#nullable enable + +partial struct BTreeViews : System.IEquatable, SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + Id = BSATN.IdRW.Read(reader); + X = BSATN.XRW.Read(reader); + Y = BSATN.YRW.Read(reader); + Faction = BSATN.FactionRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.IdRW.Write(writer, Id); + BSATN.XRW.Write(writer, X); + BSATN.YRW.Write(writer, Y); + BSATN.FactionRW.Write(writer, Faction); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"BTreeViews {{ Id = {SpacetimeDB.BSATN.StringUtil.GenericToString(Id)}, X = {SpacetimeDB.BSATN.StringUtil.GenericToString(X)}, Y = {SpacetimeDB.BSATN.StringUtil.GenericToString(Y)}, Faction = {SpacetimeDB.BSATN.StringUtil.GenericToString(Faction)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.Identity.BSATN IdRW = new(); + internal static readonly SpacetimeDB.BSATN.U32 XRW = new(); + internal static readonly SpacetimeDB.BSATN.U32 YRW = new(); + internal static readonly SpacetimeDB.BSATN.String FactionRW = new(); + + public BTreeViews Read(System.IO.BinaryReader reader) + { + var ___result = new BTreeViews(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, BTreeViews value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType(_ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("Id", IdRW.GetAlgebraicType(registrar)), + new("X", XRW.GetAlgebraicType(registrar)), + new("Y", YRW.GetAlgebraicType(registrar)), + new("Faction", FactionRW.GetAlgebraicType(registrar)), + } + )); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashId = Id.GetHashCode(); + var ___hashX = X.GetHashCode(); + var ___hashY = Y.GetHashCode(); + var ___hashFaction = Faction == null ? 0 : Faction.GetHashCode(); + return ___hashId ^ ___hashX ^ ___hashY ^ ___hashFaction; + } + +#nullable enable + public bool Equals(BTreeViews that) + { + var ___eqId = this.Id.Equals(that.Id); + var ___eqX = this.X.Equals(that.X); + var ___eqY = this.Y.Equals(that.Y); + var ___eqFaction = + this.Faction == null ? that.Faction == null : this.Faction.Equals(that.Faction); + return ___eqId && ___eqX && ___eqY && ___eqFaction; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as BTreeViews?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(BTreeViews this_, BTreeViews that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(BTreeViews this_, BTreeViews that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // BTreeViews diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#FFI.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#FFI.verified.cs new file mode 100644 index 00000000000..395725f2581 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#FFI.verified.cs @@ -0,0 +1,4675 @@ +//HintName: FFI.cs +// +#nullable enable +// .NET 8 generates a module-local LocalReadOnly which shadows the runtime shell. +#pragma warning disable CS0436 +#pragma warning disable STDB_UNSTABLE + +#if NET10_0_OR_GREATER +global using SpacetimeDB.Generated.server_D513E4815F57969C; +#endif +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Internal = SpacetimeDB.Internal; +using TxContext = SpacetimeDB.Internal.TxContext; +#if NET10_0_OR_GREATER +[assembly: global::SpacetimeDB.ModuleDescriptorAttribute( + typeof(global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor) +)] + +#endif + +namespace SpacetimeDB +{ +#if !NET10_0_OR_GREATER + internal readonly struct BTreeMultiColumnCols + { + public readonly global::SpacetimeDB.Col X; + public readonly global::SpacetimeDB.Col Y; + public readonly global::SpacetimeDB.Col Z; + + internal BTreeMultiColumnCols(string tableName) + { + X = new global::SpacetimeDB.Col(tableName, "X"); + Y = new global::SpacetimeDB.Col(tableName, "Y"); + Z = new global::SpacetimeDB.Col(tableName, "Z"); + } + } + + internal readonly struct BTreeMultiColumnIxCols + { + public readonly global::SpacetimeDB.IxCol X; + public readonly global::SpacetimeDB.IxCol Y; + public readonly global::SpacetimeDB.IxCol Z; + + internal BTreeMultiColumnIxCols(string tableName) + { + X = new global::SpacetimeDB.IxCol(tableName, "X"); + Y = new global::SpacetimeDB.IxCol(tableName, "Y"); + Z = new global::SpacetimeDB.IxCol(tableName, "Z"); + } + } + + public readonly partial struct QueryBuilder + { + internal global::SpacetimeDB.Table< + global::BTreeMultiColumn, + BTreeMultiColumnCols, + BTreeMultiColumnIxCols + > BTreeMultiColumn() => + new( + "BTreeMultiColumn", + new BTreeMultiColumnCols("BTreeMultiColumn"), + new BTreeMultiColumnIxCols("BTreeMultiColumn") + ); + } + + internal readonly struct BTreeViewsCols + { + public readonly global::SpacetimeDB.Col Id; + public readonly global::SpacetimeDB.Col X; + public readonly global::SpacetimeDB.Col Y; + public readonly global::SpacetimeDB.Col Faction; + + internal BTreeViewsCols(string tableName) + { + Id = new global::SpacetimeDB.Col( + tableName, + "Id" + ); + X = new global::SpacetimeDB.Col(tableName, "X"); + Y = new global::SpacetimeDB.Col(tableName, "Y"); + Faction = new global::SpacetimeDB.Col(tableName, "Faction"); + } + } + + internal readonly struct BTreeViewsIxCols + { + public readonly global::SpacetimeDB.IxCol Id; + public readonly global::SpacetimeDB.IxCol X; + public readonly global::SpacetimeDB.IxCol Y; + public readonly global::SpacetimeDB.IxCol Faction; + + internal BTreeViewsIxCols(string tableName) + { + Id = new global::SpacetimeDB.IxCol( + tableName, + "Id" + ); + X = new global::SpacetimeDB.IxCol(tableName, "X"); + Y = new global::SpacetimeDB.IxCol(tableName, "Y"); + Faction = new global::SpacetimeDB.IxCol( + tableName, + "Faction" + ); + } + } + + public readonly partial struct QueryBuilder + { + internal global::SpacetimeDB.Table< + global::BTreeViews, + BTreeViewsCols, + BTreeViewsIxCols + > BTreeViews() => + new("BTreeViews", new BTreeViewsCols("BTreeViews"), new BTreeViewsIxCols("BTreeViews")); + } + + public readonly struct MultiTable1Cols + { + public readonly global::SpacetimeDB.Col Name; + public readonly global::SpacetimeDB.Col Foo; + public readonly global::SpacetimeDB.Col Bar; + + internal MultiTable1Cols(string tableName) + { + Name = new global::SpacetimeDB.Col(tableName, "Name"); + Foo = new global::SpacetimeDB.Col(tableName, "Foo"); + Bar = new global::SpacetimeDB.Col(tableName, "Bar"); + } + } + + public readonly struct MultiTable1IxCols + { + public readonly global::SpacetimeDB.IxCol Name; + public readonly global::SpacetimeDB.IxCol Foo; + + internal MultiTable1IxCols(string tableName) + { + Name = new global::SpacetimeDB.IxCol(tableName, "Name"); + Foo = new global::SpacetimeDB.IxCol(tableName, "Foo"); + } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::MultiTableRow, + MultiTable1Cols, + MultiTable1IxCols + > MultiTable1() => + new( + "MultiTable1", + new MultiTable1Cols("MultiTable1"), + new MultiTable1IxCols("MultiTable1") + ); + } + + public readonly struct MultiTable2Cols + { + public readonly global::SpacetimeDB.Col Name; + public readonly global::SpacetimeDB.Col Foo; + public readonly global::SpacetimeDB.Col Bar; + + internal MultiTable2Cols(string tableName) + { + Name = new global::SpacetimeDB.Col(tableName, "Name"); + Foo = new global::SpacetimeDB.Col(tableName, "Foo"); + Bar = new global::SpacetimeDB.Col(tableName, "Bar"); + } + } + + public readonly struct MultiTable2IxCols + { + internal MultiTable2IxCols(string tableName) { } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::MultiTableRow, + MultiTable2Cols, + MultiTable2IxCols + > MultiTable2() => + new( + "MultiTable2", + new MultiTable2Cols("MultiTable2"), + new MultiTable2IxCols("MultiTable2") + ); + } + + public readonly struct PrivateTableCols + { + internal PrivateTableCols(string tableName) { } + } + + public readonly struct PrivateTableIxCols + { + internal PrivateTableIxCols(string tableName) { } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::PrivateTable, + PrivateTableCols, + PrivateTableIxCols + > PrivateTable() => + new( + "PrivateTable", + new PrivateTableCols("PrivateTable"), + new PrivateTableIxCols("PrivateTable") + ); + } + + public readonly struct PublicTableCols + { + public readonly global::SpacetimeDB.Col Id; + public readonly global::SpacetimeDB.Col ByteField; + public readonly global::SpacetimeDB.Col UshortField; + public readonly global::SpacetimeDB.Col UintField; + public readonly global::SpacetimeDB.Col UlongField; + public readonly global::SpacetimeDB.Col UInt128Field; + public readonly global::SpacetimeDB.Col U128Field; + public readonly global::SpacetimeDB.Col U256Field; + public readonly global::SpacetimeDB.Col SbyteField; + public readonly global::SpacetimeDB.Col ShortField; + public readonly global::SpacetimeDB.Col IntField; + public readonly global::SpacetimeDB.Col LongField; + public readonly global::SpacetimeDB.Col Int128Field; + public readonly global::SpacetimeDB.Col I128Field; + public readonly global::SpacetimeDB.Col I256Field; + public readonly global::SpacetimeDB.Col BoolField; + public readonly global::SpacetimeDB.Col FloatField; + public readonly global::SpacetimeDB.Col DoubleField; + public readonly global::SpacetimeDB.Col StringField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + SpacetimeDB.Identity + > IdentityField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + SpacetimeDB.ConnectionId + > ConnectionIdField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + CustomStruct + > CustomStructField; + public readonly global::SpacetimeDB.Col CustomClassField; + public readonly global::SpacetimeDB.Col CustomEnumField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + CustomTaggedEnum + > CustomTaggedEnumField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + System.Collections.Generic.List + > ListField; + public readonly global::SpacetimeDB.Col NullableValueField; + public readonly global::SpacetimeDB.Col NullableReferenceField; + + internal PublicTableCols(string tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "Id"); + ByteField = new global::SpacetimeDB.Col( + tableName, + "ByteField" + ); + UshortField = new global::SpacetimeDB.Col( + tableName, + "UshortField" + ); + UintField = new global::SpacetimeDB.Col( + tableName, + "UintField" + ); + UlongField = new global::SpacetimeDB.Col( + tableName, + "UlongField" + ); + UInt128Field = new global::SpacetimeDB.Col( + tableName, + "UInt128Field" + ); + U128Field = new global::SpacetimeDB.Col( + tableName, + "U128Field" + ); + U256Field = new global::SpacetimeDB.Col( + tableName, + "U256Field" + ); + SbyteField = new global::SpacetimeDB.Col( + tableName, + "SbyteField" + ); + ShortField = new global::SpacetimeDB.Col( + tableName, + "ShortField" + ); + IntField = new global::SpacetimeDB.Col(tableName, "IntField"); + LongField = new global::SpacetimeDB.Col( + tableName, + "LongField" + ); + Int128Field = new global::SpacetimeDB.Col( + tableName, + "Int128Field" + ); + I128Field = new global::SpacetimeDB.Col( + tableName, + "I128Field" + ); + I256Field = new global::SpacetimeDB.Col( + tableName, + "I256Field" + ); + BoolField = new global::SpacetimeDB.Col( + tableName, + "BoolField" + ); + FloatField = new global::SpacetimeDB.Col( + tableName, + "FloatField" + ); + DoubleField = new global::SpacetimeDB.Col( + tableName, + "DoubleField" + ); + StringField = new global::SpacetimeDB.Col( + tableName, + "StringField" + ); + IdentityField = new global::SpacetimeDB.Col( + tableName, + "IdentityField" + ); + ConnectionIdField = new global::SpacetimeDB.Col< + global::PublicTable, + SpacetimeDB.ConnectionId + >(tableName, "ConnectionIdField"); + CustomStructField = new global::SpacetimeDB.Col( + tableName, + "CustomStructField" + ); + CustomClassField = new global::SpacetimeDB.Col( + tableName, + "CustomClassField" + ); + CustomEnumField = new global::SpacetimeDB.Col( + tableName, + "CustomEnumField" + ); + CustomTaggedEnumField = new global::SpacetimeDB.Col< + global::PublicTable, + CustomTaggedEnum + >(tableName, "CustomTaggedEnumField"); + ListField = new global::SpacetimeDB.Col< + global::PublicTable, + System.Collections.Generic.List + >(tableName, "ListField"); + NullableValueField = new global::SpacetimeDB.Col( + tableName, + "NullableValueField" + ); + NullableReferenceField = new global::SpacetimeDB.Col( + tableName, + "NullableReferenceField" + ); + } + } + + public readonly struct PublicTableIxCols + { + public readonly global::SpacetimeDB.IxCol Id; + + internal PublicTableIxCols(string tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "Id"); + } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::PublicTable, + PublicTableCols, + PublicTableIxCols + > PublicTable() => + new( + "PublicTable", + new PublicTableCols("PublicTable"), + new PublicTableIxCols("PublicTable") + ); + } + + internal readonly struct RegressionMultipleUniqueIndexesHadSameNameCols + { + public readonly global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + > Unique1; + public readonly global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + > Unique2; + + internal RegressionMultipleUniqueIndexesHadSameNameCols(string tableName) + { + Unique1 = new global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + >(tableName, "Unique1"); + Unique2 = new global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + >(tableName, "Unique2"); + } + } + + internal readonly struct RegressionMultipleUniqueIndexesHadSameNameIxCols + { + internal RegressionMultipleUniqueIndexesHadSameNameIxCols(string tableName) { } + } + + public readonly partial struct QueryBuilder + { + internal global::SpacetimeDB.Table< + global::RegressionMultipleUniqueIndexesHadSameName, + RegressionMultipleUniqueIndexesHadSameNameCols, + RegressionMultipleUniqueIndexesHadSameNameIxCols + > RegressionMultipleUniqueIndexesHadSameName() => + new( + "RegressionMultipleUniqueIndexesHadSameName", + new RegressionMultipleUniqueIndexesHadSameNameCols( + "RegressionMultipleUniqueIndexesHadSameName" + ), + new RegressionMultipleUniqueIndexesHadSameNameIxCols( + "RegressionMultipleUniqueIndexesHadSameName" + ) + ); + } + + public readonly struct SendMessageTimerCols + { + public readonly global::SpacetimeDB.Col ScheduledId; + public readonly global::SpacetimeDB.Col< + global::Timers.SendMessageTimer, + SpacetimeDB.ScheduleAt + > ScheduledAt; + public readonly global::SpacetimeDB.Col Text; + + internal SendMessageTimerCols(string tableName) + { + ScheduledId = new global::SpacetimeDB.Col( + tableName, + "ScheduledId" + ); + ScheduledAt = new global::SpacetimeDB.Col< + global::Timers.SendMessageTimer, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduledAt"); + Text = new global::SpacetimeDB.Col( + tableName, + "Text" + ); + } + } + + public readonly struct SendMessageTimerIxCols + { + public readonly global::SpacetimeDB.IxCol< + global::Timers.SendMessageTimer, + ulong + > ScheduledId; + + internal SendMessageTimerIxCols(string tableName) + { + ScheduledId = new global::SpacetimeDB.IxCol( + tableName, + "ScheduledId" + ); + } + } + + public readonly partial struct QueryBuilder + { + public global::SpacetimeDB.Table< + global::Timers.SendMessageTimer, + SendMessageTimerCols, + SendMessageTimerIxCols + > SendMessageTimer() => + new( + "SendMessageTimer", + new SendMessageTimerCols("SendMessageTimer"), + new SendMessageTimerIxCols("SendMessageTimer") + ); + } +#endif + + internal static class Handlers { } + +#if !NET10_0_OR_GREATER + public sealed record ReducerContext : DbContext, Internal.IReducerContext + { + public global::SpacetimeDB.ModuleEnvironment Env => default; + public readonly Identity Sender; + public readonly ConnectionId? ConnectionId; + public readonly Random Rng; + public readonly Timestamp Timestamp; + public readonly AuthCtx SenderAuth; + + // **Note:** must be 0..=u32::MAX + internal int CounterUuid; + public Identity DatabaseIdentity => Internal.IReducerContext.GetDatabaseIdentity(); + + // We keep this property for compatibility with existing module code. + [global::System.Obsolete( + "ReducerContext.Identity is deprecated. Use DatabaseIdentity instead." + )] + public Identity Identity => DatabaseIdentity; + + internal ReducerContext( + Identity identity, + ConnectionId? connectionId, + Random random, + Timestamp time, + AuthCtx? senderAuth = null + ) + { + Sender = identity; + ConnectionId = connectionId; + Rng = random; + Timestamp = time; + SenderAuth = senderAuth ?? AuthCtx.BuildFromSystemTables(connectionId, identity); + CounterUuid = 0; + } + + /// + /// Create a new random `v4` using the built-in RNG. + /// + /// + /// This method fills the random bytes using the context RNG. + /// + /// + /// + /// var uuid = ctx.NewUuidV4(); + /// Log.Info(uuid); + /// + /// + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + /// + /// Create a new sortable `v7` using the built-in RNG, monotonic counter, + /// and timestamp. + /// + /// + /// A newly generated `v7` that is monotonically ordered + /// and suitable for use as a primary key or for ordered storage. + /// + /// + /// Thrown if generation fails. + /// + /// + /// + /// [SpacetimeDB.Reducer] + /// public static Guid GenerateUuidV7(ReducerContext ctx) + /// { + /// Guid uuid = ctx.NewUuidV7(); + /// Log.Info(uuid); + /// } + /// + /// + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } + } + + public sealed partial class ProcedureContext : global::SpacetimeDB.ProcedureContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + private readonly Local _db = new(); + + internal ProcedureContext( + Identity identity, + ConnectionId? connectionId, + Random random, + Timestamp time + ) + : base(identity, connectionId, random, time) { } + + protected override global::SpacetimeDB.LocalBase CreateLocal() => _db; + + protected override global::SpacetimeDB.ProcedureTxContextBase CreateTxContext( + Internal.TxContext inner + ) => _cached ??= new ProcedureTxContext(inner); + + private ProcedureTxContext? _cached; + + public Local Db => _db; + + public TResult WithTx(Func body) => + base.WithTx(tx => body((ProcedureTxContext)tx)); + + public TxOutcome TryWithTx( + Func> body + ) + where TError : Exception => base.TryWithTx(tx => body((ProcedureTxContext)tx)); + + /// + /// Create a new random `v4` using the built-in RNG. + /// + /// + /// This method fills the random bytes using the context RNG. + /// + /// + /// + /// var uuid = ctx.NewUuidV4(); + /// Log.Info(uuid); + /// + /// + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + /// + /// Create a new sortable `v7` using the built-in RNG, monotonic counter, + /// and timestamp. + /// + /// + /// A newly generated `v7` that is monotonically ordered + /// and suitable for use as a primary key or for ordered storage. + /// + /// + /// Thrown if UUID generation fails. + /// + /// + /// + /// [SpacetimeDB.Procedure] + /// public static Guid GenerateUuidV7(ReducerContext ctx) + /// { + /// Guid uuid = ctx.NewUuidV7(); + /// Log.Info(uuid); + /// } + /// + /// + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } + } + + public sealed partial class HandlerContext : global::SpacetimeDB.HandlerContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + private readonly Local _db = new(); + + internal HandlerContext(Random random, Timestamp time) + : base(random, time) { } + + protected override global::SpacetimeDB.LocalBase CreateLocal() => _db; + + protected override global::SpacetimeDB.HandlerTxContextBase CreateTxContext( + Internal.TxContext inner + ) => _cached ??= new HandlerTxContext(inner); + + private HandlerTxContext? _cached; + + [Experimental("STDB_UNSTABLE")] + public TResult WithTx(Func body) => + base.WithTx(tx => body((HandlerTxContext)tx)); + + [Experimental("STDB_UNSTABLE")] + public TxOutcome TryWithTx( + Func> body + ) + where TError : Exception => base.TryWithTx(tx => body((HandlerTxContext)tx)); + + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } + } + + public sealed class ProcedureTxContext : global::SpacetimeDB.ProcedureTxContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + + internal ProcedureTxContext(Internal.TxContext inner) + : base(inner) { } + + public new Local Db => (Local)base.Db; + } + + [Experimental("STDB_UNSTABLE")] + public sealed class HandlerTxContext : global::SpacetimeDB.HandlerTxContextBase + { + public new global::SpacetimeDB.ModuleEnvironment Env => default; + + internal HandlerTxContext(Internal.TxContext inner) + : base(inner) { } + + public new Local Db => (Local)base.Db; + } + + public sealed class Local : global::SpacetimeDB.LocalBase + { + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.BTreeMultiColumn BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.BTreeViews BTreeViews => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.MultiTable1 MultiTable1 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.MultiTable2 MultiTable2 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.PrivateTable PrivateTable => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.PublicTable PublicTable => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.RegressionMultipleUniqueIndexesHadSameName RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.SendMessageTimer SendMessageTimer => + new(); + } + + public sealed record ViewContext : DbContext, Internal.IViewContext + { + public Identity Sender { get; } + + public global::SpacetimeDB.ModuleEnvironment Env => default; + public QueryBuilder From => default; + + internal ViewContext(Identity sender, Internal.LocalReadOnly db) + : base(db) + { + Sender = sender; + } + } + + public sealed record AnonymousViewContext + : DbContext, + Internal.IAnonymousViewContext + { + public global::SpacetimeDB.ModuleEnvironment Env => default; + public QueryBuilder From => default; + + internal AnonymousViewContext(Internal.LocalReadOnly db) + : base(db) { } + } +#endif +} + +#if NET10_0_OR_GREATER +namespace SpacetimeDB.Generated.server_D513E4815F57969C +{ + public static partial class AssemblyDescriptor + { + public const string? CaseConversionPolicy = null; + public const string RootOnlyDeclarations = + "row-level security filters, environment variables, lifecycle reducer Timers.Init (Init)"; + public const int ReducerCount = 6; + public const int ProcedureCount = 0; + public const int HttpHandlerCount = 0; + public const int ViewCount = 2; + public const int AnonymousViewCount = 1; + + public static global::SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink error + ) => + global::ModuleRegistration.CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink result_sink + ) => + global::ModuleRegistration.CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource request, + global::SpacetimeDB.Internal.BytesSource request_body, + global::SpacetimeDB.Internal.BytesSink response_sink, + global::SpacetimeDB.Internal.BytesSink response_body_sink + ) => + global::ModuleRegistration.CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => + global::ModuleRegistration.CallLocalView( + id, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => global::ModuleRegistration.CallLocalAnonymousView(id, args, sink); + + public static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) => global::ModuleRegistration.Register(builder, httpBuilder); + + public readonly struct Tables + { + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.BTreeMultiColumn BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.BTreeViews BTreeViews => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.MultiTable1 MultiTable1 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.MultiTable2 MultiTable2 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.PrivateTable PrivateTable => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.PublicTable PublicTable => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.RegressionMultipleUniqueIndexesHadSameName RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.SendMessageTimer SendMessageTimer => + new(); + } + + public readonly struct ReadOnlyTables + { + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.BTreeMultiColumnReadOnly BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.BTreeViewsReadOnly BTreeViews => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.MultiTable1ReadOnly MultiTable1 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.MultiTable2ReadOnly MultiTable2 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.PrivateTableReadOnly PrivateTable => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.PublicTableReadOnly PublicTable => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.RegressionMultipleUniqueIndexesHadSameNameReadOnly RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.SendMessageTimerReadOnly SendMessageTimer => + new(); + } + + public readonly partial struct Queries { } + } + + public static class LocalTableExtensions + { + extension(global::SpacetimeDB.Local db) + { + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.BTreeMultiColumn BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.BTreeViews BTreeViews => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.MultiTable1 MultiTable1 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.MultiTable2 MultiTable2 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.PrivateTable PrivateTable => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.PublicTable PublicTable => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.RegressionMultipleUniqueIndexesHadSameName RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.SendMessageTimer SendMessageTimer => + new(); + } + } + + public static class ReadOnlyTableExtensions + { + extension(global::SpacetimeDB.Internal.LocalReadOnly db) + { + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.BTreeMultiColumnReadOnly BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.BTreeViewsReadOnly BTreeViews => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.MultiTable1ReadOnly MultiTable1 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.MultiTable2ReadOnly MultiTable2 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.PrivateTableReadOnly PrivateTable => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.PublicTableReadOnly PublicTable => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.RegressionMultipleUniqueIndexesHadSameNameReadOnly RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.SendMessageTimerReadOnly SendMessageTimer => + new(); + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) { } + } + + internal readonly struct BTreeMultiColumnCols + { + public readonly global::SpacetimeDB.Col X; + public readonly global::SpacetimeDB.Col Y; + public readonly global::SpacetimeDB.Col Z; + + internal BTreeMultiColumnCols(global::SpacetimeDB.SqlTableName tableName) + { + X = new global::SpacetimeDB.Col(tableName, "X"); + Y = new global::SpacetimeDB.Col(tableName, "Y"); + Z = new global::SpacetimeDB.Col(tableName, "Z"); + } + } + + internal readonly struct BTreeMultiColumnIxCols + { + public readonly global::SpacetimeDB.IxCol X; + public readonly global::SpacetimeDB.IxCol Y; + public readonly global::SpacetimeDB.IxCol Z; + + internal BTreeMultiColumnIxCols(global::SpacetimeDB.SqlTableName tableName) + { + X = new global::SpacetimeDB.IxCol(tableName, "X"); + Y = new global::SpacetimeDB.IxCol(tableName, "Y"); + Z = new global::SpacetimeDB.IxCol(tableName, "Z"); + } + } + + public static partial class AssemblyDescriptor + { + private static class BTreeMultiColumnSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeMultiColumn" + ); + + // Prevent eager initialization before the root installs namespace placements. + static BTreeMultiColumnSqlNameCache() { } + } + + public readonly partial struct Queries + { + internal global::SpacetimeDB.Table< + global::BTreeMultiColumn, + BTreeMultiColumnCols, + BTreeMultiColumnIxCols + > BTreeMultiColumn() + { + var tableName = BTreeMultiColumnSqlNameCache.Name; + return new( + tableName, + new BTreeMultiColumnCols(tableName), + new BTreeMultiColumnIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + internal global::SpacetimeDB.Table< + global::BTreeMultiColumn, + BTreeMultiColumnCols, + BTreeMultiColumnIxCols + > BTreeMultiColumn() => new AssemblyDescriptor.Queries().BTreeMultiColumn(); + } + } + + internal readonly struct BTreeViewsCols + { + public readonly global::SpacetimeDB.Col Id; + public readonly global::SpacetimeDB.Col X; + public readonly global::SpacetimeDB.Col Y; + public readonly global::SpacetimeDB.Col Faction; + + internal BTreeViewsCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col( + tableName, + "Id" + ); + X = new global::SpacetimeDB.Col(tableName, "X"); + Y = new global::SpacetimeDB.Col(tableName, "Y"); + Faction = new global::SpacetimeDB.Col(tableName, "Faction"); + } + } + + internal readonly struct BTreeViewsIxCols + { + public readonly global::SpacetimeDB.IxCol Id; + public readonly global::SpacetimeDB.IxCol X; + public readonly global::SpacetimeDB.IxCol Y; + public readonly global::SpacetimeDB.IxCol Faction; + + internal BTreeViewsIxCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.IxCol( + tableName, + "Id" + ); + X = new global::SpacetimeDB.IxCol(tableName, "X"); + Y = new global::SpacetimeDB.IxCol(tableName, "Y"); + Faction = new global::SpacetimeDB.IxCol( + tableName, + "Faction" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class BTreeViewsSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeViews" + ); + + // Prevent eager initialization before the root installs namespace placements. + static BTreeViewsSqlNameCache() { } + } + + public readonly partial struct Queries + { + internal global::SpacetimeDB.Table< + global::BTreeViews, + BTreeViewsCols, + BTreeViewsIxCols + > BTreeViews() + { + var tableName = BTreeViewsSqlNameCache.Name; + return new( + tableName, + new BTreeViewsCols(tableName), + new BTreeViewsIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + internal global::SpacetimeDB.Table< + global::BTreeViews, + BTreeViewsCols, + BTreeViewsIxCols + > BTreeViews() => new AssemblyDescriptor.Queries().BTreeViews(); + } + } + + public readonly struct MultiTable1Cols + { + public readonly global::SpacetimeDB.Col Name; + public readonly global::SpacetimeDB.Col Foo; + public readonly global::SpacetimeDB.Col Bar; + + internal MultiTable1Cols(global::SpacetimeDB.SqlTableName tableName) + { + Name = new global::SpacetimeDB.Col(tableName, "Name"); + Foo = new global::SpacetimeDB.Col(tableName, "Foo"); + Bar = new global::SpacetimeDB.Col(tableName, "Bar"); + } + } + + public readonly struct MultiTable1IxCols + { + public readonly global::SpacetimeDB.IxCol Name; + public readonly global::SpacetimeDB.IxCol Foo; + + internal MultiTable1IxCols(global::SpacetimeDB.SqlTableName tableName) + { + Name = new global::SpacetimeDB.IxCol(tableName, "Name"); + Foo = new global::SpacetimeDB.IxCol(tableName, "Foo"); + } + } + + public static partial class AssemblyDescriptor + { + private static class MultiTable1SqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable1" + ); + + // Prevent eager initialization before the root installs namespace placements. + static MultiTable1SqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::MultiTableRow, + MultiTable1Cols, + MultiTable1IxCols + > MultiTable1() + { + var tableName = MultiTable1SqlNameCache.Name; + return new( + tableName, + new MultiTable1Cols(tableName), + new MultiTable1IxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::MultiTableRow, + MultiTable1Cols, + MultiTable1IxCols + > MultiTable1() => new AssemblyDescriptor.Queries().MultiTable1(); + } + } + + public readonly struct MultiTable2Cols + { + public readonly global::SpacetimeDB.Col Name; + public readonly global::SpacetimeDB.Col Foo; + public readonly global::SpacetimeDB.Col Bar; + + internal MultiTable2Cols(global::SpacetimeDB.SqlTableName tableName) + { + Name = new global::SpacetimeDB.Col(tableName, "Name"); + Foo = new global::SpacetimeDB.Col(tableName, "Foo"); + Bar = new global::SpacetimeDB.Col(tableName, "Bar"); + } + } + + public readonly struct MultiTable2IxCols + { + internal MultiTable2IxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class MultiTable2SqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable2" + ); + + // Prevent eager initialization before the root installs namespace placements. + static MultiTable2SqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::MultiTableRow, + MultiTable2Cols, + MultiTable2IxCols + > MultiTable2() + { + var tableName = MultiTable2SqlNameCache.Name; + return new( + tableName, + new MultiTable2Cols(tableName), + new MultiTable2IxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::MultiTableRow, + MultiTable2Cols, + MultiTable2IxCols + > MultiTable2() => new AssemblyDescriptor.Queries().MultiTable2(); + } + } + + public readonly struct PrivateTableCols + { + internal PrivateTableCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public readonly struct PrivateTableIxCols + { + internal PrivateTableIxCols(global::SpacetimeDB.SqlTableName tableName) { } + } + + public static partial class AssemblyDescriptor + { + private static class PrivateTableSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "PrivateTable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PrivateTableSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::PrivateTable, + PrivateTableCols, + PrivateTableIxCols + > PrivateTable() + { + var tableName = PrivateTableSqlNameCache.Name; + return new( + tableName, + new PrivateTableCols(tableName), + new PrivateTableIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::PrivateTable, + PrivateTableCols, + PrivateTableIxCols + > PrivateTable() => new AssemblyDescriptor.Queries().PrivateTable(); + } + } + + public readonly struct PublicTableCols + { + public readonly global::SpacetimeDB.Col Id; + public readonly global::SpacetimeDB.Col ByteField; + public readonly global::SpacetimeDB.Col UshortField; + public readonly global::SpacetimeDB.Col UintField; + public readonly global::SpacetimeDB.Col UlongField; + public readonly global::SpacetimeDB.Col UInt128Field; + public readonly global::SpacetimeDB.Col U128Field; + public readonly global::SpacetimeDB.Col U256Field; + public readonly global::SpacetimeDB.Col SbyteField; + public readonly global::SpacetimeDB.Col ShortField; + public readonly global::SpacetimeDB.Col IntField; + public readonly global::SpacetimeDB.Col LongField; + public readonly global::SpacetimeDB.Col Int128Field; + public readonly global::SpacetimeDB.Col I128Field; + public readonly global::SpacetimeDB.Col I256Field; + public readonly global::SpacetimeDB.Col BoolField; + public readonly global::SpacetimeDB.Col FloatField; + public readonly global::SpacetimeDB.Col DoubleField; + public readonly global::SpacetimeDB.Col StringField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + SpacetimeDB.Identity + > IdentityField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + SpacetimeDB.ConnectionId + > ConnectionIdField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + CustomStruct + > CustomStructField; + public readonly global::SpacetimeDB.Col CustomClassField; + public readonly global::SpacetimeDB.Col CustomEnumField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + CustomTaggedEnum + > CustomTaggedEnumField; + public readonly global::SpacetimeDB.Col< + global::PublicTable, + System.Collections.Generic.List + > ListField; + public readonly global::SpacetimeDB.Col NullableValueField; + public readonly global::SpacetimeDB.Col NullableReferenceField; + + internal PublicTableCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "Id"); + ByteField = new global::SpacetimeDB.Col( + tableName, + "ByteField" + ); + UshortField = new global::SpacetimeDB.Col( + tableName, + "UshortField" + ); + UintField = new global::SpacetimeDB.Col( + tableName, + "UintField" + ); + UlongField = new global::SpacetimeDB.Col( + tableName, + "UlongField" + ); + UInt128Field = new global::SpacetimeDB.Col( + tableName, + "UInt128Field" + ); + U128Field = new global::SpacetimeDB.Col( + tableName, + "U128Field" + ); + U256Field = new global::SpacetimeDB.Col( + tableName, + "U256Field" + ); + SbyteField = new global::SpacetimeDB.Col( + tableName, + "SbyteField" + ); + ShortField = new global::SpacetimeDB.Col( + tableName, + "ShortField" + ); + IntField = new global::SpacetimeDB.Col(tableName, "IntField"); + LongField = new global::SpacetimeDB.Col( + tableName, + "LongField" + ); + Int128Field = new global::SpacetimeDB.Col( + tableName, + "Int128Field" + ); + I128Field = new global::SpacetimeDB.Col( + tableName, + "I128Field" + ); + I256Field = new global::SpacetimeDB.Col( + tableName, + "I256Field" + ); + BoolField = new global::SpacetimeDB.Col( + tableName, + "BoolField" + ); + FloatField = new global::SpacetimeDB.Col( + tableName, + "FloatField" + ); + DoubleField = new global::SpacetimeDB.Col( + tableName, + "DoubleField" + ); + StringField = new global::SpacetimeDB.Col( + tableName, + "StringField" + ); + IdentityField = new global::SpacetimeDB.Col( + tableName, + "IdentityField" + ); + ConnectionIdField = new global::SpacetimeDB.Col< + global::PublicTable, + SpacetimeDB.ConnectionId + >(tableName, "ConnectionIdField"); + CustomStructField = new global::SpacetimeDB.Col( + tableName, + "CustomStructField" + ); + CustomClassField = new global::SpacetimeDB.Col( + tableName, + "CustomClassField" + ); + CustomEnumField = new global::SpacetimeDB.Col( + tableName, + "CustomEnumField" + ); + CustomTaggedEnumField = new global::SpacetimeDB.Col< + global::PublicTable, + CustomTaggedEnum + >(tableName, "CustomTaggedEnumField"); + ListField = new global::SpacetimeDB.Col< + global::PublicTable, + System.Collections.Generic.List + >(tableName, "ListField"); + NullableValueField = new global::SpacetimeDB.Col( + tableName, + "NullableValueField" + ); + NullableReferenceField = new global::SpacetimeDB.Col( + tableName, + "NullableReferenceField" + ); + } + } + + public readonly struct PublicTableIxCols + { + public readonly global::SpacetimeDB.IxCol Id; + + internal PublicTableIxCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "Id"); + } + } + + public static partial class AssemblyDescriptor + { + private static class PublicTableSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "PublicTable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PublicTableSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::PublicTable, + PublicTableCols, + PublicTableIxCols + > PublicTable() + { + var tableName = PublicTableSqlNameCache.Name; + return new( + tableName, + new PublicTableCols(tableName), + new PublicTableIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::PublicTable, + PublicTableCols, + PublicTableIxCols + > PublicTable() => new AssemblyDescriptor.Queries().PublicTable(); + } + } + + internal readonly struct RegressionMultipleUniqueIndexesHadSameNameCols + { + public readonly global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + > Unique1; + public readonly global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + > Unique2; + + internal RegressionMultipleUniqueIndexesHadSameNameCols( + global::SpacetimeDB.SqlTableName tableName + ) + { + Unique1 = new global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + >(tableName, "Unique1"); + Unique2 = new global::SpacetimeDB.Col< + global::RegressionMultipleUniqueIndexesHadSameName, + uint + >(tableName, "Unique2"); + } + } + + internal readonly struct RegressionMultipleUniqueIndexesHadSameNameIxCols + { + internal RegressionMultipleUniqueIndexesHadSameNameIxCols( + global::SpacetimeDB.SqlTableName tableName + ) { } + } + + public static partial class AssemblyDescriptor + { + private static class RegressionMultipleUniqueIndexesHadSameNameSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "RegressionMultipleUniqueIndexesHadSameName" + ); + + // Prevent eager initialization before the root installs namespace placements. + static RegressionMultipleUniqueIndexesHadSameNameSqlNameCache() { } + } + + public readonly partial struct Queries + { + internal global::SpacetimeDB.Table< + global::RegressionMultipleUniqueIndexesHadSameName, + RegressionMultipleUniqueIndexesHadSameNameCols, + RegressionMultipleUniqueIndexesHadSameNameIxCols + > RegressionMultipleUniqueIndexesHadSameName() + { + var tableName = RegressionMultipleUniqueIndexesHadSameNameSqlNameCache.Name; + return new( + tableName, + new RegressionMultipleUniqueIndexesHadSameNameCols(tableName), + new RegressionMultipleUniqueIndexesHadSameNameIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + internal global::SpacetimeDB.Table< + global::RegressionMultipleUniqueIndexesHadSameName, + RegressionMultipleUniqueIndexesHadSameNameCols, + RegressionMultipleUniqueIndexesHadSameNameIxCols + > RegressionMultipleUniqueIndexesHadSameName() => + new AssemblyDescriptor.Queries().RegressionMultipleUniqueIndexesHadSameName(); + } + } + + public readonly struct SendMessageTimerCols + { + public readonly global::SpacetimeDB.Col ScheduledId; + public readonly global::SpacetimeDB.Col< + global::Timers.SendMessageTimer, + SpacetimeDB.ScheduleAt + > ScheduledAt; + public readonly global::SpacetimeDB.Col Text; + + internal SendMessageTimerCols(global::SpacetimeDB.SqlTableName tableName) + { + ScheduledId = new global::SpacetimeDB.Col( + tableName, + "ScheduledId" + ); + ScheduledAt = new global::SpacetimeDB.Col< + global::Timers.SendMessageTimer, + SpacetimeDB.ScheduleAt + >(tableName, "ScheduledAt"); + Text = new global::SpacetimeDB.Col( + tableName, + "Text" + ); + } + } + + public readonly struct SendMessageTimerIxCols + { + public readonly global::SpacetimeDB.IxCol< + global::Timers.SendMessageTimer, + ulong + > ScheduledId; + + internal SendMessageTimerIxCols(global::SpacetimeDB.SqlTableName tableName) + { + ScheduledId = new global::SpacetimeDB.IxCol( + tableName, + "ScheduledId" + ); + } + } + + public static partial class AssemblyDescriptor + { + private static class SendMessageTimerSqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "SendMessageTimer" + ); + + // Prevent eager initialization before the root installs namespace placements. + static SendMessageTimerSqlNameCache() { } + } + + public readonly partial struct Queries + { + public global::SpacetimeDB.Table< + global::Timers.SendMessageTimer, + SendMessageTimerCols, + SendMessageTimerIxCols + > SendMessageTimer() + { + var tableName = SendMessageTimerSqlNameCache.Name; + return new( + tableName, + new SendMessageTimerCols(tableName), + new SendMessageTimerIxCols(tableName) + ); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + public global::SpacetimeDB.Table< + global::Timers.SendMessageTimer, + SendMessageTimerCols, + SendMessageTimerIxCols + > SendMessageTimer() => new AssemblyDescriptor.Queries().SendMessageTimer(); + } + } +} +#endif + +namespace SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles +{ + internal readonly struct BTreeMultiColumn + : global::SpacetimeDB.Internal.ITableView + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeMultiColumn" + ); + + public static global::BTreeMultiColumn ReadGenFields( + System.IO.BinaryReader reader, + global::BTreeMultiColumn row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(BTreeMultiColumn), + ProductTypeRef: (uint) + new global::BTreeMultiColumn.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [], + Indexes: + [ + new( + SourceName: "BTreeMultiColumn_X_Y_Z_idx_btree", + AccessorName: "Location", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0, 1, 2]) + ), + ], + Constraints: [], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + BTreeMultiColumn, + global::BTreeMultiColumn + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + BTreeMultiColumn, + global::BTreeMultiColumn + >.DoIter(); + + public global::BTreeMultiColumn Insert(global::BTreeMultiColumn row) => + global::SpacetimeDB.Internal.ITableView< + BTreeMultiColumn, + global::BTreeMultiColumn + >.DoInsert(row); + + public bool Delete(global::BTreeMultiColumn row) => + global::SpacetimeDB.Internal.ITableView< + BTreeMultiColumn, + global::BTreeMultiColumn + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + BTreeMultiColumn, + global::BTreeMultiColumn + >.DoClear(); + + internal sealed class LocationIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeMultiColumn_X_Y_Z_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static LocationIndex() { } + + public IEnumerable Filter(uint X) => + DoFilter(new SpacetimeDB.Internal.BTreeIndexBounds(X)); + + public ulong Delete(uint X) => + DoDelete(new SpacetimeDB.Internal.BTreeIndexBounds(X)); + + public IEnumerable Filter( + global::SpacetimeDB.Bound X + ) => + DoFilter(new SpacetimeDB.Internal.BTreeIndexBounds(X)); + + public ulong Delete(global::SpacetimeDB.Bound X) => + DoDelete(new SpacetimeDB.Internal.BTreeIndexBounds(X)); + + public IEnumerable Filter((uint X, uint Y) f) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public ulong Delete((uint X, uint Y) f) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public IEnumerable Filter( + (uint X, global::SpacetimeDB.Bound Y) f + ) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public ulong Delete((uint X, global::SpacetimeDB.Bound Y) f) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public IEnumerable Filter((uint X, uint Y, uint Z) f) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public ulong Delete((uint X, uint Y, uint Z) f) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public IEnumerable Filter( + (uint X, uint Y, global::SpacetimeDB.Bound Z) f + ) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public ulong Delete((uint X, uint Y, global::SpacetimeDB.Bound Z) f) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + } + + private static LocationIndex? __Location; + internal LocationIndex Location => __Location ??= new(); + } + + internal readonly struct BTreeViews + : global::SpacetimeDB.Internal.ITableView + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeViews" + ); + + public static global::BTreeViews ReadGenFields( + System.IO.BinaryReader reader, + global::BTreeViews row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(BTreeViews), + ProductTypeRef: (uint) + new global::BTreeViews.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [0], + Indexes: + [ + new( + SourceName: "BTreeViews_Id_idx_btree", + AccessorName: "Id", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + new( + SourceName: "BTreeViews_X_Y_idx_btree", + AccessorName: "Location", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1, 2]) + ), + new( + SourceName: "BTreeViews_Faction_idx_btree", + AccessorName: "Faction", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([3]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + BTreeViews, + global::BTreeViews + >.MakeUniqueConstraint(0), + ], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView.DoIter(); + + public global::BTreeViews Insert(global::BTreeViews row) => + global::SpacetimeDB.Internal.ITableView.DoInsert(row); + + public bool Delete(global::BTreeViews row) => + global::SpacetimeDB.Internal.ITableView.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView.DoClear(); + + internal sealed class IdUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + BTreeViews, + global::BTreeViews, + SpacetimeDB.Identity, + SpacetimeDB.Identity.BSATN + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeViews_Id_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdUniqueIndex() { } + + internal IdUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::BTreeViews? Find(SpacetimeDB.Identity key) => FindSingle(key); + + public global::BTreeViews Update(global::BTreeViews row) => DoUpdate(row); + } + + private static IdUniqueIndex? __Id; + internal IdUniqueIndex Id => __Id ??= new(); + + internal sealed class LocationIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeViews_X_Y_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static LocationIndex() { } + + public IEnumerable Filter(uint X) => + DoFilter(new SpacetimeDB.Internal.BTreeIndexBounds(X)); + + public ulong Delete(uint X) => + DoDelete(new SpacetimeDB.Internal.BTreeIndexBounds(X)); + + public IEnumerable Filter(global::SpacetimeDB.Bound X) => + DoFilter(new SpacetimeDB.Internal.BTreeIndexBounds(X)); + + public ulong Delete(global::SpacetimeDB.Bound X) => + DoDelete(new SpacetimeDB.Internal.BTreeIndexBounds(X)); + + public IEnumerable Filter((uint X, uint Y) f) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public ulong Delete((uint X, uint Y) f) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public IEnumerable Filter( + (uint X, global::SpacetimeDB.Bound Y) f + ) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public ulong Delete((uint X, global::SpacetimeDB.Bound Y) f) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + } + + private static LocationIndex? __Location; + internal LocationIndex Location => __Location ??= new(); + + internal sealed class FactionIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeViews_Faction_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static FactionIndex() { } + + public IEnumerable Filter(string Faction) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds( + Faction + ) + ); + + public ulong Delete(string Faction) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds( + Faction + ) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound Faction + ) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds( + Faction + ) + ); + + public ulong Delete(global::SpacetimeDB.Bound Faction) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds( + Faction + ) + ); + } + + private static FactionIndex? __Faction; + internal FactionIndex Faction => __Faction ??= new(); + } + + public readonly struct MultiTable1 + : global::SpacetimeDB.Internal.ITableView + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable1" + ); + + public static global::MultiTableRow ReadGenFields( + System.IO.BinaryReader reader, + global::MultiTableRow row + ) + { + if (row.Foo == default) + { + row.Foo = global::MultiTableRow.BSATN.FooRW.Read(reader); + } + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(MultiTable1), + ProductTypeRef: (uint) + new global::MultiTableRow.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [1], + Indexes: + [ + new( + SourceName: "MultiTable1_Foo_idx_btree", + AccessorName: "Foo", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) + ), + new( + SourceName: "MultiTable1_Name_idx_btree", + AccessorName: "Name", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + MultiTable1, + global::MultiTableRow + >.MakeUniqueConstraint(1), + ], + Sequences: + [ + global::SpacetimeDB.Internal.ITableView< + MultiTable1, + global::MultiTableRow + >.MakeSequence(1), + ], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Public, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView.DoIter(); + + public global::MultiTableRow Insert(global::MultiTableRow row) => + global::SpacetimeDB.Internal.ITableView.DoInsert( + row + ); + + public bool Delete(global::MultiTableRow row) => + global::SpacetimeDB.Internal.ITableView.DoDelete( + row + ); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView.DoClear(); + + public sealed class FooUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + MultiTable1, + global::MultiTableRow, + uint, + SpacetimeDB.BSATN.U32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable1_Foo_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static FooUniqueIndex() { } + + internal FooUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::MultiTableRow? Find(uint key) => FindSingle(key); + + public global::MultiTableRow Update(global::MultiTableRow row) => DoUpdate(row); + } + + private static FooUniqueIndex? __Foo; + public FooUniqueIndex Foo => __Foo ??= new(); + + public sealed class NameIndex() + : SpacetimeDB.Internal.IndexBase(__resolvedName) + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable1_Name_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static NameIndex() { } + + public IEnumerable Filter(string Name) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds( + Name + ) + ); + + public ulong Delete(string Name) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds( + Name + ) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound Name + ) => + DoFilter( + new SpacetimeDB.Internal.BTreeIndexBounds( + Name + ) + ); + + public ulong Delete(global::SpacetimeDB.Bound Name) => + DoDelete( + new SpacetimeDB.Internal.BTreeIndexBounds( + Name + ) + ); + } + + private static NameIndex? __Name; + public NameIndex Name => __Name ??= new(); + } + + public readonly struct MultiTable2 + : global::SpacetimeDB.Internal.ITableView + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable2" + ); + + public static global::MultiTableRow ReadGenFields( + System.IO.BinaryReader reader, + global::MultiTableRow row + ) + { + if (row.Foo == default) + { + row.Foo = global::MultiTableRow.BSATN.FooRW.Read(reader); + } + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(MultiTable2), + ProductTypeRef: (uint) + new global::MultiTableRow.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [], + Indexes: + [ + new( + SourceName: "MultiTable2_Bar_idx_btree", + AccessorName: "Bar", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([2]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + MultiTable2, + global::MultiTableRow + >.MakeUniqueConstraint(2), + ], + Sequences: + [ + global::SpacetimeDB.Internal.ITableView< + MultiTable2, + global::MultiTableRow + >.MakeSequence(1), + ], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView.DoIter(); + + public global::MultiTableRow Insert(global::MultiTableRow row) => + global::SpacetimeDB.Internal.ITableView.DoInsert( + row + ); + + public bool Delete(global::MultiTableRow row) => + global::SpacetimeDB.Internal.ITableView.DoDelete( + row + ); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView.DoClear(); + + public sealed class BarUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + MultiTable2, + global::MultiTableRow, + uint, + SpacetimeDB.BSATN.U32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable2_Bar_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static BarUniqueIndex() { } + + internal BarUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::MultiTableRow? Find(uint key) => FindSingle(key); + } + + private static BarUniqueIndex? __Bar; + public BarUniqueIndex Bar => __Bar ??= new(); + } + + public readonly struct PrivateTable + : global::SpacetimeDB.Internal.ITableView + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "PrivateTable" + ); + + public static global::PrivateTable ReadGenFields( + System.IO.BinaryReader reader, + global::PrivateTable row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(PrivateTable), + ProductTypeRef: (uint) + new global::PrivateTable.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [], + Indexes: [], + Constraints: [], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: true + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView.DoIter(); + + public global::PrivateTable Insert(global::PrivateTable row) => + global::SpacetimeDB.Internal.ITableView.DoInsert( + row + ); + + public bool Delete(global::PrivateTable row) => + global::SpacetimeDB.Internal.ITableView.DoDelete( + row + ); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView.DoClear(); + } + + public readonly struct PublicTable + : global::SpacetimeDB.Internal.ITableView + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "PublicTable" + ); + + public static global::PublicTable ReadGenFields( + System.IO.BinaryReader reader, + global::PublicTable row + ) + { + if (row.Id == default) + { + row.Id = global::PublicTable.BSATN.IdRW.Read(reader); + } + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(PublicTable), + ProductTypeRef: (uint) + new global::PublicTable.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [0], + Indexes: + [ + new( + SourceName: "PublicTable_Id_idx_btree", + AccessorName: "Id", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + PublicTable, + global::PublicTable + >.MakeUniqueConstraint(0), + ], + Sequences: + [ + global::SpacetimeDB.Internal.ITableView< + PublicTable, + global::PublicTable + >.MakeSequence(0), + ], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Public, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView.DoIter(); + + public global::PublicTable Insert(global::PublicTable row) => + global::SpacetimeDB.Internal.ITableView.DoInsert(row); + + public bool Delete(global::PublicTable row) => + global::SpacetimeDB.Internal.ITableView.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView.DoClear(); + + public sealed class IdUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + PublicTable, + global::PublicTable, + int, + SpacetimeDB.BSATN.I32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "PublicTable_Id_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdUniqueIndex() { } + + internal IdUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::PublicTable? Find(int key) => FindSingle(key); + + public global::PublicTable Update(global::PublicTable row) => DoUpdate(row); + } + + private static IdUniqueIndex? __Id; + public IdUniqueIndex Id => __Id ??= new(); + } + + internal readonly struct RegressionMultipleUniqueIndexesHadSameName + : global::SpacetimeDB.Internal.ITableView< + RegressionMultipleUniqueIndexesHadSameName, + global::RegressionMultipleUniqueIndexesHadSameName + > + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "RegressionMultipleUniqueIndexesHadSameName" + ); + + public static global::RegressionMultipleUniqueIndexesHadSameName ReadGenFields( + System.IO.BinaryReader reader, + global::RegressionMultipleUniqueIndexesHadSameName row + ) + { + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(RegressionMultipleUniqueIndexesHadSameName), + ProductTypeRef: (uint) + new global::RegressionMultipleUniqueIndexesHadSameName.BSATN() + .GetAlgebraicType(registrar) + .Ref_, + PrimaryKey: [], + Indexes: + [ + new( + SourceName: "RegressionMultipleUniqueIndexesHadSameName_Unique1_idx_btree", + AccessorName: "Unique1", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + new( + SourceName: "RegressionMultipleUniqueIndexesHadSameName_Unique2_idx_btree", + AccessorName: "Unique2", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([1]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + RegressionMultipleUniqueIndexesHadSameName, + global::RegressionMultipleUniqueIndexesHadSameName + >.MakeUniqueConstraint(0), + global::SpacetimeDB.Internal.ITableView< + RegressionMultipleUniqueIndexesHadSameName, + global::RegressionMultipleUniqueIndexesHadSameName + >.MakeUniqueConstraint(1), + ], + Sequences: [], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => null; + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + RegressionMultipleUniqueIndexesHadSameName, + global::RegressionMultipleUniqueIndexesHadSameName + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + RegressionMultipleUniqueIndexesHadSameName, + global::RegressionMultipleUniqueIndexesHadSameName + >.DoIter(); + + public global::RegressionMultipleUniqueIndexesHadSameName Insert( + global::RegressionMultipleUniqueIndexesHadSameName row + ) => + global::SpacetimeDB.Internal.ITableView< + RegressionMultipleUniqueIndexesHadSameName, + global::RegressionMultipleUniqueIndexesHadSameName + >.DoInsert(row); + + public bool Delete(global::RegressionMultipleUniqueIndexesHadSameName row) => + global::SpacetimeDB.Internal.ITableView< + RegressionMultipleUniqueIndexesHadSameName, + global::RegressionMultipleUniqueIndexesHadSameName + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + RegressionMultipleUniqueIndexesHadSameName, + global::RegressionMultipleUniqueIndexesHadSameName + >.DoClear(); + + internal sealed class Unique1UniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + RegressionMultipleUniqueIndexesHadSameName, + global::RegressionMultipleUniqueIndexesHadSameName, + uint, + SpacetimeDB.BSATN.U32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "RegressionMultipleUniqueIndexesHadSameName_Unique1_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static Unique1UniqueIndex() { } + + internal Unique1UniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::RegressionMultipleUniqueIndexesHadSameName? Find(uint key) => + FindSingle(key); + } + + private static Unique1UniqueIndex? __Unique1; + internal Unique1UniqueIndex Unique1 => __Unique1 ??= new(); + + internal sealed class Unique2UniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + RegressionMultipleUniqueIndexesHadSameName, + global::RegressionMultipleUniqueIndexesHadSameName, + uint, + SpacetimeDB.BSATN.U32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "RegressionMultipleUniqueIndexesHadSameName_Unique2_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static Unique2UniqueIndex() { } + + internal Unique2UniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::RegressionMultipleUniqueIndexesHadSameName? Find(uint key) => + FindSingle(key); + } + + private static Unique2UniqueIndex? __Unique2; + internal Unique2UniqueIndex Unique2 => __Unique2 ??= new(); + } + + public readonly struct SendMessageTimer + : global::SpacetimeDB.Internal.ITableView + { + public static string LookupName => + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "SendMessageTimer" + ); + + public static global::Timers.SendMessageTimer ReadGenFields( + System.IO.BinaryReader reader, + global::Timers.SendMessageTimer row + ) + { + if (row.ScheduledId == default) + { + row.ScheduledId = global::Timers.SendMessageTimer.BSATN.ScheduledIdRW.Read(reader); + } + return row; + } + + public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(SendMessageTimer), + ProductTypeRef: (uint) + new global::Timers.SendMessageTimer.BSATN().GetAlgebraicType(registrar).Ref_, + PrimaryKey: [0], + Indexes: + [ + new( + SourceName: "SendMessageTimer_ScheduledId_idx_btree", + AccessorName: "ScheduledId", + Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.BTree([0]) + ), + ], + Constraints: + [ + global::SpacetimeDB.Internal.ITableView< + SendMessageTimer, + global::Timers.SendMessageTimer + >.MakeUniqueConstraint(0), + ], + Sequences: + [ + global::SpacetimeDB.Internal.ITableView< + SendMessageTimer, + global::Timers.SendMessageTimer + >.MakeSequence(0), + ], + TableType: SpacetimeDB.Internal.TableType.User, + TableAccess: SpacetimeDB.Internal.TableAccess.Private, + DefaultValues: [], + IsEvent: false + ); + + public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => + global::SpacetimeDB.Internal.ITableView< + SendMessageTimer, + global::Timers.SendMessageTimer + >.MakeSchedule("SendScheduledMessage", 1); + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => + global::SpacetimeDB.Internal.ITableView< + SendMessageTimer, + global::Timers.SendMessageTimer + >.DoCount(); + + public IEnumerable Iter() => + global::SpacetimeDB.Internal.ITableView< + SendMessageTimer, + global::Timers.SendMessageTimer + >.DoIter(); + + public global::Timers.SendMessageTimer Insert(global::Timers.SendMessageTimer row) => + global::SpacetimeDB.Internal.ITableView< + SendMessageTimer, + global::Timers.SendMessageTimer + >.DoInsert(row); + + public bool Delete(global::Timers.SendMessageTimer row) => + global::SpacetimeDB.Internal.ITableView< + SendMessageTimer, + global::Timers.SendMessageTimer + >.DoDelete(row); + + public ulong Clear() => + global::SpacetimeDB.Internal.ITableView< + SendMessageTimer, + global::Timers.SendMessageTimer + >.DoClear(); + + public sealed class ScheduledIdUniqueIndex + : global::SpacetimeDB.Internal.UniqueIndex< + SendMessageTimer, + global::Timers.SendMessageTimer, + ulong, + SpacetimeDB.BSATN.U64 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "SendMessageTimer_ScheduledId_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static ScheduledIdUniqueIndex() { } + + internal ScheduledIdUniqueIndex() + : base(__resolvedName) { } + + // Important: don't move this to the base class. + // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based + // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. + public global::Timers.SendMessageTimer? Find(ulong key) => FindSingle(key); + + public global::Timers.SendMessageTimer Update(global::Timers.SendMessageTimer row) => + DoUpdate(row); + } + + private static ScheduledIdUniqueIndex? __ScheduledId; + public ScheduledIdUniqueIndex ScheduledId => __ScheduledId ??= new(); + } +} + +sealed class public_table_queryViewDispatcher : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "public_table_query", + Index: 0, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: global::SpacetimeDB.BSATN.AlgebraicType.MakeQueryBuilderProductType( + new PublicTable.BSATN().GetAlgebraicType(registrar) + ) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.PublicTableQuery((SpacetimeDB.ViewContext)ctx); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RawSql( + returnValue.ToSql() + ); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'public_table_query': " + e); + throw; + } + } +} + +sealed class public_table_viewViewDispatcher : global::SpacetimeDB.Internal.IView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "public_table_view", + Index: 1, + IsPublic: true, + IsAnonymous: false, + Params: [], + ReturnType: new SpacetimeDB.BSATN.ValueOption< + PublicTable, + PublicTable.BSATN + >().GetAlgebraicType(registrar) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IViewContext ctx + ) + { + try + { + var returnValue = Module.PublicTableByIdentity((SpacetimeDB.ViewContext)ctx); + var listSerializer = SpacetimeDB.BSATN.ValueOption< + PublicTable, + PublicTable.BSATN + >.GetListSerializer(); + var listValue = ModuleRegistration.ToListOrEmpty(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'public_table_view': " + e); + throw; + } + } +} + +sealed class find_public_table__by_identityViewDispatcher + : global::SpacetimeDB.Internal.IAnonymousView +{ + public SpacetimeDB.Internal.RawViewDefV10 MakeAnonymousViewDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new global::SpacetimeDB.Internal.RawViewDefV10( + SourceName: "find_public_table__by_identity", + Index: 0, + IsPublic: true, + IsAnonymous: true, + Params: [], + ReturnType: new SpacetimeDB.BSATN.ValueOption< + PublicTable, + PublicTable.BSATN + >().GetAlgebraicType(registrar) + ); + + public static byte[] Invoke( + System.IO.BinaryReader reader, + global::SpacetimeDB.Internal.IAnonymousViewContext ctx + ) + { + try + { + var returnValue = Module.FindPublicTableByIdentity( + (SpacetimeDB.AnonymousViewContext)ctx + ); + var listSerializer = SpacetimeDB.BSATN.ValueOption< + PublicTable, + PublicTable.BSATN + >.GetListSerializer(); + var listValue = ModuleRegistration.ToListOrEmpty(returnValue); + var header = new global::SpacetimeDB.Internal.ViewResultHeader.RowData(default); + var headerRW = new global::SpacetimeDB.Internal.ViewResultHeader.BSATN(); + using var output = new System.IO.MemoryStream(); + using var writer = new System.IO.BinaryWriter(output); + headerRW.Write(writer, header); + listSerializer.Write(writer, listValue); + return output.ToArray(); + } + catch (System.Exception e) + { + global::SpacetimeDB.Log.Error("Error in view 'find_public_table__by_identity': " + e); + throw; + } + } +} + +namespace SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles +{ + internal sealed class BTreeMultiColumnReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeMultiColumn" + ); + + // Prevent eager initialization before the root installs namespace placements. + static BTreeMultiColumnReadOnly() { } + + internal BTreeMultiColumnReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class LocationIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeMultiColumn_X_Y_Z_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static LocationIndex() { } + + internal LocationIndex() + : base(__resolvedName) { } + + public IEnumerable Filter(uint X) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + X + ) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound X + ) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + X + ) + ); + + public IEnumerable Filter((uint X, uint Y) f) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public IEnumerable Filter( + (uint X, global::SpacetimeDB.Bound Y) f + ) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public IEnumerable Filter((uint X, uint Y, uint Z) f) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public IEnumerable Filter( + (uint X, uint Y, global::SpacetimeDB.Bound Z) f + ) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + } + + private static LocationIndex? __Location; + internal LocationIndex Location => __Location ??= new(); + } + + internal sealed class BTreeViewsReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeViews" + ); + + // Prevent eager initialization before the root installs namespace placements. + static BTreeViewsReadOnly() { } + + internal BTreeViewsReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class IdIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.BTreeViewsReadOnly, + global::BTreeViews, + SpacetimeDB.Identity, + SpacetimeDB.Identity.BSATN + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeViews_Id_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdIndex() { } + + internal IdIndex() + : base(__resolvedName) { } + + public global::BTreeViews? Find(SpacetimeDB.Identity key) => FindSingle(key); + } + + private static IdIndex? __Id; + public IdIndex Id => __Id ??= new(); + + public sealed class LocationIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeViews_X_Y_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static LocationIndex() { } + + internal LocationIndex() + : base(__resolvedName) { } + + public IEnumerable Filter(uint X) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + X + ) + ); + + public IEnumerable Filter(global::SpacetimeDB.Bound X) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds( + X + ) + ); + + public IEnumerable Filter((uint X, uint Y) f) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + + public IEnumerable Filter( + (uint X, global::SpacetimeDB.Bound Y) f + ) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds< + uint, + SpacetimeDB.BSATN.U32, + uint, + SpacetimeDB.BSATN.U32 + >(f) + ); + } + + private static LocationIndex? __Location; + internal LocationIndex Location => __Location ??= new(); + + public sealed class FactionIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "BTreeViews_Faction_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static FactionIndex() { } + + internal FactionIndex() + : base(__resolvedName) { } + + public IEnumerable Filter(string Faction) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds< + string, + SpacetimeDB.BSATN.String + >(Faction) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound Faction + ) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds< + string, + SpacetimeDB.BSATN.String + >(Faction) + ); + } + + private static FactionIndex? __Faction; + internal FactionIndex Faction => __Faction ??= new(); + } + + public sealed class MultiTable1ReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable1" + ); + + // Prevent eager initialization before the root installs namespace placements. + static MultiTable1ReadOnly() { } + + internal MultiTable1ReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class FooIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.MultiTable1ReadOnly, + global::MultiTableRow, + uint, + SpacetimeDB.BSATN.U32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable1_Foo_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static FooIndex() { } + + internal FooIndex() + : base(__resolvedName) { } + + public global::MultiTableRow? Find(uint key) => FindSingle(key); + } + + private static FooIndex? __Foo; + public FooIndex Foo => __Foo ??= new(); + + public sealed class NameIndex + : global::SpacetimeDB.Internal.ReadOnlyIndexBase + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable1_Name_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static NameIndex() { } + + internal NameIndex() + : base(__resolvedName) { } + + public IEnumerable Filter(string Name) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds< + string, + SpacetimeDB.BSATN.String + >(Name) + ); + + public IEnumerable Filter( + global::SpacetimeDB.Bound Name + ) => + DoFilter( + new global::SpacetimeDB.Internal.BTreeIndexBounds< + string, + SpacetimeDB.BSATN.String + >(Name) + ); + } + + private static NameIndex? __Name; + public NameIndex Name => __Name ??= new(); + } + + public sealed class MultiTable2ReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable2" + ); + + // Prevent eager initialization before the root installs namespace placements. + static MultiTable2ReadOnly() { } + + internal MultiTable2ReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class BarIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.MultiTable2ReadOnly, + global::MultiTableRow, + uint, + SpacetimeDB.BSATN.U32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "MultiTable2_Bar_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static BarIndex() { } + + internal BarIndex() + : base(__resolvedName) { } + + public global::MultiTableRow? Find(uint key) => FindSingle(key); + } + + private static BarIndex? __Bar; + public BarIndex Bar => __Bar ??= new(); + } + + public sealed class PrivateTableReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "PrivateTable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PrivateTableReadOnly() { } + + internal PrivateTableReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + } + + public sealed class PublicTableReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "PublicTable" + ); + + // Prevent eager initialization before the root installs namespace placements. + static PublicTableReadOnly() { } + + internal PublicTableReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class IdIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.PublicTableReadOnly, + global::PublicTable, + int, + SpacetimeDB.BSATN.I32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "PublicTable_Id_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static IdIndex() { } + + internal IdIndex() + : base(__resolvedName) { } + + public global::PublicTable? Find(int key) => FindSingle(key); + } + + private static IdIndex? __Id; + public IdIndex Id => __Id ??= new(); + } + + internal sealed class RegressionMultipleUniqueIndexesHadSameNameReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "RegressionMultipleUniqueIndexesHadSameName" + ); + + // Prevent eager initialization before the root installs namespace placements. + static RegressionMultipleUniqueIndexesHadSameNameReadOnly() { } + + internal RegressionMultipleUniqueIndexesHadSameNameReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class Unique1Index + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.RegressionMultipleUniqueIndexesHadSameNameReadOnly, + global::RegressionMultipleUniqueIndexesHadSameName, + uint, + SpacetimeDB.BSATN.U32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "RegressionMultipleUniqueIndexesHadSameName_Unique1_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static Unique1Index() { } + + internal Unique1Index() + : base(__resolvedName) { } + + public global::RegressionMultipleUniqueIndexesHadSameName? Find(uint key) => + FindSingle(key); + } + + private static Unique1Index? __Unique1; + public Unique1Index Unique1 => __Unique1 ??= new(); + + public sealed class Unique2Index + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.RegressionMultipleUniqueIndexesHadSameNameReadOnly, + global::RegressionMultipleUniqueIndexesHadSameName, + uint, + SpacetimeDB.BSATN.U32 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "RegressionMultipleUniqueIndexesHadSameName_Unique2_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static Unique2Index() { } + + internal Unique2Index() + : base(__resolvedName) { } + + public global::RegressionMultipleUniqueIndexesHadSameName? Find(uint key) => + FindSingle(key); + } + + private static Unique2Index? __Unique2; + public Unique2Index Unique2 => __Unique2 ??= new(); + } + + public sealed class SendMessageTimerReadOnly + : global::SpacetimeDB.Internal.ReadOnlyTableView + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "SendMessageTimer" + ); + + // Prevent eager initialization before the root installs namespace placements. + static SendMessageTimerReadOnly() { } + + internal SendMessageTimerReadOnly() + : base(__resolvedName) { } + + /// + /// Returns the number of rows in this table. + /// + /// This reads datastore metadata, so it runs in constant time. + /// It also takes into account modifications by the current transaction. + /// + public ulong Count => DoCount(); + + public sealed class ScheduledIdIndex + : global::SpacetimeDB.Internal.ReadOnlyUniqueIndex< + global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.SendMessageTimerReadOnly, + global::Timers.SendMessageTimer, + ulong, + SpacetimeDB.BSATN.U64 + > + { + private static readonly string __resolvedName = + global::SpacetimeDB.Internal.Module.ResolveName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "SendMessageTimer_ScheduledId_idx_btree" + ); + + // Prevent eager initialization before the root installs namespace placements. + static ScheduledIdIndex() { } + + internal ScheduledIdIndex() + : base(__resolvedName) { } + + public global::Timers.SendMessageTimer? Find(ulong key) => FindSingle(key); + } + + private static ScheduledIdIndex? __ScheduledId; + public ScheduledIdIndex ScheduledId => __ScheduledId ??= new(); + } +} + +#if !NET10_0_OR_GREATER +namespace SpacetimeDB.Internal +{ + public sealed partial class LocalReadOnly + { + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.BTreeMultiColumnReadOnly BTreeMultiColumn => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.BTreeViewsReadOnly BTreeViews => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.MultiTable1ReadOnly MultiTable1 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.MultiTable2ReadOnly MultiTable2 => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.PrivateTableReadOnly PrivateTable => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.PublicTableReadOnly PublicTable => + new(); + internal global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.RegressionMultipleUniqueIndexesHadSameNameReadOnly RegressionMultipleUniqueIndexesHadSameName => + new(); + public global::SpacetimeDB.Generated.server_D513E4815F57969C.ViewHandles.SendMessageTimerReadOnly SendMessageTimer => + new(); + } +} +#endif + +static class ModuleRegistration +{ + // Module host calls are single-threaded in Wasm today, so the generated + // entrypoints reuse buffers across calls to avoid per-invocation allocation. + private static byte[] reducerArgsBuffer = new byte[0x10_000]; + private static byte[] procedureArgsBuffer = new byte[0x10_000]; + private static byte[] httpRequestBuffer = new byte[0x10_000]; + private static byte[] httpRequestBodyBuffer = new byte[0x10_000]; + private static byte[] viewArgsBuffer = new byte[0x10_000]; + private static byte[] anonymousViewArgsBuffer = new byte[0x10_000]; + + sealed class Init : SpacetimeDB.Internal.IReducer + { + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(Init), + Params: [], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => SpacetimeDB.Internal.Lifecycle.Init; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Timers.Init((SpacetimeDB.ReducerContext)ctx); + } + } + + sealed class InsertData : SpacetimeDB.Internal.IReducer + { + private static readonly PublicTable.BSATN dataRW = new(); + + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(InsertData), + Params: [new("data", dataRW.GetAlgebraicType(registrar))], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Reducers.InsertData((SpacetimeDB.ReducerContext)ctx, dataRW.Read(reader)); + } + } + + sealed class InsertData2 : SpacetimeDB.Internal.IReducer + { + private static readonly PublicTable.BSATN dataRW = new(); + + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(InsertData2), + Params: [new("data", dataRW.GetAlgebraicType(registrar))], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Test.NestingNamespaces.AndClasses.InsertData2( + (SpacetimeDB.ReducerContext)ctx, + dataRW.Read(reader) + ); + } + } + + sealed class InsertMultiData : SpacetimeDB.Internal.IReducer + { + private static readonly MultiTableRow.BSATN dataRW = new(); + + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(InsertMultiData), + Params: [new("data", dataRW.GetAlgebraicType(registrar))], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + MultiTableRow.InsertMultiData((SpacetimeDB.ReducerContext)ctx, dataRW.Read(reader)); + } + } + + sealed class ScheduleImmediate : SpacetimeDB.Internal.IReducer + { + private static readonly PublicTable.BSATN dataRW = new(); + + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(ScheduleImmediate), + Params: [new("data", dataRW.GetAlgebraicType(registrar))], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Reducers.ScheduleImmediate((SpacetimeDB.ReducerContext)ctx, dataRW.Read(reader)); + } + } + + sealed class SendScheduledMessage : SpacetimeDB.Internal.IReducer + { + private static readonly Timers.SendMessageTimer.BSATN argRW = new(); + + public SpacetimeDB.Internal.RawReducerDefV10 MakeReducerDef( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + new( + SourceName: nameof(SendScheduledMessage), + Params: [new("arg", argRW.GetAlgebraicType(registrar))], + Visibility: SpacetimeDB.Internal.FunctionVisibility.ClientCallable, + OkReturnType: SpacetimeDB.BSATN.AlgebraicType.Unit, + ErrReturnType: new SpacetimeDB.BSATN.AlgebraicType.String(default) + ); + + public SpacetimeDB.Internal.Lifecycle? Lifecycle => null; + + public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerContext ctx) + { + Timers.SendScheduledMessage((SpacetimeDB.ReducerContext)ctx, argRW.Read(reader)); + } + } + + public static List ToListOrEmpty(T? value) + where T : struct => value is null ? new List() : new List { value.Value }; + + public static List ToListOrEmpty(T? value) + where T : class => value is null ? new List() : new List { value }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + // In AOT mode we're building a library. + // Main method won't be called automatically, so we need to export it as a preinit function. + [UnmanagedCallersOnly(EntryPoint = "__preinit__10_init_csharp")] +#else + // Prevent trimming of FFI exports that are invoked from C and not visible to C# trimmer. + [DynamicDependency(DynamicallyAccessedMemberTypes.PublicMethods, typeof(ModuleRegistration))] +#endif + public static void Main() => Initialize(); + + internal static void Initialize() + { +#if !NET10_0_OR_GREATER + SpacetimeDB.Internal.Module.SetReducerContextConstructor( + (identity, connectionId, random, time) => + new SpacetimeDB.ReducerContext(identity, connectionId, random, time) + ); + SpacetimeDB.Internal.Module.SetViewContextConstructor( + identity => new SpacetimeDB.ViewContext( + identity, + new SpacetimeDB.Internal.LocalReadOnly() + ) + ); + SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor(() => + new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly()) + ); + SpacetimeDB.Internal.Module.SetProcedureContextConstructor( + (identity, connectionId, random, time) => + new SpacetimeDB.ProcedureContext(identity, connectionId, random, time) + ); + SpacetimeDB.Internal.Module.SetHandlerContextConstructor( + (random, time) => new SpacetimeDB.HandlerContext(random, time) + ); +#endif + +#if NET10_0_OR_GREATER + global::SpacetimeDB.Internal.Module.InstallNamespaces( + new global::SpacetimeDB.Internal.NamespaceRegistry( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + global::SpacetimeDB.CaseConversionPolicy.SnakeCase, + new (string, string, string?, global::SpacetimeDB.CaseConversionPolicy)[] { } + ) + ); + global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.Register( + global::SpacetimeDB.Internal.Module.RootBuilder + ); +#else + Register(global::SpacetimeDB.Internal.Module.RootBuilder); +#endif + } + + internal static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null + ) + { + // HTTP routes retain the root routing API even for mounted modules. + httpBuilder ??= builder; + builder.RegisterEnvironment( + new("REQUIRED", new global::SpacetimeDB.Internal.EnvVarType.String(default), false) + ); + builder.RegisterEnvironment( + new("OPTIONAL", new global::SpacetimeDB.Internal.EnvVarType.String(default), true) + ); + builder.RegisterEnvironment( + new( + "MODE", + new global::SpacetimeDB.Internal.EnvVarType.Union( + new global::System.Collections.Generic.List { "dev", "prod" } + ), + false + ) + ); + var __memoryStream = new MemoryStream(); + var __writer = new BinaryWriter(__memoryStream); + + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + builder.RegisterReducer(); + + // IMPORTANT: The order in which we register views matters. + // It must correspond to the order in which we call `GenerateDispatcherClass`. + // See the comment on `GenerateDispatcherClass` for more explanation. + builder.RegisterView(); + builder.RegisterView(); + builder.RegisterAnonymousView(); + + builder.RegisterTable< + global::BTreeMultiColumn, + global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.BTreeMultiColumn + >(); + builder.RegisterTable< + global::BTreeViews, + global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.BTreeViews + >(); + builder.RegisterTable< + global::MultiTableRow, + global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.MultiTable1 + >(); + builder.RegisterTable< + global::MultiTableRow, + global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.MultiTable2 + >(); + builder.RegisterTable< + global::PrivateTable, + global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.PrivateTable + >(); + builder.RegisterTable< + global::PublicTable, + global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.PublicTable + >(); + builder.RegisterTable< + global::RegressionMultipleUniqueIndexesHadSameName, + global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.RegressionMultipleUniqueIndexesHadSameName + >(); + builder.RegisterTable< + global::Timers.SendMessageTimer, + global::SpacetimeDB.Generated.server_D513E4815F57969C.TableHandles.SendMessageTimer + >(); + + builder.RegisterClientVisibilityFilter(global::Module.ALL_PUBLIC_TABLES); + } + + // Export entrypoints live in generated module code so all build modes can + // dispatch directly to concrete generated functions. +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__describe_module__")] +#endif + public static void __describe_module__(SpacetimeDB.Internal.BytesSink d) => + SpacetimeDB.Internal.Module.__describe_module__(d); + + private static SpacetimeDB.Internal.Errno __call_reducer_0( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + Init.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_1( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + InsertData.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_2( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + InsertData2.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_3( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + InsertMultiData.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_4( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + ScheduleImmediate.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_reducer_5( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateReducerContext( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref reducerArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + SendScheduledMessage.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.EnsureNoUnreadBytes(stream, "reducer arguments"); + return SpacetimeDB.Internal.Errno.OK; + } + catch (System.Exception e) + { + return SpacetimeDB.Internal.Module.WriteReducerError(error, e); + } + } + + private static SpacetimeDB.Internal.Errno __call_view_0( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = public_table_queryViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_1( + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateViewContext( + sender_0, + sender_1, + sender_2, + sender_3 + ); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes(args, ref viewArgsBuffer); + using var reader = new System.IO.BinaryReader(stream); + var bytes = public_table_viewViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + + private static SpacetimeDB.Internal.Errno __call_view_anon_0( + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { + try + { + var ctx = SpacetimeDB.Internal.Module.CreateAnonymousViewContext(); + using var stream = SpacetimeDB.Internal.Module.ConsumeBytes( + args, + ref anonymousViewArgsBuffer + ); + using var reader = new System.IO.BinaryReader(stream); + var bytes = find_public_table__by_identityViewDispatcher.Invoke(reader, ctx); + SpacetimeDB.Internal.Module.WriteBytes(sink, bytes); + return (SpacetimeDB.Internal.Errno)2; + } + catch (System.Exception e) + { + SpacetimeDB.Log.Error($"Error while invoking anonymous view: {e}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + } + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_reducer__")] +#endif + public static SpacetimeDB.Internal.Errno __call_reducer__( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .ReducerCount + ) + return global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.CallLocalReducer( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); + localId -= global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .ReducerCount; + return SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ); +#else + return CallLocalReducer( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error + ) => + id switch + { + 0 => __call_reducer_0( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 1 => __call_reducer_1( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 2 => __call_reducer_2( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 3 => __call_reducer_3( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 4 => __call_reducer_4( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + 5 => __call_reducer_5( + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + error + ), + _ => SpacetimeDB.Internal.Module.WriteReducerError( + error, + new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id") + ), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_procedure__")] +#endif + public static SpacetimeDB.Internal.Errno __call_procedure__( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .ProcedureCount + ) + return global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.CallLocalProcedure( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); + localId -= global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .ProcedureCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id"); +#else + return CallLocalProcedure( + id, + sender_0, + sender_1, + sender_2, + sender_3, + conn_id_0, + conn_id_1, + timestamp, + args, + result_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink + ) => + id switch + { + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown procedure id" + ), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_http_handler__")] +#endif + public static SpacetimeDB.Internal.Errno __call_http_handler__( + int id, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource request, + SpacetimeDB.Internal.BytesSource request_body, + SpacetimeDB.Internal.BytesSink response_sink, + SpacetimeDB.Internal.BytesSink response_body_sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .HttpHandlerCount + ) + return global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.CallLocalHttpHandler( + localId, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); + localId -= global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .HttpHandlerCount; + throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id"); +#else + return CallLocalHttpHandler( + id, + timestamp, + request, + request_body, + response_sink, + response_body_sink + ); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource request, + SpacetimeDB.Internal.BytesSource request_body, + SpacetimeDB.Internal.BytesSink response_sink, + SpacetimeDB.Internal.BytesSink response_body_sink + ) => + id switch + { + _ => throw new System.ArgumentOutOfRangeException( + nameof(id), + id, + "Unknown HTTP handler id" + ), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_view__")] +#endif + public static SpacetimeDB.Internal.Errno __call_view__( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.ViewCount + ) + return global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.CallLocalView( + localId, + sender_0, + sender_1, + sender_2, + sender_3, + args, + sink + ); + localId -= global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .ViewCount; + return UnknownViewId(id); +#else + return CallLocalView(id, sender_0, sender_1, sender_2, sender_3, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) => + id switch + { + 0 => __call_view_0(sender_0, sender_1, sender_2, sender_3, args, sink), + 1 => __call_view_1(sender_0, sender_1, sender_2, sender_3, args, sink), + _ => UnknownViewId(id), + }; + +#if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER + [UnmanagedCallersOnly(EntryPoint = "__call_view_anon__")] +#endif + public static SpacetimeDB.Internal.Errno __call_view_anon__( + int id, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) + { +#if NET10_0_OR_GREATER + if (id < 0) + { + return UnknownAnonymousViewId(id); + } + var localId = id; + if ( + (uint)localId + < (uint) + global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .AnonymousViewCount + ) + return global::SpacetimeDB.Generated.server_D513E4815F57969C.AssemblyDescriptor.CallLocalAnonymousView( + localId, + args, + sink + ); + localId -= global::SpacetimeDB + .Generated + .server_D513E4815F57969C + .AssemblyDescriptor + .AnonymousViewCount; + return UnknownAnonymousViewId(id); +#else + return CallLocalAnonymousView(id, args, sink); +#endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink + ) => + id switch + { + 0 => __call_view_anon_0(args, sink), + _ => UnknownAnonymousViewId(id), + }; + + private static SpacetimeDB.Internal.Errno UnknownViewId(int id) + { + SpacetimeDB.Log.Error($"Unknown view id: {id}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } + + private static SpacetimeDB.Internal.Errno UnknownAnonymousViewId(int id) + { + SpacetimeDB.Log.Error($"Unknown anonymous view id: {id}"); + return SpacetimeDB.Internal.Errno.HOST_CALL_FAILURE; + } +} + +#pragma warning restore STDB_UNSTABLE +#pragma warning restore CS0436 diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#MultiTableRow.InsertMultiData.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#MultiTableRow.InsertMultiData.verified.cs new file mode 100644 index 00000000000..5549aba2925 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#MultiTableRow.InsertMultiData.verified.cs @@ -0,0 +1,31 @@ +//HintName: MultiTableRow.InsertMultiData.cs +// +#nullable enable + +partial struct MultiTableRow +{ + private static class __ScheduleInsertMultiDataName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(InsertMultiData), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleInsertMultiDataName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateInsertMultiData(MultiTableRow data) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + new MultiTableRow.BSATN().Write(writer, data); + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleInsertMultiDataName.Name, + stream + ); + } +} // MultiTableRow diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#MultiTableRow.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#MultiTableRow.verified.cs new file mode 100644 index 00000000000..d5786199b4b --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#MultiTableRow.verified.cs @@ -0,0 +1,115 @@ +//HintName: MultiTableRow.cs +// +#nullable enable + +partial struct MultiTableRow + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + Name = BSATN.NameRW.Read(reader); + Foo = BSATN.FooRW.Read(reader); + Bar = BSATN.BarRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.NameRW.Write(writer, Name); + BSATN.FooRW.Write(writer, Foo); + BSATN.BarRW.Write(writer, Bar); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"MultiTableRow {{ Name = {SpacetimeDB.BSATN.StringUtil.GenericToString(Name)}, Foo = {SpacetimeDB.BSATN.StringUtil.GenericToString(Foo)}, Bar = {SpacetimeDB.BSATN.StringUtil.GenericToString(Bar)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.String NameRW = new(); + internal static readonly SpacetimeDB.BSATN.U32 FooRW = new(); + internal static readonly SpacetimeDB.BSATN.U32 BarRW = new(); + + public MultiTableRow Read(System.IO.BinaryReader reader) + { + var ___result = new MultiTableRow(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, MultiTableRow value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType(_ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("Name", NameRW.GetAlgebraicType(registrar)), + new("Foo", FooRW.GetAlgebraicType(registrar)), + new("Bar", BarRW.GetAlgebraicType(registrar)), + } + )); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashName = Name == null ? 0 : Name.GetHashCode(); + var ___hashFoo = Foo.GetHashCode(); + var ___hashBar = Bar.GetHashCode(); + return ___hashName ^ ___hashFoo ^ ___hashBar; + } + +#nullable enable + public bool Equals(MultiTableRow that) + { + var ___eqName = this.Name == null ? that.Name == null : this.Name.Equals(that.Name); + var ___eqFoo = this.Foo.Equals(that.Foo); + var ___eqBar = this.Bar.Equals(that.Bar); + return ___eqName && ___eqFoo && ___eqBar; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as MultiTableRow?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(MultiTableRow this_, MultiTableRow that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(MultiTableRow this_, MultiTableRow that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // MultiTableRow diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#PrivateTable.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#PrivateTable.verified.cs new file mode 100644 index 00000000000..7904294b21b --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#PrivateTable.verified.cs @@ -0,0 +1,92 @@ +//HintName: PrivateTable.cs +// +#nullable enable + +partial class PrivateTable : System.IEquatable, SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) { } + + public void WriteFields(System.IO.BinaryWriter writer) { } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => $"PrivateTable {{ }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + public PrivateTable Read(System.IO.BinaryReader reader) + { + var ___result = new PrivateTable(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, PrivateTable value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType(_ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] { } + )); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + return 0; + } + +#nullable enable + public bool Equals(PrivateTable? that) + { + if (((object?)that) == null) + { + return false; + } + + return true; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as PrivateTable; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(PrivateTable? this_, PrivateTable? that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(PrivateTable? this_, PrivateTable? that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // PrivateTable diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#PublicTable.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#PublicTable.verified.cs new file mode 100644 index 00000000000..66eb1f4dfe6 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#PublicTable.verified.cs @@ -0,0 +1,380 @@ +//HintName: PublicTable.cs +// +#nullable enable + +partial struct PublicTable : System.IEquatable, SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + Id = BSATN.IdRW.Read(reader); + ByteField = BSATN.ByteFieldRW.Read(reader); + UshortField = BSATN.UshortFieldRW.Read(reader); + UintField = BSATN.UintFieldRW.Read(reader); + UlongField = BSATN.UlongFieldRW.Read(reader); + UInt128Field = BSATN.UInt128FieldRW.Read(reader); + U128Field = BSATN.U128FieldRW.Read(reader); + U256Field = BSATN.U256FieldRW.Read(reader); + SbyteField = BSATN.SbyteFieldRW.Read(reader); + ShortField = BSATN.ShortFieldRW.Read(reader); + IntField = BSATN.IntFieldRW.Read(reader); + LongField = BSATN.LongFieldRW.Read(reader); + Int128Field = BSATN.Int128FieldRW.Read(reader); + I128Field = BSATN.I128FieldRW.Read(reader); + I256Field = BSATN.I256FieldRW.Read(reader); + BoolField = BSATN.BoolFieldRW.Read(reader); + FloatField = BSATN.FloatFieldRW.Read(reader); + DoubleField = BSATN.DoubleFieldRW.Read(reader); + StringField = BSATN.StringFieldRW.Read(reader); + IdentityField = BSATN.IdentityFieldRW.Read(reader); + ConnectionIdField = BSATN.ConnectionIdFieldRW.Read(reader); + CustomStructField = BSATN.CustomStructFieldRW.Read(reader); + CustomClassField = BSATN.CustomClassFieldRW.Read(reader); + CustomEnumField = BSATN.CustomEnumFieldRW.Read(reader); + CustomTaggedEnumField = BSATN.CustomTaggedEnumFieldRW.Read(reader); + ListField = BSATN.ListFieldRW.Read(reader); + NullableValueField = BSATN.NullableValueFieldRW.Read(reader); + NullableReferenceField = BSATN.NullableReferenceFieldRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.IdRW.Write(writer, Id); + BSATN.ByteFieldRW.Write(writer, ByteField); + BSATN.UshortFieldRW.Write(writer, UshortField); + BSATN.UintFieldRW.Write(writer, UintField); + BSATN.UlongFieldRW.Write(writer, UlongField); + BSATN.UInt128FieldRW.Write(writer, UInt128Field); + BSATN.U128FieldRW.Write(writer, U128Field); + BSATN.U256FieldRW.Write(writer, U256Field); + BSATN.SbyteFieldRW.Write(writer, SbyteField); + BSATN.ShortFieldRW.Write(writer, ShortField); + BSATN.IntFieldRW.Write(writer, IntField); + BSATN.LongFieldRW.Write(writer, LongField); + BSATN.Int128FieldRW.Write(writer, Int128Field); + BSATN.I128FieldRW.Write(writer, I128Field); + BSATN.I256FieldRW.Write(writer, I256Field); + BSATN.BoolFieldRW.Write(writer, BoolField); + BSATN.FloatFieldRW.Write(writer, FloatField); + BSATN.DoubleFieldRW.Write(writer, DoubleField); + BSATN.StringFieldRW.Write(writer, StringField); + BSATN.IdentityFieldRW.Write(writer, IdentityField); + BSATN.ConnectionIdFieldRW.Write(writer, ConnectionIdField); + BSATN.CustomStructFieldRW.Write(writer, CustomStructField); + BSATN.CustomClassFieldRW.Write(writer, CustomClassField); + BSATN.CustomEnumFieldRW.Write(writer, CustomEnumField); + BSATN.CustomTaggedEnumFieldRW.Write(writer, CustomTaggedEnumField); + BSATN.ListFieldRW.Write(writer, ListField); + BSATN.NullableValueFieldRW.Write(writer, NullableValueField); + BSATN.NullableReferenceFieldRW.Write(writer, NullableReferenceField); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"PublicTable {{ Id = {SpacetimeDB.BSATN.StringUtil.GenericToString(Id)}, ByteField = {SpacetimeDB.BSATN.StringUtil.GenericToString(ByteField)}, UshortField = {SpacetimeDB.BSATN.StringUtil.GenericToString(UshortField)}, UintField = {SpacetimeDB.BSATN.StringUtil.GenericToString(UintField)}, UlongField = {SpacetimeDB.BSATN.StringUtil.GenericToString(UlongField)}, UInt128Field = {SpacetimeDB.BSATN.StringUtil.GenericToString(UInt128Field)}, U128Field = {SpacetimeDB.BSATN.StringUtil.GenericToString(U128Field)}, U256Field = {SpacetimeDB.BSATN.StringUtil.GenericToString(U256Field)}, SbyteField = {SpacetimeDB.BSATN.StringUtil.GenericToString(SbyteField)}, ShortField = {SpacetimeDB.BSATN.StringUtil.GenericToString(ShortField)}, IntField = {SpacetimeDB.BSATN.StringUtil.GenericToString(IntField)}, LongField = {SpacetimeDB.BSATN.StringUtil.GenericToString(LongField)}, Int128Field = {SpacetimeDB.BSATN.StringUtil.GenericToString(Int128Field)}, I128Field = {SpacetimeDB.BSATN.StringUtil.GenericToString(I128Field)}, I256Field = {SpacetimeDB.BSATN.StringUtil.GenericToString(I256Field)}, BoolField = {SpacetimeDB.BSATN.StringUtil.GenericToString(BoolField)}, FloatField = {SpacetimeDB.BSATN.StringUtil.GenericToString(FloatField)}, DoubleField = {SpacetimeDB.BSATN.StringUtil.GenericToString(DoubleField)}, StringField = {SpacetimeDB.BSATN.StringUtil.GenericToString(StringField)}, IdentityField = {SpacetimeDB.BSATN.StringUtil.GenericToString(IdentityField)}, ConnectionIdField = {SpacetimeDB.BSATN.StringUtil.GenericToString(ConnectionIdField)}, CustomStructField = {SpacetimeDB.BSATN.StringUtil.GenericToString(CustomStructField)}, CustomClassField = {SpacetimeDB.BSATN.StringUtil.GenericToString(CustomClassField)}, CustomEnumField = {SpacetimeDB.BSATN.StringUtil.GenericToString(CustomEnumField)}, CustomTaggedEnumField = {SpacetimeDB.BSATN.StringUtil.GenericToString(CustomTaggedEnumField)}, ListField = {SpacetimeDB.BSATN.StringUtil.GenericToString(ListField)}, NullableValueField = {SpacetimeDB.BSATN.StringUtil.GenericToString(NullableValueField)}, NullableReferenceField = {SpacetimeDB.BSATN.StringUtil.GenericToString(NullableReferenceField)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.I32 IdRW = new(); + internal static readonly SpacetimeDB.BSATN.U8 ByteFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.U16 UshortFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.U32 UintFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.U64 UlongFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.U128 UInt128FieldRW = new(); + internal static readonly SpacetimeDB.BSATN.U128Stdb U128FieldRW = new(); + internal static readonly SpacetimeDB.BSATN.U256 U256FieldRW = new(); + internal static readonly SpacetimeDB.BSATN.I8 SbyteFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.I16 ShortFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.I32 IntFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.I64 LongFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.I128 Int128FieldRW = new(); + internal static readonly SpacetimeDB.BSATN.I128Stdb I128FieldRW = new(); + internal static readonly SpacetimeDB.BSATN.I256 I256FieldRW = new(); + internal static readonly SpacetimeDB.BSATN.Bool BoolFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.F32 FloatFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.F64 DoubleFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.String StringFieldRW = new(); + internal static readonly SpacetimeDB.Identity.BSATN IdentityFieldRW = new(); + internal static readonly SpacetimeDB.ConnectionId.BSATN ConnectionIdFieldRW = new(); + internal static readonly CustomStruct.BSATN CustomStructFieldRW = new(); + internal static readonly CustomClass.BSATN CustomClassFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.Enum CustomEnumFieldRW = new(); + internal static readonly CustomTaggedEnum.BSATN CustomTaggedEnumFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.List ListFieldRW = + new(); + internal static readonly SpacetimeDB.BSATN.ValueOption< + int, + SpacetimeDB.BSATN.I32 + > NullableValueFieldRW = new(); + internal static readonly SpacetimeDB.BSATN.RefOption< + string, + SpacetimeDB.BSATN.String + > NullableReferenceFieldRW = new(); + + public PublicTable Read(System.IO.BinaryReader reader) + { + var ___result = new PublicTable(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, PublicTable value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType(_ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("Id", IdRW.GetAlgebraicType(registrar)), + new("ByteField", ByteFieldRW.GetAlgebraicType(registrar)), + new("UshortField", UshortFieldRW.GetAlgebraicType(registrar)), + new("UintField", UintFieldRW.GetAlgebraicType(registrar)), + new("UlongField", UlongFieldRW.GetAlgebraicType(registrar)), + new("UInt128Field", UInt128FieldRW.GetAlgebraicType(registrar)), + new("U128Field", U128FieldRW.GetAlgebraicType(registrar)), + new("U256Field", U256FieldRW.GetAlgebraicType(registrar)), + new("SbyteField", SbyteFieldRW.GetAlgebraicType(registrar)), + new("ShortField", ShortFieldRW.GetAlgebraicType(registrar)), + new("IntField", IntFieldRW.GetAlgebraicType(registrar)), + new("LongField", LongFieldRW.GetAlgebraicType(registrar)), + new("Int128Field", Int128FieldRW.GetAlgebraicType(registrar)), + new("I128Field", I128FieldRW.GetAlgebraicType(registrar)), + new("I256Field", I256FieldRW.GetAlgebraicType(registrar)), + new("BoolField", BoolFieldRW.GetAlgebraicType(registrar)), + new("FloatField", FloatFieldRW.GetAlgebraicType(registrar)), + new("DoubleField", DoubleFieldRW.GetAlgebraicType(registrar)), + new("StringField", StringFieldRW.GetAlgebraicType(registrar)), + new("IdentityField", IdentityFieldRW.GetAlgebraicType(registrar)), + new("ConnectionIdField", ConnectionIdFieldRW.GetAlgebraicType(registrar)), + new("CustomStructField", CustomStructFieldRW.GetAlgebraicType(registrar)), + new("CustomClassField", CustomClassFieldRW.GetAlgebraicType(registrar)), + new("CustomEnumField", CustomEnumFieldRW.GetAlgebraicType(registrar)), + new( + "CustomTaggedEnumField", + CustomTaggedEnumFieldRW.GetAlgebraicType(registrar) + ), + new("ListField", ListFieldRW.GetAlgebraicType(registrar)), + new("NullableValueField", NullableValueFieldRW.GetAlgebraicType(registrar)), + new( + "NullableReferenceField", + NullableReferenceFieldRW.GetAlgebraicType(registrar) + ), + } + )); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashId = Id.GetHashCode(); + var ___hashByteField = ByteField.GetHashCode(); + var ___hashUshortField = UshortField.GetHashCode(); + var ___hashUintField = UintField.GetHashCode(); + var ___hashUlongField = UlongField.GetHashCode(); + var ___hashUInt128Field = UInt128Field.GetHashCode(); + var ___hashU128Field = U128Field.GetHashCode(); + var ___hashU256Field = U256Field.GetHashCode(); + var ___hashSbyteField = SbyteField.GetHashCode(); + var ___hashShortField = ShortField.GetHashCode(); + var ___hashIntField = IntField.GetHashCode(); + var ___hashLongField = LongField.GetHashCode(); + var ___hashInt128Field = Int128Field.GetHashCode(); + var ___hashI128Field = I128Field.GetHashCode(); + var ___hashI256Field = I256Field.GetHashCode(); + var ___hashBoolField = BoolField.GetHashCode(); + var ___hashFloatField = FloatField.GetHashCode(); + var ___hashDoubleField = DoubleField.GetHashCode(); + var ___hashStringField = StringField == null ? 0 : StringField.GetHashCode(); + var ___hashIdentityField = IdentityField.GetHashCode(); + var ___hashConnectionIdField = ConnectionIdField.GetHashCode(); + var ___hashCustomStructField = CustomStructField.GetHashCode(); + var ___hashCustomClassField = CustomClassField == null ? 0 : CustomClassField.GetHashCode(); + var ___hashCustomEnumField = CustomEnumField.GetHashCode(); + var ___hashCustomTaggedEnumField = + CustomTaggedEnumField == null ? 0 : CustomTaggedEnumField.GetHashCode(); + var ___hashListField = 0; + if (ListField != null) + { + var ___hc0 = new System.HashCode(); + for (int ___i0 = 0; ___i0 < ListField.Count; ___i0++) + { + var ___tmp0 = ListField[___i0]; + var ___out1 = ___tmp0.GetHashCode(); + ___hc0.Add(___out1); + } + ___hashListField = ___hc0.ToHashCode(); + } + var ___hashNullableValueField = NullableValueField.GetHashCode(); + var ___hashNullableReferenceField = + NullableReferenceField == null ? 0 : NullableReferenceField.GetHashCode(); + return ___hashId + ^ ___hashByteField + ^ ___hashUshortField + ^ ___hashUintField + ^ ___hashUlongField + ^ ___hashUInt128Field + ^ ___hashU128Field + ^ ___hashU256Field + ^ ___hashSbyteField + ^ ___hashShortField + ^ ___hashIntField + ^ ___hashLongField + ^ ___hashInt128Field + ^ ___hashI128Field + ^ ___hashI256Field + ^ ___hashBoolField + ^ ___hashFloatField + ^ ___hashDoubleField + ^ ___hashStringField + ^ ___hashIdentityField + ^ ___hashConnectionIdField + ^ ___hashCustomStructField + ^ ___hashCustomClassField + ^ ___hashCustomEnumField + ^ ___hashCustomTaggedEnumField + ^ ___hashListField + ^ ___hashNullableValueField + ^ ___hashNullableReferenceField; + } + +#nullable enable + public bool Equals(PublicTable that) + { + var ___eqId = this.Id.Equals(that.Id); + var ___eqByteField = this.ByteField.Equals(that.ByteField); + var ___eqUshortField = this.UshortField.Equals(that.UshortField); + var ___eqUintField = this.UintField.Equals(that.UintField); + var ___eqUlongField = this.UlongField.Equals(that.UlongField); + var ___eqUInt128Field = this.UInt128Field.Equals(that.UInt128Field); + var ___eqU128Field = this.U128Field.Equals(that.U128Field); + var ___eqU256Field = this.U256Field.Equals(that.U256Field); + var ___eqSbyteField = this.SbyteField.Equals(that.SbyteField); + var ___eqShortField = this.ShortField.Equals(that.ShortField); + var ___eqIntField = this.IntField.Equals(that.IntField); + var ___eqLongField = this.LongField.Equals(that.LongField); + var ___eqInt128Field = this.Int128Field.Equals(that.Int128Field); + var ___eqI128Field = this.I128Field.Equals(that.I128Field); + var ___eqI256Field = this.I256Field.Equals(that.I256Field); + var ___eqBoolField = this.BoolField.Equals(that.BoolField); + var ___eqFloatField = this.FloatField.Equals(that.FloatField); + var ___eqDoubleField = this.DoubleField.Equals(that.DoubleField); + var ___eqStringField = + this.StringField == null + ? that.StringField == null + : this.StringField.Equals(that.StringField); + var ___eqIdentityField = this.IdentityField.Equals(that.IdentityField); + var ___eqConnectionIdField = this.ConnectionIdField.Equals(that.ConnectionIdField); + var ___eqCustomStructField = this.CustomStructField.Equals(that.CustomStructField); + var ___eqCustomClassField = + this.CustomClassField == null + ? that.CustomClassField == null + : this.CustomClassField.Equals(that.CustomClassField); + var ___eqCustomEnumField = this.CustomEnumField == that.CustomEnumField; + var ___eqCustomTaggedEnumField = + this.CustomTaggedEnumField == null + ? that.CustomTaggedEnumField == null + : this.CustomTaggedEnumField.Equals(that.CustomTaggedEnumField); + var ___eqListField = true; + if (this.ListField == null || that.ListField == null) + { + ___eqListField = this.ListField == that.ListField; + } + else if (this.ListField.Count != that.ListField.Count) + { + ___eqListField = false; + } + else + { + for (int ___i0 = 0; ___i0 < this.ListField.Count; ___i0++) + { + var ___tmpA0 = this.ListField[___i0]; + var ___tmpB0 = that.ListField[___i0]; + var ___out1 = ___tmpA0.Equals(___tmpB0); + if (!___out1) + { + ___eqListField = false; + break; + } + } + } + var ___eqNullableValueField = System.Nullable.Equals( + this.NullableValueField, + that.NullableValueField + ); + var ___eqNullableReferenceField = + this.NullableReferenceField == null + ? that.NullableReferenceField == null + : this.NullableReferenceField.Equals(that.NullableReferenceField); + return ___eqId + && ___eqByteField + && ___eqUshortField + && ___eqUintField + && ___eqUlongField + && ___eqUInt128Field + && ___eqU128Field + && ___eqU256Field + && ___eqSbyteField + && ___eqShortField + && ___eqIntField + && ___eqLongField + && ___eqInt128Field + && ___eqI128Field + && ___eqI256Field + && ___eqBoolField + && ___eqFloatField + && ___eqDoubleField + && ___eqStringField + && ___eqIdentityField + && ___eqConnectionIdField + && ___eqCustomStructField + && ___eqCustomClassField + && ___eqCustomEnumField + && ___eqCustomTaggedEnumField + && ___eqListField + && ___eqNullableValueField + && ___eqNullableReferenceField; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as PublicTable?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(PublicTable this_, PublicTable that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(PublicTable this_, PublicTable that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // PublicTable diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Reducers.InsertData.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Reducers.InsertData.verified.cs new file mode 100644 index 00000000000..1e2eafd9af6 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Reducers.InsertData.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.InsertData.cs +// +#nullable enable + +partial class Reducers +{ + private static class __ScheduleInsertDataName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(InsertData), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleInsertDataName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateInsertData(PublicTable data) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + new PublicTable.BSATN().Write(writer, data); + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleInsertDataName.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Reducers.ScheduleImmediate.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Reducers.ScheduleImmediate.verified.cs new file mode 100644 index 00000000000..0200ad976db --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Reducers.ScheduleImmediate.verified.cs @@ -0,0 +1,31 @@ +//HintName: Reducers.ScheduleImmediate.cs +// +#nullable enable + +partial class Reducers +{ + private static class __ScheduleScheduleImmediateName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(ScheduleImmediate), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleScheduleImmediateName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateScheduleImmediate(PublicTable data) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + new PublicTable.BSATN().Write(writer, data); + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleScheduleImmediateName.Name, + stream + ); + } +} // Reducers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#RegressionMultipleUniqueIndexesHadSameName.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#RegressionMultipleUniqueIndexesHadSameName.verified.cs new file mode 100644 index 00000000000..08d5589debd --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#RegressionMultipleUniqueIndexesHadSameName.verified.cs @@ -0,0 +1,121 @@ +//HintName: RegressionMultipleUniqueIndexesHadSameName.cs +// +#nullable enable + +partial struct RegressionMultipleUniqueIndexesHadSameName + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite +{ + public void ReadFields(System.IO.BinaryReader reader) + { + Unique1 = BSATN.Unique1RW.Read(reader); + Unique2 = BSATN.Unique2RW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.Unique1RW.Write(writer, Unique1); + BSATN.Unique2RW.Write(writer, Unique2); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"RegressionMultipleUniqueIndexesHadSameName {{ Unique1 = {SpacetimeDB.BSATN.StringUtil.GenericToString(Unique1)}, Unique2 = {SpacetimeDB.BSATN.StringUtil.GenericToString(Unique2)} }}"; + + public readonly partial struct BSATN + : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.U32 Unique1RW = new(); + internal static readonly SpacetimeDB.BSATN.U32 Unique2RW = new(); + + public RegressionMultipleUniqueIndexesHadSameName Read(System.IO.BinaryReader reader) + { + var ___result = new RegressionMultipleUniqueIndexesHadSameName(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write( + System.IO.BinaryWriter writer, + RegressionMultipleUniqueIndexesHadSameName value + ) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("Unique1", Unique1RW.GetAlgebraicType(registrar)), + new("Unique2", Unique2RW.GetAlgebraicType(registrar)), + } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashUnique1 = Unique1.GetHashCode(); + var ___hashUnique2 = Unique2.GetHashCode(); + return ___hashUnique1 ^ ___hashUnique2; + } + +#nullable enable + public bool Equals(RegressionMultipleUniqueIndexesHadSameName that) + { + var ___eqUnique1 = this.Unique1.Equals(that.Unique1); + var ___eqUnique2 = this.Unique2.Equals(that.Unique2); + return ___eqUnique1 && ___eqUnique2; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as RegressionMultipleUniqueIndexesHadSameName?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==( + RegressionMultipleUniqueIndexesHadSameName this_, + RegressionMultipleUniqueIndexesHadSameName that + ) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=( + RegressionMultipleUniqueIndexesHadSameName this_, + RegressionMultipleUniqueIndexesHadSameName that + ) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore +} // RegressionMultipleUniqueIndexesHadSameName diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Test.NestingNamespaces.AndClasses.InsertData2.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Test.NestingNamespaces.AndClasses.InsertData2.verified.cs new file mode 100644 index 00000000000..77fcaf513d2 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Test.NestingNamespaces.AndClasses.InsertData2.verified.cs @@ -0,0 +1,34 @@ +//HintName: Test.NestingNamespaces.AndClasses.InsertData2.cs +// +#nullable enable + +namespace Test.NestingNamespaces +{ + partial class AndClasses + { + private static class __ScheduleInsertData2Name + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(InsertData2), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleInsertData2Name() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateInsertData2(PublicTable data) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + new PublicTable.BSATN().Write(writer, data); + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleInsertData2Name.Name, + stream + ); + } + } // AndClasses +} // namespace diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Timers.Init.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Timers.Init.verified.cs new file mode 100644 index 00000000000..f313a9af2fd --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Timers.Init.verified.cs @@ -0,0 +1,31 @@ +//HintName: Timers.Init.cs +// +#nullable enable + +partial class Timers +{ + private static class __ScheduleInitName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(Init), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleInitName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateInit() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleInitName.Name, + stream + ); + } +} // Timers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Timers.SendMessageTimer.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Timers.SendMessageTimer.verified.cs new file mode 100644 index 00000000000..90065b14a30 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Timers.SendMessageTimer.verified.cs @@ -0,0 +1,123 @@ +//HintName: Timers.SendMessageTimer.cs +// +#nullable enable + +partial class Timers +{ + partial struct SendMessageTimer + : System.IEquatable, + SpacetimeDB.BSATN.IStructuralReadWrite + { + public void ReadFields(System.IO.BinaryReader reader) + { + ScheduledId = BSATN.ScheduledIdRW.Read(reader); + ScheduledAt = BSATN.ScheduledAtRW.Read(reader); + Text = BSATN.TextRW.Read(reader); + } + + public void WriteFields(System.IO.BinaryWriter writer) + { + BSATN.ScheduledIdRW.Write(writer, ScheduledId); + BSATN.ScheduledAtRW.Write(writer, ScheduledAt); + BSATN.TextRW.Write(writer, Text); + } + + object SpacetimeDB.BSATN.IStructuralReadWrite.GetSerializer() + { + return new BSATN(); + } + + public override string ToString() => + $"SendMessageTimer {{ ScheduledId = {SpacetimeDB.BSATN.StringUtil.GenericToString(ScheduledId)}, ScheduledAt = {SpacetimeDB.BSATN.StringUtil.GenericToString(ScheduledAt)}, Text = {SpacetimeDB.BSATN.StringUtil.GenericToString(Text)} }}"; + + public readonly partial struct BSATN : SpacetimeDB.BSATN.IReadWrite + { + internal static readonly SpacetimeDB.BSATN.U64 ScheduledIdRW = new(); + internal static readonly SpacetimeDB.ScheduleAt.BSATN ScheduledAtRW = new(); + internal static readonly SpacetimeDB.BSATN.String TextRW = new(); + + public Timers.SendMessageTimer Read(System.IO.BinaryReader reader) + { + var ___result = new Timers.SendMessageTimer(); + ___result.ReadFields(reader); + return ___result; + } + + public void Write(System.IO.BinaryWriter writer, Timers.SendMessageTimer value) + { + value.WriteFields(writer); + } + + public SpacetimeDB.BSATN.AlgebraicType.Ref GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => + registrar.RegisterType( + _ => new SpacetimeDB.BSATN.AlgebraicType.Product( + new SpacetimeDB.BSATN.AggregateElement[] + { + new("ScheduledId", ScheduledIdRW.GetAlgebraicType(registrar)), + new("ScheduledAt", ScheduledAtRW.GetAlgebraicType(registrar)), + new("Text", TextRW.GetAlgebraicType(registrar)), + } + ) + ); + + SpacetimeDB.BSATN.AlgebraicType SpacetimeDB.BSATN.IReadWrite.GetAlgebraicType( + SpacetimeDB.BSATN.ITypeRegistrar registrar + ) => GetAlgebraicType(registrar); + } + + public override int GetHashCode() + { + var ___hashScheduledId = ScheduledId.GetHashCode(); + var ___hashScheduledAt = ScheduledAt == null ? 0 : ScheduledAt.GetHashCode(); + var ___hashText = Text == null ? 0 : Text.GetHashCode(); + return ___hashScheduledId ^ ___hashScheduledAt ^ ___hashText; + } + +#nullable enable + public bool Equals(Timers.SendMessageTimer that) + { + var ___eqScheduledId = this.ScheduledId.Equals(that.ScheduledId); + var ___eqScheduledAt = + this.ScheduledAt == null + ? that.ScheduledAt == null + : this.ScheduledAt.Equals(that.ScheduledAt); + var ___eqText = this.Text == null ? that.Text == null : this.Text.Equals(that.Text); + return ___eqScheduledId && ___eqScheduledAt && ___eqText; + } + + public override bool Equals(object? that) + { + if (that == null) + { + return false; + } + var that_ = that as Timers.SendMessageTimer?; + if (((object?)that_) == null) + { + return false; + } + return Equals(that_); + } + + public static bool operator ==(Timers.SendMessageTimer this_, Timers.SendMessageTimer that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return object.Equals(this_, that); + } + return this_.Equals(that); + } + + public static bool operator !=(Timers.SendMessageTimer this_, Timers.SendMessageTimer that) + { + if (((object?)this_) == null || ((object?)that) == null) + { + return !object.Equals(this_, that); + } + return !this_.Equals(that); + } +#nullable restore + } // SendMessageTimer +} // Timers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Timers.SendScheduledMessage.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Timers.SendScheduledMessage.verified.cs new file mode 100644 index 00000000000..f6a1283b596 --- /dev/null +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Module.net10#Timers.SendScheduledMessage.verified.cs @@ -0,0 +1,33 @@ +//HintName: Timers.SendScheduledMessage.cs +// +#nullable enable + +partial class Timers +{ + private static class __ScheduleSendScheduledMessageName + { + internal static readonly string Name = + global::SpacetimeDB.Internal.Module.ResolveFunctionName( + "server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + nameof(SendScheduledMessage), + null + ); + + // Prevent eager initialization before the root installs namespace placements. + static __ScheduleSendScheduledMessageName() { } + } + + [System.Diagnostics.CodeAnalysis.Experimental("STDB_UNSTABLE")] + public static void VolatileNonatomicScheduleImmediateSendScheduledMessage( + Timers.SendMessageTimer arg + ) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + new Timers.SendMessageTimer.BSATN().Write(writer, arg); + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate( + __ScheduleSendScheduledMessageName.Name, + stream + ); + } +} // Timers diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#ContainsNestedLists.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#ContainsNestedLists.verified.cs index 87362d50f8c..7d1f84bf4e8 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#ContainsNestedLists.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#ContainsNestedLists.verified.cs @@ -110,7 +110,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new( "StringListListArray", StringListListArrayRW.GetAlgebraicType(registrar) - ) + ), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomClass.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomClass.verified.cs index fd03fc1c88c..747b4e001ba 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomClass.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomClass.verified.cs @@ -62,7 +62,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new("IntField", IntFieldRW.GetAlgebraicType(registrar)), new("StringField", StringFieldRW.GetAlgebraicType(registrar)), new("NullableIntField", NullableIntFieldRW.GetAlgebraicType(registrar)), - new("NullableStringField", NullableStringFieldRW.GetAlgebraicType(registrar)) + new("NullableStringField", NullableStringFieldRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomNestedClass.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomNestedClass.verified.cs index f713b9b01ac..0bb9a731fc6 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomNestedClass.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomNestedClass.verified.cs @@ -96,7 +96,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new( "NestedNullableCustomRecord", NestedNullableCustomRecordRW.GetAlgebraicType(registrar) - ) + ), } ) ); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomRecord.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomRecord.verified.cs index f75ef133e9e..0e812263dec 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomRecord.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomRecord.verified.cs @@ -62,7 +62,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new("IntField", IntFieldRW.GetAlgebraicType(registrar)), new("StringField", StringFieldRW.GetAlgebraicType(registrar)), new("NullableIntField", NullableIntFieldRW.GetAlgebraicType(registrar)), - new("NullableStringField", NullableStringFieldRW.GetAlgebraicType(registrar)) + new("NullableStringField", NullableStringFieldRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomStruct.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomStruct.verified.cs index 56afcdd431c..fb4ef83d788 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomStruct.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomStruct.verified.cs @@ -64,7 +64,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new("IntField", IntFieldRW.GetAlgebraicType(registrar)), new("StringField", StringFieldRW.GetAlgebraicType(registrar)), new("NullableIntField", NullableIntFieldRW.GetAlgebraicType(registrar)), - new("NullableStringField", NullableStringFieldRW.GetAlgebraicType(registrar)) + new("NullableStringField", NullableStringFieldRW.GetAlgebraicType(registrar)), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomTaggedEnum.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomTaggedEnum.verified.cs index 78c43d2fb53..01ec183af3e 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomTaggedEnum.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#CustomTaggedEnum.verified.cs @@ -49,10 +49,9 @@ public CustomTaggedEnum Read(System.IO.BinaryReader reader) 1 => new StringVariant(StringVariantRW.Read(reader)), 2 => new NullableIntVariant(NullableIntVariantRW.Read(reader)), 3 => new NullableStringVariant(NullableStringVariantRW.Read(reader)), - _ - => throw new System.InvalidOperationException( - "Invalid tag value, this state should be unreachable." - ) + _ => throw new System.InvalidOperationException( + "Invalid tag value, this state should be unreachable." + ), }; } @@ -91,7 +90,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar new( "NullableStringVariant", NullableStringVariantRW.GetAlgebraicType(registrar) - ) + ), } )); diff --git a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#FormerlyForbiddenFieldNames.verified.cs b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#FormerlyForbiddenFieldNames.verified.cs index 8c9d2c5f5b0..3b143e46d48 100644 --- a/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#FormerlyForbiddenFieldNames.verified.cs +++ b/crates/bindings-csharp/Codegen.Tests/fixtures/server/snapshots/Type#FormerlyForbiddenFieldNames.verified.cs @@ -55,7 +55,7 @@ SpacetimeDB.BSATN.ITypeRegistrar registrar { new("Read", ReadRW.GetAlgebraicType(registrar)), new("Write", WriteRW.GetAlgebraicType(registrar)), - new("GetAlgebraicType", GetAlgebraicTypeRW.GetAlgebraicType(registrar)) + new("GetAlgebraicType", GetAlgebraicTypeRW.GetAlgebraicType(registrar)), } ) ); diff --git a/crates/bindings-csharp/Codegen/Diag.cs b/crates/bindings-csharp/Codegen/Diag.cs index c2374db5b8e..269e59d5b14 100644 --- a/crates/bindings-csharp/Codegen/Diag.cs +++ b/crates/bindings-csharp/Codegen/Diag.cs @@ -361,4 +361,80 @@ string type $"View '{ctx.method.Identifier}' declares primary key '{ctx.primaryKey}', but its type '{ctx.type}' is not supported for view primary keys.", ctx => ctx.primaryKeySyntax ); + + public static readonly ErrorDescriptor<( + ISymbol symbol, + string message + )> InvalidEnvironmentDeclaration = + new(group, "Invalid environment declaration", ctx => $"{ctx.message}", ctx => ctx.symbol); + + public static readonly ErrorDescriptor<( + AttributeData attribute, + string message + )> InvalidNamespace = + new(group, "Invalid namespace mount", ctx => $"{ctx.message}", ctx => ctx.attribute); + + public static readonly ErrorDescriptor<( + string accessor, + string first, + string second + )> NamespaceAccessorCollision = + new( + group, + "Conflicting module accessors", + ctx => + $"Accessor '{ctx.accessor}' is contributed by both '{ctx.first}' and '{ctx.second}'. Mount the conflicting dependency with a distinct accessor.", + _ => Location.None + ); + + public static readonly ErrorDescriptor DependencyNamespaceMounts = + new( + group, + "Dependency declares namespace mounts", + identity => + $"Dependency '{identity}' declares namespace mounts. Only the consuming root may choose dependency placement; move those declarations to the root.", + _ => Location.None + ); + + public static readonly ErrorDescriptor<( + string assembly, + string name, + string declarations + )> MountedRootOnlyDeclarations = + new( + group, + "Root-only declarations in mounted dependency", + ctx => + $"Dependency '{ctx.assembly}' mounted in namespace '{ctx.name}' declares {ctx.declarations}. These declarations are only supported in the root scope. Move them to the root, or omit the namespace declaration so the dependency registers automatically in public. Root-defined RLS may target namespace-qualified tables.", + _ => Location.None + ); + + public static readonly ErrorDescriptor<( + Location location, + string scope, + string name, + string first, + string second + )> GeneratedNameCollision = + new( + group, + "Conflicting generated C# names", + ctx => + $"Generated C# name '{ctx.scope}.{ctx.name}' is used by both {ctx.first} and {ctx.second}. Choose distinct accessors or member names.", + ctx => ctx.location + ); + + public static readonly ErrorDescriptor<( + string root, + string rootPolicy, + string dependency, + string dependencyPolicy + )> ConflictingCaseConversionPolicies = + new( + group, + "Conflicting case conversion policies", + ctx => + $"Root assembly '{ctx.root}' uses case conversion policy '{ctx.rootPolicy}', but dependency '{ctx.dependency}' declares '{ctx.dependencyPolicy}' in the shared public scope. Use the same policy, remove the dependency's setting to inherit the root policy, or mount the dependency in a distinct namespace.", + _ => Location.None + ); } diff --git a/crates/bindings-csharp/Codegen/Environment.cs b/crates/bindings-csharp/Codegen/Environment.cs index 5162abfe8e7..782fe30d69c 100644 --- a/crates/bindings-csharp/Codegen/Environment.cs +++ b/crates/bindings-csharp/Codegen/Environment.cs @@ -13,37 +13,43 @@ namespace SpacetimeDB.Codegen; [Generator] public sealed class EnvironmentGenerator : IIncrementalGenerator { - private static readonly DiagnosticDescriptor InvalidDeclaration = - new( - "STDBENV001", - "Invalid environment declaration", - "{0}", - "SpacetimeDB", - DiagnosticSeverity.Error, - isEnabledByDefault: true - ); - public void Initialize(IncrementalGeneratorInitializationContext context) { - var declarations = context + var declarations = Declarations(context); + var assembly = context.CompilationProvider.Select( + (compilation, _) => + ( + SharedContexts: Module.UsesSharedContexts(compilation), + Namespace: Module.AssemblyNamespace(compilation.Assembly) + ) + ); + context.RegisterSourceOutput( + declarations.Combine(assembly), + (ctx, input) => + Generate(ctx, input.Left, input.Right.SharedContexts, input.Right.Namespace) + ); + } + + internal static IncrementalValueProvider> Declarations( + IncrementalGeneratorInitializationContext context + ) => + context .SyntaxProvider.ForAttributeWithMetadataName( "SpacetimeDB.EnvAttribute", (_, _) => true, (ctx, _) => (INamedTypeSymbol)ctx.TargetSymbol ) .Collect(); - context.RegisterSourceOutput(declarations, Generate); - } - private static void Generate( - SourceProductionContext context, - ImmutableArray types + internal static string RegistrationCode(ImmutableArray types) => + string.Join("\n", Parse(types, true, (_, _) => { }).Registrations); + + private static (List Properties, List Registrations) Parse( + ImmutableArray types, + bool sharedContexts, + Action Report ) { - void Report(ISymbol symbol, string message) => - context.ReportDiagnostic( - Diagnostic.Create(InvalidDeclaration, symbol.Locations.FirstOrDefault(), message) - ); if (types.Length > 1) { foreach (var type in types) @@ -54,7 +60,9 @@ void Report(ISymbol symbol, string message) => .Where(field => !field.IsImplicitlyDeclared) .ToArray(); if (fields.Length > 256 && types.Length != 0) + { Report(types[0], "An environment schema may declare at most 256 variables."); + } var keys = new HashSet(StringComparer.Ordinal); var properties = new List(); @@ -119,7 +127,7 @@ void Report(ISymbol symbol, string message) => : $"new global::SpacetimeDB.Internal.EnvVarType.Union(new global::System.Collections.Generic.List {{ {string.Join(", ", strings.Select(Literal))} }})"; } registrations.Add( - $"global::SpacetimeDB.Internal.Module.RegisterEnvironment(new({Literal(name)}, {constraint}, {(optional ? "true" : "false")}));" + $"{(sharedContexts ? "builder" : "global::SpacetimeDB.Internal.Module")}.RegisterEnvironment(new({Literal(name)}, {constraint}, {(optional ? "true" : "false")}));" ); // Preserve the checked generic method, including a key literally // named Get, and inherited object members. Keywords are escaped @@ -135,13 +143,55 @@ void Report(ISymbol symbol, string message) => or "GetType" or "MemberwiseClone" ) + { continue; - var read = $"Get({Literal(name)})"; + } + + var read = $"{(sharedContexts ? "env." : "")}Get({Literal(name)})"; if (!optional) + { read += " ?? throw new global::System.InvalidOperationException(\"Required environment value is absent\")"; + } + properties.Add($"public string{(optional ? "?" : "")} @{name} => {read};"); } + return (properties, registrations); + } + + private static void Generate( + SourceProductionContext context, + ImmutableArray types, + bool sharedContexts, + string assemblyNamespace + ) + { + var (properties, registrations) = Parse( + types, + sharedContexts, + (symbol, message) => + context.ReportDiagnostic( + ErrorDescriptor.InvalidEnvironmentDeclaration.ToDiag((symbol, message)) + ) + ); + if (sharedContexts) + { + context.AddSource( + "Environment.g.cs", + $$""" + // + #nullable enable + namespace {{assemblyNamespace}} { + public static class EnvironmentExtensions { + extension(global::SpacetimeDB.DatabaseEnvironment env) { + {{string.Join("\n", properties)}} + } + } + } + """ + ); + return; + } context.AddSource( "Environment.g.cs", $$""" diff --git a/crates/bindings-csharp/Codegen/GeneratedNames.cs b/crates/bindings-csharp/Codegen/GeneratedNames.cs new file mode 100644 index 00000000000..cede1fc020c --- /dev/null +++ b/crates/bindings-csharp/Codegen/GeneratedNames.cs @@ -0,0 +1,30 @@ +namespace SpacetimeDB.Codegen; + +using Microsoft.CodeAnalysis.CSharp; + +internal delegate void GeneratedNameCollisionReporter( + string scope, + string name, + string firstContributor, + string secondContributor +); + +// Compare symbols in their emitted C# scope; @ escaping does not distinguish names. +sealed class GeneratedNames(GeneratedNameCollisionReporter report) +{ + private readonly Dictionary<(string Scope, string Name), string> declarations = []; + + internal void Add(string scope, string identifier, string contributor) + { + var name = SyntaxFactory.ParseToken(identifier).ValueText; + var key = (scope, name); + if (declarations.TryGetValue(key, out var previous)) + { + report(scope, name, previous, contributor); + } + else + { + declarations.Add(key, contributor); + } + } +} diff --git a/crates/bindings-csharp/Codegen/Module.cs b/crates/bindings-csharp/Codegen/Module.cs index 29fc16d2cfc..d4567d2ea07 100644 --- a/crates/bindings-csharp/Codegen/Module.cs +++ b/crates/bindings-csharp/Codegen/Module.cs @@ -1,8 +1,11 @@ namespace SpacetimeDB.Codegen; using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -490,6 +493,39 @@ record TableDeclaration : BaseTypeDeclaration public readonly EquatableArray Indexes; private readonly bool isRowStruct; + private readonly string assemblyIdentity; + private readonly bool sharedContexts; + private readonly string handlesNamespace; + + private string TableHandlesNamespace => handlesNamespace + ".TableHandles"; + private string ViewHandlesNamespace => handlesNamespace + ".ViewHandles"; + + private string LookupName(string localName) => + sharedContexts + ? $"global::SpacetimeDB.Internal.Module.ResolveName({SymbolDisplay.FormatLiteral(assemblyIdentity, true)}, {SymbolDisplay.FormatLiteral(localName, true)})" + : SymbolDisplay.FormatLiteral(localName, true); + + private string HandleLookupName(string localName) => + sharedContexts ? "__resolvedName" : LookupName(localName); + + private string HandleLookupNameCache(string typeName, string localName) => + sharedContexts + ? $$""" + private static readonly string __resolvedName = {{LookupName(localName)}}; + // Prevent eager initialization before the root installs namespace placements. + static {{typeName}}() { } + """ + : ""; + + private string IndexInstanceCache(string typeName, string identifier) => + sharedContexts + ? $$""" + private static {{typeName}}? __{{identifier.TrimStart('@')}}; + """ + : ""; + + private string IndexInstance(string identifier) => + sharedContexts ? $"__{identifier.TrimStart('@')} ??= new()" : "new()"; public int? GetColumnIndex(AttributeData attrContext, string name, DiagReporter diag) { @@ -509,6 +545,13 @@ public TableDeclaration(GeneratorAttributeSyntaxContext context, DiagReporter di { var typeSyntax = (TypeDeclarationSyntax)context.TargetNode; + var compilation = context.SemanticModel.Compilation; + assemblyIdentity = compilation.Assembly.Identity.ToString(); + sharedContexts = Module.UsesSharedContexts(compilation); + handlesNamespace = sharedContexts + ? Module.AssemblyNamespace(compilation.Assembly) + : "SpacetimeDB.Internal"; + isRowStruct = ((INamedTypeSymbol)context.TargetSymbol).IsValueType; if (Kind is TypeKind.Sum) @@ -551,6 +594,116 @@ public TableDeclaration(GeneratorAttributeSyntaxContext context, DiagReporter di .Select(a => new TableIndex(this, a, diag)) .ToImmutableArray() ); + if (sharedContexts) + { + ValidateGeneratedNames(diag, typeSyntax.GetLocation()); + } + } + + private void ValidateGeneratedNames(DiagReporter diag, Location location) + { + var names = new GeneratedNames( + (scope, name, first, second) => + diag.Report( + ErrorDescriptor.GeneratedNameCollision, + (location, scope, name, first, second) + ) + ); + foreach (var table in TableAccessors) + { + var owner = $"table '{table.Name}' on '{FullName}'"; + var writable = $"{TableHandlesNamespace}.{table.Name}"; + var readOnly = $"{ViewHandlesNamespace}.{table.Name}ReadOnly"; + names.Add(writable, table.Identifier, "enclosing table handle"); + names.Add(readOnly, table.Identifier + "ReadOnly", "enclosing read-only handle"); + foreach ( + var member in new[] + { + "LookupName", + "ReadGenFields", + "MakeTableDesc", + "MakeScheduleDesc", + "Count", + "Iter", + "Insert", + "Delete", + "Clear", + } + ) + names.Add(writable, member, "generated table member"); + foreach (var member in new[] { "__resolvedName", "Count", "Iter" }) + names.Add(readOnly, member, "generated read-only table member"); + + void Index(string identifier, bool unique, string contributor) + { + foreach (var scope in new[] { writable, readOnly }) + { + names.Add(scope, identifier, contributor); + names.Add( + scope, + "__" + identifier.TrimStart('@'), + $"cache field for {contributor}" + ); + names.Add( + scope, + identifier + (unique && scope == writable ? "UniqueIndex" : "Index"), + $"index type for {contributor}" + ); + } + } + foreach ( + var constraint in GetConstraints(table, ColumnAttrs.Unique) + .Where(c => c.Col.IsEquatable) + ) + Index( + constraint.Col.Identifier, + true, + $"unique column '{constraint.Col.Name}' of {owner}" + ); + foreach (var index in GetIndexes(table).Where(i => i.AccessorName.Length != 0)) + Index(index.AccessorIdentifier, false, $"index '{index.AccessorName}' of {owner}"); + + foreach (var container in new[] { "Tables", "ReadOnlyTables", "Queries" }) + if (table.Name == container) + { + names.Add(container, container, "enclosing descriptor container"); + } + + foreach (var container in new[] { "Tables", "ReadOnlyTables", "Queries" }) + names.Add(container, table.Identifier, owner); + if (table.Name is "GetType" or "ToString" or "Equals" or "GetHashCode") + { + diag.Report( + ErrorDescriptor.GeneratedNameCollision, + ( + location, + "context database/query receiver", + table.Name, + "existing receiver member", + owner + ) + ); + } + + var cols = table.Identifier + "Cols"; + names.Add(cols, cols, "enclosing query columns type"); + foreach (var column in Members) + names.Add(cols, column.Identifier, $"column '{column.Name}' of {owner}"); + var ixCols = table.Identifier + "IxCols"; + names.Add(ixCols, ixCols, "enclosing indexed query columns type"); + var indexedPositions = new HashSet( + GetConstraints(table, ColumnAttrs.PrimaryKey | ColumnAttrs.Unique) + .Select(c => c.Pos) + ); + foreach (var index in GetIndexes(table)) + foreach (var column in index.Columns.Array) + indexedPositions.Add(column.Index); + foreach (var position in indexedPositions) + { + var column = Members[position]; + names.Add(ixCols, column.Identifier, $"indexed column '{column.Name}' of {owner}"); + } + } } protected override ColumnDeclaration ConvertMember( @@ -564,7 +717,8 @@ public IEnumerable GenerateTableAccessorFilters(TableAccessor tableAcces var vis = SyntaxFacts.GetText(Visibility); var globalName = $"global::{FullName}"; - var uniqueIndexBase = isRowStruct ? "UniqueIndex" : "RefUniqueIndex"; + var uniqueIndexBase = + "global::SpacetimeDB.Internal." + (isRowStruct ? "UniqueIndex" : "RefUniqueIndex"); foreach (var ct in GetConstraints(tableAccessor, ColumnAttrs.Unique)) { @@ -581,14 +735,20 @@ public IEnumerable GenerateTableAccessorFilters(TableAccessor tableAcces : ""; yield return $$""" {{vis}} sealed class {{f.Identifier}}UniqueIndex : {{uniqueIndexBase}}<{{tableAccessor.Identifier}}, {{globalName}}, {{f.Type.Name}}, {{f.Type.BSATNName}}> { - internal {{f.Identifier}}UniqueIndex() : base("{{standardIndexName}}") {} + {{HandleLookupNameCache(f.Identifier + "UniqueIndex", standardIndexName)}} + internal {{f.Identifier}}UniqueIndex() : base({{HandleLookupName( + standardIndexName + )}}) {} // Important: don't move this to the base class. // C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based // `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another. public {{globalName}}? Find({{f.Type.Name}} key) => FindSingle(key); {{updateMethod}} } - {{vis}} {{f.Identifier}}UniqueIndex {{f.Identifier}} => new(); + {{IndexInstanceCache(f.Identifier + "UniqueIndex", f.Identifier)}} + {{vis}} {{f.Identifier}}UniqueIndex {{f.Identifier}} => {{IndexInstance( + f.Identifier + )}}; """; } @@ -608,7 +768,10 @@ public IEnumerable GenerateTableAccessorFilters(TableAccessor tableAcces var standardIndexName = index.StandardIndexName(tableAccessor); yield return $$""" - {{vis}} sealed class {{identifierName}}Index() : SpacetimeDB.Internal.IndexBase<{{globalName}}>("{{standardIndexName}}") { + {{vis}} sealed class {{identifierName}}Index() : SpacetimeDB.Internal.IndexBase<{{globalName}}>({{HandleLookupName( + standardIndexName + )}}) { + {{HandleLookupNameCache(identifierName + "Index", standardIndexName)}} """; for (var n = 0; n < members.Length; n++) @@ -651,7 +814,7 @@ public ulong Delete({{argsBounds}}) => """; } - yield return $"}}\n {vis} {identifierName}Index {identifierName} => new();\n"; + yield return $"}}\n {IndexInstanceCache(identifierName + "Index", identifierName)}\n {vis} {identifierName}Index {identifierName} => {IndexInstance(identifierName)};\n"; } } @@ -677,17 +840,23 @@ private IEnumerable GenerateReadOnlyAccessorFilters(TableAccessor tableA yield return $$$""" public sealed class {{{f.Identifier}}}Index : {{{uniqueIndexBase}}}< - global::SpacetimeDB.Internal.ViewHandles.{{{tableAccessor.Identifier}}}ReadOnly, + global::{{{ViewHandlesNamespace}}}.{{{tableAccessor.Identifier}}}ReadOnly, {{{globalName}}}, {{{f.Type.Name}}}, {{{f.Type.BSATNName}}}> { - internal {{{f.Identifier}}}Index() : base("{{{standardIndexName}}}") { } + {{{HandleLookupNameCache(f.Identifier + "Index", standardIndexName)}}} + internal {{{f.Identifier}}}Index() : base({{{HandleLookupName( + standardIndexName + )}}}) { } public {{{globalName}}}? Find({{{f.Type.Name}}} key) => FindSingle(key); } - public {{{f.Identifier}}}Index {{{f.Identifier}}} => new(); + {{{IndexInstanceCache(f.Identifier + "Index", f.Identifier)}}} + public {{{f.Identifier}}}Index {{{f.Identifier}}} => {{{IndexInstance( + f.Identifier + )}}}; """; } @@ -709,7 +878,10 @@ public sealed class {{{f.Identifier}}}Index public sealed class {{{identifierName}}}Index : global::SpacetimeDB.Internal.ReadOnlyIndexBase<{{{globalName}}}> { - internal {{{identifierName}}}Index() : base("{{{standardIndexName}}}") {} + {{{HandleLookupNameCache(identifierName + "Index", standardIndexName)}}} + internal {{{identifierName}}}Index() : base({{{HandleLookupName( + standardIndexName + )}}}) {} """, }; @@ -753,7 +925,9 @@ public sealed class {{{identifierName}}}Index ); } - blocks.Add($"}}\n{vis} {identifierName}Index {identifierName} => new();"); + blocks.Add( + $"}}\n{IndexInstanceCache(identifierName + "Index", identifierName)}\n{vis} {identifierName}Index {identifierName} => {IndexInstance(identifierName)};" + ); yield return string.Join("\n", blocks); } } @@ -799,6 +973,7 @@ public IEnumerable GenerateTableAccessors() globalName, $$$""" {{{SyntaxFacts.GetText(Visibility)}}} readonly struct {{{accessorIdentifier}}} : {{{iTable}}} { + {{{(sharedContexts ? $"public static string LookupName => {LookupName(v.Name)};" : "")}}} public static {{{globalName}}} ReadGenFields(System.IO.BinaryReader reader, {{{globalName}}} row) { {{{string.Join( "\n", @@ -856,7 +1031,7 @@ v.Scheduled is { } scheduled {{{string.Join("\n", GenerateTableAccessorFilters(v))}}} } """, - $"{SyntaxFacts.GetText(Visibility)} global::SpacetimeDB.Internal.TableHandles.{accessorIdentifier} {accessorIdentifier} => new();" + $"{SyntaxFacts.GetText(Visibility)} global::{TableHandlesNamespace}.{accessorIdentifier} {accessorIdentifier} => new();" ); } } @@ -889,7 +1064,10 @@ public IEnumerable GenerateReadOnlyAccessors() {{{visibility}}} sealed class {{{accessorIdentifier}}}ReadOnly : global::SpacetimeDB.Internal.ReadOnlyTableView<{{{globalName}}}> { - internal {{{accessorIdentifier}}}ReadOnly() : base("{{{accessor.Name}}}") { } + {{{HandleLookupNameCache(accessorIdentifier + "ReadOnly", accessor.Name)}}} + internal {{{accessorIdentifier}}}ReadOnly() : base({{{HandleLookupName( + accessor.Name + )}}}) { } /// /// Returns the number of rows in this table. @@ -902,12 +1080,13 @@ public IEnumerable GenerateReadOnlyAccessors() {{{readOnlyIndexDecls}}} } """, - $"{visibility} global::SpacetimeDB.Internal.ViewHandles.{accessorIdentifier}ReadOnly {accessorIdentifier} => new();" + $"{visibility} global::{ViewHandlesNamespace}.{accessorIdentifier}ReadOnly {accessorIdentifier} => new();" ); } } - public IEnumerable GenerateQueryBuilderMembers() + // useExtensions means we're in a .NET 10 context + public IEnumerable GenerateQueryBuilderMembers(bool useExtensions = false) { if (Kind is TypeKind.Sum) { @@ -929,8 +1108,7 @@ string ColDecl(ColumnDeclaration col) var typeName = col.Type.Name; var isNullable = typeName.EndsWith("?", StringComparison.Ordinal); var valueTypeName = isNullable ? typeName[..^1] : typeName; - var colType = isNullable ? "global::SpacetimeDB.Col" : "global::SpacetimeDB.Col"; - return $"public readonly {colType}<{globalRowName}, {valueTypeName}> {col.Identifier};"; + return $"public readonly global::SpacetimeDB.Col<{globalRowName}, {valueTypeName}> {col.Identifier};"; } string ColInit(ColumnDeclaration col) @@ -938,14 +1116,13 @@ string ColInit(ColumnDeclaration col) var typeName = col.Type.Name; var isNullable = typeName.EndsWith("?", StringComparison.Ordinal); var valueTypeName = isNullable ? typeName[..^1] : typeName; - var colType = isNullable ? "global::SpacetimeDB.Col" : "global::SpacetimeDB.Col"; - return $"{col.Identifier} = new {colType}<{globalRowName}, {valueTypeName}>(tableName, \"{col.Name}\");"; + return $"{col.Identifier} = new global::SpacetimeDB.Col<{globalRowName}, {valueTypeName}>(tableName, \"{col.Name}\");"; } - var colsDecls = string.Join("\n ", Members.Select(ColDecl)); - var colsInits = string.Join("\n ", Members.Select(ColInit)); + var colsDecls = string.Join("\n ", Members.Select(ColDecl)); + var colsInits = string.Join("\n ", Members.Select(ColInit)); - var ixPositions = new global::System.Collections.Generic.HashSet(); + var ixPositions = new HashSet(); foreach (var c in GetConstraints(accessor, ColumnAttrs.PrimaryKey | ColumnAttrs.Unique)) { ixPositions.Add(c.Pos); @@ -970,10 +1147,7 @@ string IxColDecl(ColumnDeclaration col) var typeName = col.Type.Name; var isNullable = typeName.EndsWith("?", StringComparison.Ordinal); var valueTypeName = isNullable ? typeName[..^1] : typeName; - var colType = isNullable - ? "global::SpacetimeDB.IxCol" - : "global::SpacetimeDB.IxCol"; - return $"public readonly {colType}<{globalRowName}, {valueTypeName}> {col.Identifier};"; + return $"public readonly global::SpacetimeDB.IxCol<{globalRowName}, {valueTypeName}> {col.Identifier};"; } string IxColInit(ColumnDeclaration col) @@ -981,21 +1155,61 @@ string IxColInit(ColumnDeclaration col) var typeName = col.Type.Name; var isNullable = typeName.EndsWith("?", StringComparison.Ordinal); var valueTypeName = isNullable ? typeName[..^1] : typeName; - var colType = isNullable - ? "global::SpacetimeDB.IxCol" - : "global::SpacetimeDB.IxCol"; - return $"{col.Identifier} = new {colType}<{globalRowName}, {valueTypeName}>(tableName, \"{col.Name}\");"; + return $"{col.Identifier} = new global::SpacetimeDB.IxCol<{globalRowName}, {valueTypeName}>(tableName, \"{col.Name}\");"; } - var ixColsDecls = string.Join("\n ", ixMembers.Select(IxColDecl)); - var ixColsInits = string.Join("\n ", ixMembers.Select(IxColInit)); + var ixColsDecls = string.Join("\n ", ixMembers.Select(IxColDecl)); + var ixColsInits = string.Join("\n ", ixMembers.Select(IxColInit)); + var nameType = useExtensions ? "global::SpacetimeDB.SqlTableName" : "string"; + var queryType = + $"global::SpacetimeDB.Table<{globalRowName}, {colsTypeName}, {ixColsTypeName}>"; + var queryMember = useExtensions + ? $$""" + public static partial class AssemblyDescriptor + { + private static class {{accessorIdentifier}}SqlNameCache + { + internal static readonly global::SpacetimeDB.SqlTableName Name = + global::SpacetimeDB.Internal.Module.ResolveSqlName({{SymbolDisplay.FormatLiteral( + assemblyIdentity, + true + )}}, {{SymbolDisplay.FormatLiteral(tableName, true)}}); + // Prevent eager initialization before the root installs namespace placements. + static {{accessorIdentifier}}SqlNameCache() { } + } + + public readonly partial struct Queries + { + {{vis}} {{queryType}} {{accessorIdentifier}}() + { + var tableName = {{accessorIdentifier}}SqlNameCache.Name; + return new(tableName, new {{colsTypeName}}(tableName), new {{ixColsTypeName}}(tableName)); + } + } + } + + public static partial class QueryTableExtensions + { + extension(global::SpacetimeDB.QueryBuilder from) + { + {{vis}} {{queryType}} {{accessorIdentifier}}() => new AssemblyDescriptor.Queries().{{accessorIdentifier}}(); + } + } + """ + : $$""" + public readonly partial struct QueryBuilder + { + {{vis}} {{queryType}} {{accessorIdentifier}}() => + new("{{tableName}}", new {{colsTypeName}}("{{tableName}}"), new {{ixColsTypeName}}("{{tableName}}")); + } + """; yield return $$""" {{vis}} readonly struct {{colsTypeName}} { {{colsDecls}} - internal {{colsTypeName}}(string tableName) + internal {{colsTypeName}}({{nameType}} tableName) { {{colsInits}} } @@ -1005,17 +1219,13 @@ string IxColInit(ColumnDeclaration col) { {{ixColsDecls}} - internal {{ixColsTypeName}}(string tableName) + internal {{ixColsTypeName}}({{nameType}} tableName) { {{ixColsInits}} } } - public readonly partial struct QueryBuilder - { - {{vis}} global::SpacetimeDB.Table<{{globalRowName}}, {{colsTypeName}}, {{ixColsTypeName}}> {{accessorIdentifier}}() => - new("{{tableName}}", new {{colsTypeName}}("{{tableName}}"), new {{ixColsTypeName}}("{{tableName}}")); - } + {{queryMember}} """; } } @@ -1392,7 +1602,7 @@ public string GenerateViewDef(uint Index) return null; } - return $"SpacetimeDB.Internal.Module.RegisterViewPrimaryKey(\"{EscapeStringLiteral(Name)}\", [\"{EscapeStringLiteral(PrimaryKey)}\"]);"; + return $"builder.RegisterViewPrimaryKey(\"{EscapeStringLiteral(Name)}\", [\"{EscapeStringLiteral(PrimaryKey)}\"]);"; } /// @@ -1504,6 +1714,7 @@ public static byte[] Invoke( /// record ReducerDeclaration { + private readonly string? declaringAssembly; public readonly string Name; public readonly string? CanonicalName; public readonly ReducerKind Kind; @@ -1516,6 +1727,9 @@ record ReducerDeclaration public ReducerDeclaration(GeneratorAttributeSyntaxContext context, DiagReporter diag) { + declaringAssembly = Module.UsesSharedContexts(context.SemanticModel.Compilation) + ? context.SemanticModel.Compilation.Assembly.Identity.ToString() + : null; var methodSyntax = (MethodDeclarationSyntax)context.TargetNode; var method = (IMethodSymbol)context.TargetSymbol; var attr = context.Attributes.Single().ParseAs(); @@ -1596,6 +1810,28 @@ public static void Invoke(BinaryReader reader, SpacetimeDB.Internal.IReducerCont public Scope.Extensions GenerateSchedule() { var extensions = new Scope.Extensions(Scope, FullName); + var functionName = string.IsNullOrEmpty(CanonicalName) + ? $"nameof({Identifier})" + : SymbolDisplay.FormatLiteral(CanonicalName!, true); + if (declaringAssembly is not null) + { + var cacheName = $"__Schedule{Name}Name"; + extensions.Contents.Append( + $$""" + private static class {{cacheName}} + { + internal static readonly string Name = global::SpacetimeDB.Internal.Module.ResolveFunctionName({{SymbolDisplay.FormatLiteral( + declaringAssembly, + true + )}}, nameof({{Identifier}}), {{(string.IsNullOrEmpty(CanonicalName) ? "null" : SymbolDisplay.FormatLiteral(CanonicalName!, true))}}); + // Prevent eager initialization before the root installs namespace placements. + static {{cacheName}}() { } + } + + """ + ); + functionName = cacheName + ".Name"; + } // Mark the API as unstable. We use name `STDB_UNSTABLE` because: // 1. It's a close equivalent of the `unstable` Cargo feature in Rust. @@ -1614,7 +1850,7 @@ public Scope.Extensions GenerateSchedule() "\n", Args.Select(a => $"new {a.Type.ToBSATNString()}().Write(writer, {a.Identifier});") )}} - SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate(nameof({{Identifier}}), stream); + SpacetimeDB.Internal.IReducer.VolatileNonatomicScheduleImmediate({{functionName}}, stream); } """ ); @@ -1628,6 +1864,7 @@ public Scope.Extensions GenerateSchedule() /// record ProcedureDeclaration { + private readonly string? declaringAssembly; public readonly string Name; public readonly string? CanonicalName; public readonly string FullName; @@ -1643,6 +1880,9 @@ record ProcedureDeclaration public ProcedureDeclaration(GeneratorAttributeSyntaxContext context, DiagReporter diag) { + declaringAssembly = Module.UsesSharedContexts(context.SemanticModel.Compilation) + ? context.SemanticModel.Compilation.Assembly.Identity.ToString() + : null; var methodSyntax = (MethodDeclarationSyntax)context.TargetNode; var method = (IMethodSymbol)context.TargetSymbol; var attr = context.Attributes.Single().ParseAs(); @@ -1817,6 +2057,28 @@ public static byte[] Invoke(BinaryReader reader, SpacetimeDB.Internal.IProcedure public Scope.Extensions GenerateSchedule() { var extensions = new Scope.Extensions(Scope, FullName); + var functionName = string.IsNullOrEmpty(CanonicalName) + ? $"nameof({Identifier})" + : SymbolDisplay.FormatLiteral(CanonicalName!, true); + if (declaringAssembly is not null) + { + var cacheName = $"__Schedule{Name}Name"; + extensions.Contents.Append( + $$""" + private static class {{cacheName}} + { + internal static readonly string Name = global::SpacetimeDB.Internal.Module.ResolveFunctionName({{SymbolDisplay.FormatLiteral( + declaringAssembly, + true + )}}, nameof({{Identifier}}), {{(string.IsNullOrEmpty(CanonicalName) ? "null" : SymbolDisplay.FormatLiteral(CanonicalName!, true))}}); + // Prevent eager initialization before the root installs namespace placements. + static {{cacheName}}() { } + } + + """ + ); + functionName = cacheName + ".Name"; + } // Mark the API as unstable. We use name `STDB_UNSTABLE` because: // 1. It's a close equivalent of the `unstable` Cargo feature in Rust. @@ -1835,7 +2097,7 @@ public Scope.Extensions GenerateSchedule() "\n", Args.Select(a => $"new {a.Type.ToBSATNString()}().Write(writer, {a.Identifier});") )}} - SpacetimeDB.Internal.ProcedureExtensions.VolatileNonatomicScheduleImmediate(nameof({{Identifier}}), stream); + SpacetimeDB.Internal.ProcedureExtensions.VolatileNonatomicScheduleImmediate({{functionName}}, stream); } """ ); @@ -2016,9 +2278,176 @@ DiagReporter diag } } +record AssemblyTableAccessor(string Name, string TypeName); + +record AssemblyDeclaration( + string Identity, + string DescriptorTypeName, + bool DeclaresMounts, + string RootOnlyDeclarations, + string? CaseConversionPolicy, + EquatableArray Tables, + EquatableArray ReadOnlyTables, + EquatableArray Queries +); + [Generator] public class Module : IIncrementalGenerator { + internal static bool UsesSharedContexts(Compilation compilation) => + compilation.SyntaxTrees.Any(tree => + tree.Options is CSharpParseOptions options + && options.PreprocessorSymbolNames.Contains("NET10_0_OR_GREATER") + ); + + internal static string AssemblyNamespace(IAssemblySymbol assembly) + { + var name = Regex.Replace(assembly.Name, @"[^A-Za-z0-9_]", "_"); + + if (name.Length == 0 || char.IsDigit(name[0])) + { + name = "_" + name; + } + + using var sha256 = System.Security.Cryptography.SHA256.Create(); + var hash = sha256.ComputeHash( + System.Text.Encoding.UTF8.GetBytes(assembly.Identity.ToString()) + ); + var suffix = string.Concat(hash.Take(8).Select(b => b.ToString("X2"))); + + return $"SpacetimeDB.Generated.{name}_{suffix}"; + } + + private static string IndentGeneratedCode(string code, int spaces) => + code.Replace("\n", "\n" + new string(' ', spaces)); + + private static EquatableArray DiscoverAssemblies( + Compilation compilation, + CancellationToken cancellationToken + ) + { + cancellationToken.ThrowIfCancellationRequested(); + if ( + !compilation.SyntaxTrees.Any(tree => + tree.Options is CSharpParseOptions options + && options.PreprocessorSymbolNames.Contains("NET10_0_OR_GREATER") + ) + ) + { + return new(ImmutableArray.Empty); + } + + var markerType = compilation.GetTypeByMetadataName("SpacetimeDB.ModuleDescriptorAttribute"); + if (markerType is null) + { + return new(ImmutableArray.Empty); + } + + var visited = new HashSet { compilation.Assembly.Identity }; + var pending = new Stack( + compilation.SourceModule.ReferencedAssemblySymbols + ); + var assemblies = new List(); + while (pending.Count > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + var assembly = pending.Pop(); + if (!visited.Add(assembly.Identity)) + { + continue; + } + + // Unmarked utility assemblies may reference contributing modules. + foreach (var module in assembly.Modules) + { + foreach (var reference in module.ReferencedAssemblySymbols) + { + pending.Push(reference); + } + } + + var marker = assembly + .GetAttributes() + .FirstOrDefault(attribute => + SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, markerType) + ); + if ( + marker is null + || marker.ConstructorArguments.Length != 1 + || marker.ConstructorArguments[0].Kind != TypedConstantKind.Type + || marker.ConstructorArguments[0].Value is not INamedTypeSymbol descriptor + ) + { + continue; + } + + assemblies.Add( + new AssemblyDeclaration( + assembly.Identity.ToString(), + descriptor.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + assembly + .GetAttributes() + .Any(attribute => + attribute.AttributeClass?.ToDisplayString() + == "SpacetimeDB.NamespaceAttribute" + ), + descriptor + .GetMembers("RootOnlyDeclarations") + .OfType() + .FirstOrDefault() + ?.ConstantValue as string + ?? "", + descriptor + .GetMembers("CaseConversionPolicy") + .OfType() + .FirstOrDefault() + ?.ConstantValue as string, + ReadAccessors("Tables"), + ReadAccessors("ReadOnlyTables"), + new( + descriptor + .GetTypeMembers("Queries") + .SelectMany(type => type.GetMembers()) + .OfType() + .Where(method => + method.DeclaredAccessibility == Accessibility.Public + && method.MethodKind == MethodKind.Ordinary + && method.Parameters.IsEmpty + && !method.IsStatic + ) + .Select(method => new AssemblyTableAccessor( + method.Name, + method.ReturnType.ToDisplayString( + SymbolDisplayFormat.FullyQualifiedFormat + ) + )) + .ToImmutableArray() + ) + ) + ); + + EquatableArray ReadAccessors(string container) => + new( + descriptor + .GetTypeMembers(container) + .SelectMany(type => type.GetMembers()) + .OfType() + .Where(property => property.DeclaredAccessibility == Accessibility.Public) + .Select(property => new AssemblyTableAccessor( + property.Name, + property.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + )) + .ToImmutableArray() + ); + } + + return new( + assemblies + .OrderBy(assembly => assembly.Identity, StringComparer.Ordinal) + .ToImmutableArray() + ); + } + private static string EscapeStringLiteral(string s) => s.Replace("\\", "\\\\") .Replace("\"", "\\\"") @@ -2278,7 +2707,10 @@ public void Initialize(IncrementalGeneratorInitializationContext context) "Reducer", context, reducers - .Select((r, ct) => (r.Name, r.FullName, r.CanonicalName, Class: r.GenerateClass())) + .Select( + (r, ct) => + (r.Name, r.FullName, r.CanonicalName, r.Kind, Class: r.GenerateClass()) + ) .WithTrackingName("SpacetimeDB.Reducer.GenerateClass"), r => r.Name, r => r.FullName @@ -2407,12 +2839,137 @@ public void Initialize(IncrementalGeneratorInitializationContext context) .Combine(columnDefaultValues) .Select((tuple, ct) => FlattenModuleOutputInputs(tuple)); + var environment = EnvironmentGenerator + .Declarations(context) + .Select( + (types, _) => + ( + HasDeclarations: types.Length != 0, + Registrations: EnvironmentGenerator.RegistrationCode(types) + ) + ); + var extensionNamespace = context + .CompilationProvider.Select( + (compilation, _) => + ( + Name: AssemblyNamespace(compilation.Assembly), + Identity: compilation.Assembly.Identity.ToString(), + SharedContexts: UsesSharedContexts(compilation) + ) + ) + .Combine(environment) + .Select( + (input, _) => + ( + input.Left.Name, + input.Left.Identity, + input.Left.SharedContexts, + HasEnvironment: input.Right.HasDeclarations, + EnvironmentRegistrations: input.Right.Registrations + ) + ); + + var referencedAssemblies = context.CompilationProvider.Select(DiscoverAssemblies); + var namespaceDeclarations = context + .CompilationProvider.Combine(referencedAssemblies) + .Combine(tableDecls) + .SelectMany( + (input, ct) => + new[] + { + DiagReporter.With( + Location.None, + diag => + NamespaceDeclaration.Parse( + input.Left.Left, + input.Left.Right, + input.Right.SelectMany(t => + t.TableAccessors.Select(a => a.Name) + ), + diag, + ct + ) + ), + } + ) + .ReportDiagnostics(context) + .WithTrackingName("SpacetimeDB.Namespace.Parse") + .Collect(); + // Register the generated source code with the compilation context as part of module publishing // Once the compilation is complete, the generated code will be used to create tables and reducers in the database context.RegisterSourceOutput( - moduleOutputInputs, - (context, inputs) => + moduleOutputInputs + .Combine(extensionNamespace) + .Combine(referencedAssemblies) + .Combine(namespaceDeclarations), + (context, input) => { + var ( + ( + ( + inputs, + ( + extensionNamespaceName, + identity, + sharedContexts, + hasEnvironment, + environmentRegistrations + ) + ), + assemblies + ), + mounts + ) = input; + var handlesNamespace = sharedContexts + ? extensionNamespaceName + : "SpacetimeDB.Internal"; + var mountByIdentity = mounts + .SelectMany(m => m) + .ToDictionary(m => m.AssemblyIdentity, StringComparer.Ordinal); + bool IsChild(AssemblyDeclaration assembly) => + mountByIdentity.TryGetValue(assembly.Identity, out var mount) + && !mount.Accessor.Equals("public", StringComparison.OrdinalIgnoreCase); + var publicScopeAssemblies = assemblies.Where(a => !IsChild(a)).ToArray(); + var mountedAssemblies = assemblies.Where(IsChild).ToArray(); + var registrationOrder = publicScopeAssemblies.Concat(mountedAssemblies).ToArray(); + foreach (var assembly in assemblies.Where(a => a.DeclaresMounts)) + context.ReportDiagnostic( + ErrorDescriptor.DependencyNamespaceMounts.ToDiag(assembly.Identity) + ); + foreach ( + var assembly in mountedAssemblies.Where(a => a.RootOnlyDeclarations.Length != 0) + ) + context.ReportDiagnostic( + ErrorDescriptor.MountedRootOnlyDeclarations.ToDiag( + ( + assembly.Identity, + mountByIdentity[assembly.Identity].Accessor, + assembly.RootOnlyDeclarations + ) + ) + ); + + string GenerateDispatchRouting(string category, string arguments, string unknownId) + { + // Match Main's registration order; each category has its own local IDs. + var descriptors = new[] + { + $"global::{extensionNamespaceName}.AssemblyDescriptor", + }.Concat(registrationOrder.Select(assembly => assembly.DescriptorTypeName)); + var routes = descriptors.Select(descriptor => + $$""" + if ((uint)localId < (uint){{descriptor}}.{{category}}Count) + return {{descriptor}}.CallLocal{{category}}(localId, {{arguments}}); + localId -= {{descriptor}}.{{category}}Count; + """ + ); + return $"if (id < 0) {{ {unknownId} }}\nvar localId = id;\n" + + string.Join("\n", routes) + + "\n" + + unknownId; + } + var ( tableAccessors, settings, @@ -2427,6 +2984,126 @@ public void Initialize(IncrementalGeneratorInitializationContext context) columnDefaultValues ) = inputs; + if (sharedContexts) + { + var generatedNames = new GeneratedNames( + (scope, name, first, second) => + context.ReportDiagnostic( + ErrorDescriptor.GeneratedNameCollision.ToDiag( + (Location.None, scope, name, first, second) + ) + ) + ); + foreach (var table in tableAccessors) + { + var owner = $"table '{table.TableAccessorName}' on '{table.TableName}'"; + generatedNames.Add( + extensionNamespaceName, + EscapeIdentifier(table.TableAccessorName + "Cols"), + owner + ); + generatedNames.Add( + extensionNamespaceName, + EscapeIdentifier(table.TableAccessorName + "IxCols"), + owner + ); + } + } + + string ConsumerAccessors(string container) + { + var members = new List(); + var used = new Dictionary(StringComparer.Ordinal); + foreach (var table in tableAccessors) + used[table.TableAccessorName] = identity; + void Add(string name, string owner, string declaration) + { + if (used.TryGetValue(name, out var previous)) + { + if (container == "Tables") + { + context.ReportDiagnostic( + ErrorDescriptor.NamespaceAccessorCollision.ToDiag( + (name, previous, owner) + ) + ); + } + + return; + } + used.Add(name, owner); + members.Add(declaration); + } + foreach (var assembly in assemblies) + { + if (IsChild(assembly)) + { + var mount = mountByIdentity[assembly.Identity]; + Add( + mount.Accessor, + assembly.Identity, + $"public {assembly.DescriptorTypeName}.{container} {mount.AccessorIdentifier} => new();" + ); + } + else + { + var accessors = container switch + { + "ReadOnlyTables" => assembly.ReadOnlyTables, + "Queries" => assembly.Queries, + _ => assembly.Tables, + }; + var invocation = container == "Queries" ? "()" : ""; + foreach (var table in accessors) + Add( + table.Name, + assembly.Identity, + $"public {table.TypeName} {EscapeIdentifier(table.Name)}{invocation} => new {assembly.DescriptorTypeName}.{container}().{EscapeIdentifier(table.Name)}{invocation};" + ); + } + } + return string.Join("\n", members); + } + var consumerWritableAccessors = ConsumerAccessors("Tables"); + var consumerReadOnlyAccessors = ConsumerAccessors("ReadOnlyTables"); + var consumerQueryAccessors = ConsumerAccessors("Queries"); + + var declaredCasePolicy = + settings.Array.Length == 1 ? settings.Array[0].CaseConversionPolicy : null; + var rootCasePolicy = declaredCasePolicy ?? "SnakeCase"; + + var compositionRegistration = new List + { + "global::SpacetimeDB.Internal.Module.InstallNamespaces(new global::SpacetimeDB.Internal.NamespaceRegistry(" + + SymbolDisplay.FormatLiteral(identity, true) + + $", global::SpacetimeDB.CaseConversionPolicy.{rootCasePolicy}, new (string, string, string?, global::SpacetimeDB.CaseConversionPolicy)[] {{" + + string.Join( + ",", + mountByIdentity.Values.Select(m => + $"({SymbolDisplay.FormatLiteral(m.AssemblyIdentity, true)}, {SymbolDisplay.FormatLiteral(m.Accessor, true)}, {(m.Name is { } name ? SymbolDisplay.FormatLiteral(name, true) : "null")}, global::SpacetimeDB.CaseConversionPolicy.{assemblies.Array.Single(a => a.Identity == m.AssemblyIdentity).CaseConversionPolicy ?? "SnakeCase"})" + ) + ) + + "}));", + $"global::{extensionNamespaceName}.AssemblyDescriptor.Register(global::SpacetimeDB.Internal.Module.RootBuilder);", + }; + foreach (var assembly in publicScopeAssemblies) + compositionRegistration.Add( + $"{assembly.DescriptorTypeName}.Register(global::SpacetimeDB.Internal.Module.RootBuilder);" + ); + for (var i = 0; i < mountedAssemblies.Length; i++) + { + var assembly = mountedAssemblies[i]; + compositionRegistration.Add( + $"var child{i} = new global::SpacetimeDB.Internal.ModuleBuilder();" + ); + compositionRegistration.Add( + $"{assembly.DescriptorTypeName}.Register(child{i}, global::SpacetimeDB.Internal.Module.RootBuilder);" + ); + compositionRegistration.Add( + $"global::SpacetimeDB.Internal.Module.RootBuilder.RegisterSubmodule({SymbolDisplay.FormatLiteral(mountByIdentity[assembly.Identity].Accessor, true)}, {(mountByIdentity[assembly.Identity].Name is { } name ? SymbolDisplay.FormatLiteral(name, true) : "null")}, child{i});" + ); + } + if (settings.Array.Length > 1) { context.ReportDiagnostic( @@ -2445,18 +3122,33 @@ public void Initialize(IncrementalGeneratorInitializationContext context) ); } - var settingsRegistration = - settings.Array.Length == 1 - && settings.Array[0].CaseConversionPolicy is { } policyName - ? $"SpacetimeDB.Internal.Module.SetCaseConversionPolicy(SpacetimeDB.CaseConversionPolicy.{policyName});" - : string.Empty; + // A shared typespace also has one naming policy. Unspecified dependency + // settings inherit the root policy, whose host default is SnakeCase. + foreach (var assembly in publicScopeAssemblies) + { + if ( + assembly.CaseConversionPolicy is { } dependencyPolicy + && dependencyPolicy != rootCasePolicy + ) + { + context.ReportDiagnostic( + ErrorDescriptor.ConflictingCaseConversionPolicies.ToDiag( + (identity, rootCasePolicy, assembly.Identity, dependencyPolicy) + ) + ); + } + } + + var settingsRegistration = declaredCasePolicy is { } policyName + ? $"builder.SetCaseConversionPolicy(SpacetimeDB.CaseConversionPolicy.{policyName});" + : string.Empty; var explicitTableRegistrations = string.Join( "\n", tableDecls.Array.SelectMany(t => t.TableAccessors.Where(a => !string.IsNullOrEmpty(a.CanonicalName)) .Select(a => - $"SpacetimeDB.Internal.Module.RegisterExplicitTableName(\"{EscapeStringLiteral(a.Name)}\", \"{EscapeStringLiteral(a.CanonicalName!)}\");" + $"builder.RegisterExplicitTableName(\"{EscapeStringLiteral(a.Name)}\", \"{EscapeStringLiteral(a.CanonicalName!)}\");" ) ) ); @@ -2466,20 +3158,20 @@ public void Initialize(IncrementalGeneratorInitializationContext context) addReducers .Array.Where(r => !string.IsNullOrEmpty(r.CanonicalName)) .Select(r => - $"SpacetimeDB.Internal.Module.RegisterExplicitFunctionName(\"{EscapeStringLiteral(r.Name)}\", \"{EscapeStringLiteral(r.CanonicalName!)}\");" + $"builder.RegisterExplicitFunctionName(\"{EscapeStringLiteral(r.Name)}\", \"{EscapeStringLiteral(r.CanonicalName!)}\");" ) .Concat( addProcedures .Array.Where(p => !string.IsNullOrEmpty(p.CanonicalName)) .Select(p => - $"SpacetimeDB.Internal.Module.RegisterExplicitFunctionName(\"{EscapeStringLiteral(p.Name)}\", \"{EscapeStringLiteral(p.CanonicalName!)}\");" + $"builder.RegisterExplicitFunctionName(\"{EscapeStringLiteral(p.Name)}\", \"{EscapeStringLiteral(p.CanonicalName!)}\");" ) ) .Concat( views .Array.Where(v => !string.IsNullOrEmpty(v.CanonicalName)) .Select(v => - $"SpacetimeDB.Internal.Module.RegisterExplicitFunctionName(\"{EscapeStringLiteral(v.Name)}\", \"{EscapeStringLiteral(v.CanonicalName!)}\");" + $"builder.RegisterExplicitFunctionName(\"{EscapeStringLiteral(v.Name)}\", \"{EscapeStringLiteral(v.CanonicalName!)}\");" ) ) ); @@ -2491,7 +3183,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) t.GetIndexes(a) .Where(ix => !string.IsNullOrEmpty(ix.CanonicalName)) .Select(ix => - $"SpacetimeDB.Internal.Module.RegisterExplicitIndexName(\"{EscapeStringLiteral(ix.StandardIndexName(a))}\", \"{EscapeStringLiteral(ix.CanonicalName!)}\");" + $"builder.RegisterExplicitIndexName(\"{EscapeStringLiteral(ix.StandardIndexName(a))}\", \"{EscapeStringLiteral(ix.CanonicalName!)}\");" ) ) ) @@ -2499,6 +3191,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) var preRegistrationLines = new[] { + sharedContexts ? environmentRegistrations : "", settingsRegistration, explicitTableRegistrations, explicitFunctionRegistrations, @@ -2507,27 +3200,32 @@ public void Initialize(IncrementalGeneratorInitializationContext context) .Where(s => !string.IsNullOrWhiteSpace(s)) .ToArray(); - var preRegistrations = - preRegistrationLines.Length == 0 - ? string.Empty - : "\n " - + string.Join("\n ", preRegistrationLines) - + "\n"; + var preRegistrations = string.Join("\n", preRegistrationLines); var queryBuilderMembers = string.Join( "\n", tableDecls.Array.SelectMany(t => t.GenerateQueryBuilderMembers()) ); + var queryBuilderExtensionMembers = string.Join( + "\n", + tableDecls.Array.SelectMany(t => + t.GenerateQueryBuilderMembers(useExtensions: true) + ) + ); if (string.IsNullOrWhiteSpace(queryBuilderMembers)) { queryBuilderMembers = "public readonly partial struct QueryBuilder { }"; } - // Don't generate the FFI boilerplate if there are no tables or reducers. + // Don't generate the FFI boilerplate if there are no tables or reducers (or procedures, or views, or ...). if ( tableAccessors.Array.IsEmpty && addReducers.Array.IsEmpty && addProcedures.Array.IsEmpty && addHttpHandlers.Array.IsEmpty + && views.Array.IsEmpty + && rlsFilters.Array.IsEmpty + && assemblies.Array.IsEmpty + && !hasEnvironment ) { return; @@ -2537,25 +3235,35 @@ public void Initialize(IncrementalGeneratorInitializationContext context) $$""" // #nullable enable - // The runtime already defines SpacetimeDB.Internal.LocalReadOnly in Runtime\Internal\Module.cs as an empty partial type. - // This is needed so every module build doesn't generate a full LocalReadOnly type, but just adds on to the existing. - // We extend it here with generated table accessors, and just need to suppress the duplicate-type warning. + // .NET 8 generates a module-local LocalReadOnly which shadows the runtime shell. #pragma warning disable CS0436 #pragma warning disable STDB_UNSTABLE + #if NET10_0_OR_GREATER + global using {{extensionNamespaceName}}; + #endif using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal = SpacetimeDB.Internal; using TxContext = SpacetimeDB.Internal.TxContext; + + #if NET10_0_OR_GREATER + [assembly: global::SpacetimeDB.ModuleDescriptorAttribute( + typeof(global::{{extensionNamespaceName}}.AssemblyDescriptor))] + #endif namespace SpacetimeDB { - {{queryBuilderMembers}} - public static class Handlers { - {{string.Join("\n", addHttpHandlers.Select(r => + #if !NET10_0_OR_GREATER + {{IndentGeneratedCode(queryBuilderMembers, 4)}} + #endif + internal static class Handlers { + {{IndentGeneratedCode(string.Join("\n", addHttpHandlers.Select(r => $"public static readonly global::SpacetimeDB.Handler {EscapeIdentifier(r.Name)} = new(nameof({r.FullName}));" - ))}} + )), 8)}} } + + #if !NET10_0_OR_GREATER public sealed record ReducerContext : DbContext, Internal.IReducerContext { public global::SpacetimeDB.ModuleEnvironment Env => default; public readonly Identity Sender; @@ -2627,7 +3335,6 @@ public Uuid NewUuidV7() return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); } } - public sealed partial class ProcedureContext : global::SpacetimeDB.ProcedureContextBase { public new global::SpacetimeDB.ModuleEnvironment Env => default; private readonly Local _db = new(); @@ -2753,7 +3460,7 @@ internal HandlerTxContext(Internal.TxContext inner) : base(inner) {} } public sealed class Local : global::SpacetimeDB.LocalBase { - {{string.Join("\n", tableAccessors.Select(v => v.Getter))}} + {{IndentGeneratedCode(string.Join("\n", tableAccessors.Select(v => v.Getter)), 8)}} } public sealed record ViewContext : DbContext, Internal.IViewContext @@ -2778,30 +3485,147 @@ public sealed record AnonymousViewContext : DbContext, I internal AnonymousViewContext(Internal.LocalReadOnly db) : base(db) { } } + #endif } - namespace SpacetimeDB.Internal.TableHandles { - {{string.Join("\n", tableAccessors.Select(v => v.TableAccessor))}} + #if NET10_0_OR_GREATER + namespace {{extensionNamespaceName}} { + public static partial class AssemblyDescriptor { + public const string? CaseConversionPolicy = {{(declaredCasePolicy is null ? "null" : SymbolDisplay.FormatLiteral(declaredCasePolicy, true))}}; + public const string RootOnlyDeclarations = {{SymbolDisplay.FormatLiteral(string.Join(", ", new[] { + rlsFilters.Array.Length != 0 ? "row-level security filters" : null, + environmentRegistrations.Length != 0 ? "environment variables" : null + }.Where(value => value is not null).Concat( + addReducers.Where(r => r.Kind != ReducerKind.UserDefined) + .Select(r => $"lifecycle reducer {r.FullName} ({r.Kind})") + )), true)}}; + public const int ReducerCount = {{addReducers.Array.Length}}; + public const int ProcedureCount = {{addProcedures.Array.Length}}; + public const int HttpHandlerCount = {{addHttpHandlers.Array.Length}}; + public const int ViewCount = {{views.Array.Count(v => !v.IsAnonymous)}}; + public const int AnonymousViewCount = {{views.Array.Count(v => v.IsAnonymous)}}; + + public static global::SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink error + ) => global::ModuleRegistration.CallLocalReducer( + id, sender_0, sender_1, sender_2, sender_3, conn_id_0, conn_id_1, timestamp, args, error + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink result_sink + ) => global::ModuleRegistration.CallLocalProcedure( + id, sender_0, sender_1, sender_2, sender_3, conn_id_0, conn_id_1, timestamp, args, result_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + global::SpacetimeDB.Timestamp timestamp, + global::SpacetimeDB.Internal.BytesSource request, + global::SpacetimeDB.Internal.BytesSource request_body, + global::SpacetimeDB.Internal.BytesSink response_sink, + global::SpacetimeDB.Internal.BytesSink response_body_sink + ) => global::ModuleRegistration.CallLocalHttpHandler( + id, timestamp, request, request_body, response_sink, response_body_sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => global::ModuleRegistration.CallLocalView( + id, sender_0, sender_1, sender_2, sender_3, args, sink + ); + + public static global::SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + global::SpacetimeDB.Internal.BytesSource args, + global::SpacetimeDB.Internal.BytesSink sink + ) => global::ModuleRegistration.CallLocalAnonymousView( + id, args, sink + ); + + public static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null) + => global::ModuleRegistration.Register(builder, httpBuilder); + + public readonly struct Tables { + {{IndentGeneratedCode(string.Join("\n", tableAccessors.Select(v => v.Getter)), 12)}} + } + + public readonly struct ReadOnlyTables { + {{IndentGeneratedCode(string.Join("\n", readOnlyAccessors.Select(v => v.ReadOnlyGetter)), 12)}} + } + + public readonly partial struct Queries { } + } + public static class LocalTableExtensions { + extension(global::SpacetimeDB.Local db) { + {{IndentGeneratedCode(string.Join("\n", tableAccessors.Select(v => v.Getter)), 12)}} + {{IndentGeneratedCode(consumerWritableAccessors, 12)}} + } + } + public static class ReadOnlyTableExtensions { + extension(global::SpacetimeDB.Internal.LocalReadOnly db) { + {{IndentGeneratedCode(string.Join("\n", readOnlyAccessors.Select(v => v.ReadOnlyGetter)), 12)}} + {{IndentGeneratedCode(consumerReadOnlyAccessors, 12)}} + } + } + public static partial class QueryTableExtensions { + extension(global::SpacetimeDB.QueryBuilder from) { + {{IndentGeneratedCode(consumerQueryAccessors, 12)}} + } + } + {{IndentGeneratedCode(queryBuilderExtensionMembers, 4)}} + } + #endif + + namespace {{handlesNamespace}}.TableHandles { + {{IndentGeneratedCode(string.Join("\n", tableAccessors.Select(v => v.TableAccessor)), 4)}} } - {{string.Join("\n", + {{IndentGeneratedCode(string.Join("\n", views.Array.Where(v => !v.IsAnonymous) .Select((v, i) => v.GenerateDispatcherClass((uint)i)) .Concat( views.Array.Where(v => v.IsAnonymous) .Select((v, i) => v.GenerateDispatcherClass((uint)i)) ) - )}} + ), 0)}} - namespace SpacetimeDB.Internal.ViewHandles { - {{string.Join("\n", readOnlyAccessors.Array.Select(v => v.ReadOnlyAccessor))}} + namespace {{handlesNamespace}}.ViewHandles { + {{IndentGeneratedCode(string.Join("\n", readOnlyAccessors.Array.Select(v => v.ReadOnlyAccessor)), 4)}} } + #if !NET10_0_OR_GREATER namespace SpacetimeDB.Internal { public sealed partial class LocalReadOnly { - {{string.Join("\n", readOnlyAccessors.Select(v => v.ReadOnlyGetter))}} + {{IndentGeneratedCode(string.Join("\n", readOnlyAccessors.Select(v => v.ReadOnlyGetter)), 8)}} } } + #endif static class ModuleRegistration { // Module host calls are single-threaded in Wasm today, so the generated @@ -2813,11 +3637,11 @@ static class ModuleRegistration { private static byte[] viewArgsBuffer = new byte[0x10_000]; private static byte[] anonymousViewArgsBuffer = new byte[0x10_000]; - {{string.Join("\n", addReducers.Select(r => r.Class))}} + {{IndentGeneratedCode(string.Join("\n", addReducers.Select(r => r.Class)), 4)}} - {{string.Join("\n", addProcedures.Select(r => r.Class))}} + {{IndentGeneratedCode(string.Join("\n", addProcedures.Select(r => r.Class)), 4)}} - {{string.Join("\n", addHttpHandlers.Select(r => r.Class))}} + {{IndentGeneratedCode(string.Join("\n", addHttpHandlers.Select(r => r.Class)), 4)}} public static List ToListOrEmpty(T? value) where T : struct => value is null ? new List() : new List { value.Value }; @@ -2833,65 +3657,84 @@ public static List ToListOrEmpty(T? value) where T : class // Prevent trimming of FFI exports that are invoked from C and not visible to C# trimmer. [DynamicDependency(DynamicallyAccessedMemberTypes.PublicMethods, typeof(ModuleRegistration))] #endif - public static void Main() { - SpacetimeDB.Internal.Module.SetReducerContextConstructor((identity, connectionId, random, time) => new SpacetimeDB.ReducerContext(identity, connectionId, random, time)); - SpacetimeDB.Internal.Module.SetViewContextConstructor(identity => new SpacetimeDB.ViewContext(identity, new SpacetimeDB.Internal.LocalReadOnly())); - SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor(() => new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly())); - SpacetimeDB.Internal.Module.SetProcedureContextConstructor((identity, connectionId, random, time) => new SpacetimeDB.ProcedureContext(identity, connectionId, random, time));{{preRegistrations}} - SpacetimeDB.Internal.Module.SetHandlerContextConstructor((random, time) => new SpacetimeDB.HandlerContext(random, time)); - var __memoryStream = new MemoryStream(); - var __writer = new BinaryWriter(__memoryStream); - - {{string.Join( + public static void Main() => Initialize(); + + internal static void Initialize() { + #if !NET10_0_OR_GREATER + SpacetimeDB.Internal.Module.SetReducerContextConstructor((identity, connectionId, random, time) => new SpacetimeDB.ReducerContext(identity, connectionId, random, time)); + SpacetimeDB.Internal.Module.SetViewContextConstructor(identity => new SpacetimeDB.ViewContext(identity, new SpacetimeDB.Internal.LocalReadOnly())); + SpacetimeDB.Internal.Module.SetAnonymousViewContextConstructor(() => new SpacetimeDB.AnonymousViewContext(new SpacetimeDB.Internal.LocalReadOnly())); + SpacetimeDB.Internal.Module.SetProcedureContextConstructor((identity, connectionId, random, time) => new SpacetimeDB.ProcedureContext(identity, connectionId, random, time)); + SpacetimeDB.Internal.Module.SetHandlerContextConstructor((random, time) => new SpacetimeDB.HandlerContext(random, time)); + #endif + + #if NET10_0_OR_GREATER + {{IndentGeneratedCode(string.Join("\n", compositionRegistration), 8)}} + #else + Register(global::SpacetimeDB.Internal.Module.RootBuilder); + #endif + } + + internal static void Register( + global::SpacetimeDB.Internal.ModuleBuilder builder, + global::SpacetimeDB.Internal.ModuleBuilder? httpBuilder = null) + { + // HTTP routes retain the root routing API even for mounted modules. + httpBuilder ??= builder; + {{IndentGeneratedCode(preRegistrations, 8)}} + var __memoryStream = new MemoryStream(); + var __writer = new BinaryWriter(__memoryStream); + + {{IndentGeneratedCode(string.Join( "\n", addReducers.Select(r => - $"SpacetimeDB.Internal.Module.RegisterReducer<{EscapeIdentifier(r.Name)}>();" + $"builder.RegisterReducer<{EscapeIdentifier(r.Name)}>();" ) - )}} - {{string.Join( + ), 8)}} + {{IndentGeneratedCode(string.Join( "\n", addProcedures.Select(r => - $"SpacetimeDB.Internal.Module.RegisterProcedure<{EscapeIdentifier(r.Name)}>();" + $"builder.RegisterProcedure<{EscapeIdentifier(r.Name)}>();" ) - )}} - {{string.Join( + ), 8)}} + {{IndentGeneratedCode(string.Join( "\n", addHttpHandlers.Select(r => - $"SpacetimeDB.Internal.Module.RegisterHttpHandler<{EscapeIdentifier(r.Name)}>();" + $"httpBuilder.RegisterHttpHandler<{EscapeIdentifier(r.Name)}>();" ) - )}} + ), 8)}} // IMPORTANT: The order in which we register views matters. // It must correspond to the order in which we call `GenerateDispatcherClass`. // See the comment on `GenerateDispatcherClass` for more explanation. - {{string.Join("\n", + {{IndentGeneratedCode(string.Join("\n", views.Array.Where(v => !v.IsAnonymous) - .Select(v => $"SpacetimeDB.Internal.Module.RegisterView<{v.Name}ViewDispatcher>();") + .Select(v => $"builder.RegisterView<{v.Name}ViewDispatcher>();") .Concat( views.Array.Where(v => v.IsAnonymous) - .Select(v => $"SpacetimeDB.Internal.Module.RegisterAnonymousView<{v.Name}ViewDispatcher>();") + .Select(v => $"builder.RegisterAnonymousView<{v.Name}ViewDispatcher>();") ) - )}} + ), 8)}} - {{string.Join("\n", + {{IndentGeneratedCode(string.Join("\n", views.Array.Select(v => v.GenerateViewPrimaryKeyRegistration()) .OfType() - )}} + ), 8)}} - {{string.Join( + {{IndentGeneratedCode(string.Join( "\n", - tableAccessors.Select(t => $"SpacetimeDB.Internal.Module.RegisterTable<{t.TableName}, SpacetimeDB.Internal.TableHandles.{EscapeIdentifier(t.TableAccessorName)}>();") - )}} - {{( + tableAccessors.Select(t => $"builder.RegisterTable<{t.TableName}, global::{handlesNamespace}.TableHandles.{EscapeIdentifier(t.TableAccessorName)}>();") + ), 8)}} + {{IndentGeneratedCode(( httpRouters.Array.FirstOrDefault(r => r.IsValid) is { } router - ? $"SpacetimeDB.Internal.Module.RegisterHttpRouter({router.FullName}());" + ? $"httpBuilder.RegisterHttpRouter({router.FullName}());" : string.Empty - )}} - {{string.Join( + ), 8)}} + {{IndentGeneratedCode(string.Join( "\n", - rlsFilters.Select(f => $"SpacetimeDB.Internal.Module.RegisterClientVisibilityFilter({f.GlobalName});") - )}} - {{string.Join( + rlsFilters.Select(f => $"builder.RegisterClientVisibilityFilter({f.GlobalName});") + ), 8)}} + {{IndentGeneratedCode(string.Join( "\n", columnDefaultValues.Select(d => "{\n" @@ -2900,9 +3743,9 @@ public static void Main() { + "__memoryStream.SetLength(0);\n" + $"value.Write(__writer, {d.Value});\n" + "var array = __memoryStream.ToArray();\n" - + $"SpacetimeDB.Internal.Module.RegisterTableDefaultValue(\"{d.TableName}\", {d.ColumnId}, array);" + + $"builder.RegisterTableDefaultValue(\"{d.TableName}\", {d.ColumnId}, array);" + "\n}\n") - )}} + ), 8)}} } // Export entrypoints live in generated module code so all build modes can @@ -2912,7 +3755,7 @@ public static void Main() { #endif public static void __describe_module__(SpacetimeDB.Internal.BytesSink d) => SpacetimeDB.Internal.Module.__describe_module__(d); - {{string.Join( + {{IndentGeneratedCode(string.Join( "\n\n", addReducers.Select((r, i) => $$""" @@ -2940,9 +3783,9 @@ SpacetimeDB.Internal.BytesSink error } """ ) - )}} + ), 4)}} - {{string.Join( + {{IndentGeneratedCode(string.Join( "\n\n", addProcedures.Select((p, i) => $$""" @@ -2972,9 +3815,9 @@ SpacetimeDB.Internal.BytesSink result_sink } """ ) - )}} + ), 4)}} - {{string.Join( + {{IndentGeneratedCode(string.Join( "\n\n", addHttpHandlers.Select((h, i) => $$""" @@ -3000,9 +3843,9 @@ SpacetimeDB.Internal.BytesSink response_body_sink } """ ) - )}} + ), 4)}} - {{string.Join( + {{IndentGeneratedCode(string.Join( "\n\n", views.Array.Where(v => !v.IsAnonymous).Select((v, i) => $$""" @@ -3028,9 +3871,9 @@ SpacetimeDB.Internal.BytesSink sink } """ ) - )}} + ), 4)}} - {{string.Join( + {{IndentGeneratedCode(string.Join( "\n\n", views.Array.Where(v => v.IsAnonymous).Select((v, i) => $$""" @@ -3052,7 +3895,7 @@ SpacetimeDB.Internal.BytesSink sink } """ ) - )}} + ), 4)}} #if EXPERIMENTAL_WASM_AOT || NET10_0_OR_GREATER [UnmanagedCallersOnly(EntryPoint = "__call_reducer__")] @@ -3068,13 +3911,32 @@ public static SpacetimeDB.Internal.Errno __call_reducer__( SpacetimeDB.Timestamp timestamp, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink error + ) { + #if NET10_0_OR_GREATER + {{IndentGeneratedCode(GenerateDispatchRouting("Reducer", "sender_0, sender_1, sender_2, sender_3, conn_id_0, conn_id_1, timestamp, args, error", "return SpacetimeDB.Internal.Module.WriteReducerError(error, new System.ArgumentOutOfRangeException(nameof(id), id, \"Unknown reducer id\"));"), 8)}} + #else + return CallLocalReducer(id, sender_0, sender_1, sender_2, sender_3, conn_id_0, conn_id_1, timestamp, args, error); + #endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalReducer( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink error ) => id switch { - {{string.Join( + {{IndentGeneratedCode(string.Join( "\n", addReducers.Select((r, i) => $"{i} => __call_reducer_{i}(sender_0, sender_1, sender_2, sender_3, conn_id_0, conn_id_1, timestamp, args, error)," ) - )}} + ), 8)}} _ => SpacetimeDB.Internal.Module.WriteReducerError(error, new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown reducer id")) }; @@ -3092,13 +3954,32 @@ public static SpacetimeDB.Internal.Errno __call_procedure__( SpacetimeDB.Timestamp timestamp, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink result_sink + ) { + #if NET10_0_OR_GREATER + {{IndentGeneratedCode(GenerateDispatchRouting("Procedure", "sender_0, sender_1, sender_2, sender_3, conn_id_0, conn_id_1, timestamp, args, result_sink", "throw new System.ArgumentOutOfRangeException(nameof(id), id, \"Unknown procedure id\");"), 8)}} + #else + return CallLocalProcedure(id, sender_0, sender_1, sender_2, sender_3, conn_id_0, conn_id_1, timestamp, args, result_sink); + #endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalProcedure( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + ulong conn_id_0, + ulong conn_id_1, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink result_sink ) => id switch { - {{string.Join( + {{IndentGeneratedCode(string.Join( "\n", addProcedures.Select((p, i) => $"{i} => __call_procedure_{i}(sender_0, sender_1, sender_2, sender_3, conn_id_0, conn_id_1, timestamp, args, result_sink)," ) - )}} + ), 8)}} _ => throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown procedure id") }; @@ -3112,13 +3993,28 @@ public static SpacetimeDB.Internal.Errno __call_http_handler__( SpacetimeDB.Internal.BytesSource request_body, SpacetimeDB.Internal.BytesSink response_sink, SpacetimeDB.Internal.BytesSink response_body_sink + ) { + #if NET10_0_OR_GREATER + {{IndentGeneratedCode(GenerateDispatchRouting("HttpHandler", "timestamp, request, request_body, response_sink, response_body_sink", "throw new System.ArgumentOutOfRangeException(nameof(id), id, \"Unknown HTTP handler id\");"), 8)}} + #else + return CallLocalHttpHandler(id, timestamp, request, request_body, response_sink, response_body_sink); + #endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalHttpHandler( + int id, + SpacetimeDB.Timestamp timestamp, + SpacetimeDB.Internal.BytesSource request, + SpacetimeDB.Internal.BytesSource request_body, + SpacetimeDB.Internal.BytesSink response_sink, + SpacetimeDB.Internal.BytesSink response_body_sink ) => id switch { - {{string.Join( + {{IndentGeneratedCode(string.Join( "\n", addHttpHandlers.Select((h, i) => $"{i} => __call_http_handler_{i}(timestamp, request, request_body, response_sink, response_body_sink)," ) - )}} + ), 8)}} _ => throw new System.ArgumentOutOfRangeException(nameof(id), id, "Unknown HTTP handler id") }; @@ -3133,13 +4029,29 @@ public static SpacetimeDB.Internal.Errno __call_view__( ulong sender_3, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink sink + ) { + #if NET10_0_OR_GREATER + {{IndentGeneratedCode(GenerateDispatchRouting("View", "sender_0, sender_1, sender_2, sender_3, args, sink", "return UnknownViewId(id);"), 8)}} + #else + return CallLocalView(id, sender_0, sender_1, sender_2, sender_3, args, sink); + #endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalView( + int id, + ulong sender_0, + ulong sender_1, + ulong sender_2, + ulong sender_3, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink ) => id switch { - {{string.Join("\n", + {{IndentGeneratedCode(string.Join("\n", views.Array.Where(v => !v.IsAnonymous) .Select((v, i) => $"{i} => __call_view_{i}(sender_0, sender_1, sender_2, sender_3, args, sink)," ) - )}} + ), 8)}} _ => UnknownViewId(id) }; @@ -3150,13 +4062,25 @@ public static SpacetimeDB.Internal.Errno __call_view_anon__( int id, SpacetimeDB.Internal.BytesSource args, SpacetimeDB.Internal.BytesSink sink + ) { + #if NET10_0_OR_GREATER + {{IndentGeneratedCode(GenerateDispatchRouting("AnonymousView", "args, sink", "return UnknownAnonymousViewId(id);"), 8)}} + #else + return CallLocalAnonymousView(id, args, sink); + #endif + } + + internal static SpacetimeDB.Internal.Errno CallLocalAnonymousView( + int id, + SpacetimeDB.Internal.BytesSource args, + SpacetimeDB.Internal.BytesSink sink ) => id switch { - {{string.Join("\n", + {{IndentGeneratedCode(string.Join("\n", views.Array.Where(v => v.IsAnonymous) .Select((v, i) => $"{i} => __call_view_anon_{i}(args, sink)," ) - )}} + ), 8)}} _ => UnknownAnonymousViewId(id) }; diff --git a/crates/bindings-csharp/Codegen/NamespaceDeclaration.cs b/crates/bindings-csharp/Codegen/NamespaceDeclaration.cs new file mode 100644 index 00000000000..beaace7d237 --- /dev/null +++ b/crates/bindings-csharp/Codegen/NamespaceDeclaration.cs @@ -0,0 +1,258 @@ +namespace SpacetimeDB.Codegen; + +using System.Collections.Immutable; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using static Utils; + +internal record NamespaceDeclaration(string AssemblyIdentity, string Accessor, string? Name) +{ + public string AccessorIdentifier => EscapeIdentifier(Accessor); + + public static EquatableArray Parse( + Compilation compilation, + EquatableArray assemblies, + IEnumerable tableAccessors, + DiagReporter diag, + CancellationToken cancellationToken + ) + { + var attributeType = compilation.GetTypeByMetadataName("SpacetimeDB.NamespaceAttribute"); + var result = ImmutableArray.CreateBuilder(); + if (attributeType is null) + { + return new EquatableArray(result.ToImmutable()); + } + + var identities = new Dictionary(StringComparer.Ordinal); + var accessors = new Dictionary(StringComparer.OrdinalIgnoreCase); + var tables = new HashSet(tableAccessors, StringComparer.Ordinal); + var assemblyIdentities = new HashSet( + assemblies.Select(static assembly => assembly.Identity), + StringComparer.Ordinal + ); + var supported = compilation.SyntaxTrees.Any(static tree => + tree.Options is CSharpParseOptions options + && options.PreprocessorSymbolNames.Contains("NET10_0_OR_GREATER") + // Use the numeric value to keep the analyzer compatible with Roslyn 4.3. + && (int)options.LanguageVersion >= 1400 + ); + + foreach (var attribute in compilation.Assembly.GetAttributes()) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, attributeType)) + { + continue; + } + + var valid = true; + if (!supported) + { + ReportError( + diag, + attribute, + ref valid, + "Namespace mounts require .NET 10 and C# 14." + ); + } + + if ( + attribute.ConstructorArguments.Length != 1 + || attribute.ConstructorArguments[0].Value is not INamedTypeSymbol marker + ) + { + ReportError( + diag, + attribute, + ref valid, + "A namespace mount requires a marker type declared in a module assembly." + ); + continue; + } + + var identity = marker.ContainingAssembly.Identity.ToString(); + if ( + SymbolEqualityComparer.Default.Equals( + marker.ContainingAssembly, + compilation.Assembly + ) + ) + { + ReportError(diag, attribute, ref valid, "The root assembly cannot mount itself."); + } + else if (supported && !assemblyIdentities.Contains(identity)) + { + ReportError( + diag, + attribute, + ref valid, + $"Assembly '{identity}' has no discovered module descriptor." + ); + } + + var accessor = + attribute.NamedArguments.FirstOrDefault(static a => a.Key == "Accessor").Value.Value + as string + ?? ""; + var name = + attribute.NamedArguments.FirstOrDefault(static a => a.Key == "Name").Value.Value + as string; + // Keywords are stored unescaped and escaped only when rendering C#. + if ( + accessor.Length == 0 + || accessor[0] == '@' + || !( + SyntaxFacts.IsValidIdentifier(accessor) + || SyntaxFacts.GetKeywordKind(accessor) != SyntaxKind.None + ) + || SyntaxFactory.ParseToken(EscapeIdentifier(accessor)).ValueText != accessor + ) + { + ReportError( + diag, + attribute, + ref valid, + "Accessor must be a nonempty C# identifier (use keyword names without '@')." + ); + } + + ValidateDatabaseIdentifier(diag, attribute, ref valid, accessor, "Accessor"); + if (name is not null) + { + ValidateDatabaseIdentifier(diag, attribute, ref valid, name, "Name"); + if ( + accessor.Equals("public", StringComparison.OrdinalIgnoreCase) + != name.Equals("public", StringComparison.OrdinalIgnoreCase) + ) + { + ReportError( + diag, + attribute, + ref valid, + "The public scope cannot be renamed or targeted by a different accessor." + ); + } + } + + CheckDuplicate( + diag, + attribute, + ref valid, + identities, + identity, + $"Assembly '{identity}' may only be mounted once." + ); + if (accessor.Length > 0) + { + CheckDuplicate( + diag, + attribute, + ref valid, + accessors, + accessor, + $"Namespace accessor '{accessor}' is declared more than once (case-insensitive)." + ); + } + + if (tables.Contains(accessor)) + { + ReportError( + diag, + attribute, + ref valid, + $"Namespace accessor '{accessor}' conflicts with a root table accessor." + ); + } + + if (accessor is "GetType" or "ToString" or "Equals" or "GetHashCode") + { + ReportError( + diag, + attribute, + ref valid, + $"Namespace accessor '{accessor}' conflicts with an existing context database/query receiver member." + ); + } + + if (valid) + { + result.Add(new NamespaceDeclaration(identity, accessor, name)); + } + } + return new EquatableArray(result.ToImmutable()); + } + + private static void ValidateDatabaseIdentifier( + DiagReporter diag, + AttributeData attribute, + ref bool valid, + string value, + string property + ) + { + if ( + value.Length == 0 + || !(char.IsLetter(value[0]) || value[0] == '_') + || value.Any(static c => !(char.IsLetterOrDigit(c) || c == '_')) + || !value.IsNormalized(NormalizationForm.FormC) + ) + { + ReportError( + diag, + attribute, + ref valid, + $"{property} must be a nonempty database identifier: letters, digits or underscores, starting with a letter or underscore." + ); + } + if (Encoding.UTF8.GetByteCount(value) > 63) + { + ReportError( + diag, + attribute, + ref valid, + $"{property} cannot exceed 63 UTF-8 bytes (the current host limit)." + ); + } + if ( + value.Equals("st", StringComparison.OrdinalIgnoreCase) + || value.Equals("spacetimedb", StringComparison.OrdinalIgnoreCase) + || value.StartsWith("pg_", StringComparison.OrdinalIgnoreCase) + ) + { + ReportError(diag, attribute, ref valid, $"Namespace {property} '{value}' is reserved."); + } + } + + private static void ReportError( + DiagReporter diag, + AttributeData attribute, + ref bool valid, + string message + ) + { + valid = false; + diag.Report(ErrorDescriptor.InvalidNamespace, (attribute, message)); + } + + private static void CheckDuplicate( + DiagReporter diag, + AttributeData attribute, + ref bool valid, + Dictionary seen, + string key, + string message + ) + { + if (seen.TryGetValue(key, out var previous)) + { + ReportError(diag, attribute, ref valid, message); + diag.Report(ErrorDescriptor.InvalidNamespace, (previous, message)); + } + else + { + seen.Add(key, attribute); + } + } +} diff --git a/crates/bindings-csharp/README.md b/crates/bindings-csharp/README.md index 947f57c9a08..bfbe4bf6d85 100644 --- a/crates/bindings-csharp/README.md +++ b/crates/bindings-csharp/README.md @@ -21,6 +21,71 @@ The [`Codegen`](./Codegen/) and [`Runtime`](./Runtime/) libraries are used: They provide all of the functionality needed to write SpacetimeDB modules in C#. See their READMEs for more information. +### Assembly dependencies and namespaces + +Assembly composition requires .NET 10 and C# 14 in both the root and its module +dependencies. Existing standalone .NET 8 modules keep their generated contexts; +they cannot participate in this assembly composition path. + +Reference another C# module with a normal `ProjectReference` (or a package +containing its compiled module assembly). No root/library build-role property is +required: the same dependency can also be published independently. +Descriptor-bearing dependencies, including transitive dependencies, register +automatically once in `public` unless the root assigns a namespace: + +```csharp +[assembly: SpacetimeDB.Namespace(typeof(AuthLib.Marker), Accessor = "MyAuth", Name = "auth_data")] +``` + +The marker can be any accessible type declared in the dependency assembly. +The tested example is [namespace-test-cs](../../modules/namespace-test-cs/), +whose root references AuthLib, AuditLib, and ExtraLib. If libraries live beneath +the root project directory, exclude their source files from its compile glob, +as that example does. + +Root code uses `ctx.Db.MyAuth.User` and `ctx.From.MyAuth.User()`. Compiled +AuthLib helpers continue to use `ctx.Db.User` and `ctx.From.User()`, regardless +of the namespace selected by the root. Ordinary helper calls share the caller's +context and transaction; a namespace is not a security boundary between helpers. + +`Accessor` controls the C# member name; `Name` controls the database namespace. +For this example, raw SQL uses `auth_data.auth_users`, while generated clients +use `conn.Db.MyAuth.User` and `q.From.MyAuth.User()`. Generated client queries and +network calls use the canonical database names automatically. +When `Name` is omitted, the host applies the root module's case-conversion policy +to the accessor: with the default `SnakeCase` policy, `MyAuth` becomes `my_auth`. +An explicit `Name` is used as supplied, without case conversion. + +#### Restrictions and limitations + +- Only the consuming root chooses namespace placement. A dependency that itself + declares namespace mounts cannot be composed, even in `public`. Nested mounts, + multiple instances of one assembly, and runtime-created namespaces are unsupported. +- An assembly can be mounted only once, and the root cannot mount itself. + Omitting the attribute, or explicitly using `Accessor = "public"`, registers + the dependency in the default scope with flat accessors. +- Dependencies in `public` inherit the root's case-conversion policy (`SnakeCase` + by default). An explicitly different policy is a compilation error. Mount the + dependency in a named namespace to keep its independent naming policy. +- `Accessor` must be a valid C# and database identifier; optional `Name` must be + a valid database identifier. Both are limited to 63 UTF-8 bytes. + Accessors are checked for case-insensitive duplicates; the host validates + canonical namespace collisions. + `st`, `spacetimedb`, and names starting with `pg_` are reserved. + Keywords use their plain spelling in the attribute and `@` in C# expressions. + The `public` scope cannot be renamed or targeted through a different accessor. +- Named namespaces cannot declare lifecycle reducers, nonempty environment + schemas, or RLS filters. The generator rejects these when composing the root. + They remain valid when the dependency is published alone or registered in + `public`, subject to ordinary host validation (including lifecycle uniqueness). +- Define RLS in the root, using canonical qualified table names, as in + [the integration fixture](../../modules/namespace-test-cs/Lib.cs). + Library-defined RLS in a named namespace is unsupported; it must not be relied + on to protect data. +- HTTP routes retain the existing root-level routing and environment authority; + mounting a dependency does not add an HTTP namespace prefix. +- Cross-language module composition is not currently supported. + ### Declared environment A module may declare one `[SpacetimeDB.Env]` struct. `string` is required and @@ -47,3 +112,10 @@ allow no environment keys. Undeclared reads and reads from host-dispatched submodules fail at runtime. Values are private, durable database configuration for secrets and other settings. Database owners and authorized collaborators can read them; module code can expose them through its own outputs. + +Environment declarations register through each assembly's descriptor on .NET 10. +Dependencies automatically registered in `public` contribute to the root schema; +mounted dependencies cannot declare environment variables (the generator and host reject them). +A library helper invoked by root code can use `ctx.Env.Get("KEY")` for a root-declared +key. Calling that library through a namespaced host entrypoint does not grant +environment access, even for a key declared by the root. diff --git a/crates/bindings-csharp/Runtime/Attrs.cs b/crates/bindings-csharp/Runtime/Attrs.cs index c8ce86aa2d9..f6dcda8533f 100644 --- a/crates/bindings-csharp/Runtime/Attrs.cs +++ b/crates/bindings-csharp/Runtime/Attrs.cs @@ -229,4 +229,37 @@ public sealed class HttpHandlerAttribute() : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class HttpRouterAttribute() : Attribute { } + +#if NET10_0_OR_GREATER + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] + public sealed class ModuleDescriptorAttribute(Type descriptorType) : Attribute + { + public Type DescriptorType { get; } = descriptorType; + } + + /// + /// Places the module contributions of the marker type's assembly in a namespace. + /// The consuming module chooses the placement; the marker may be any accessible type. + /// Requires .NET 10 and C# 14. + /// + /// + /// An assembly may be mounted only once. Dependencies cannot declare mounts. + /// Named namespaces cannot contain lifecycle reducers, RLS filters, or nonempty + /// environment declarations. Dependencies without a mount register automatically in public. + /// + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + public sealed class NamespaceAttribute(System.Type marker) : Attribute + { + public System.Type Marker { get; } = marker; + + /// The C# member name used for the mounted module. + public string Accessor { get; set; } = ""; + + /// + /// The database namespace. When omitted, the host applies the parent module's + /// case conversion policy to Accessor. + /// + public string? Name { get; set; } + } +#endif } diff --git a/crates/bindings-csharp/Runtime/Internal/CanonicalName.cs b/crates/bindings-csharp/Runtime/Internal/CanonicalName.cs new file mode 100644 index 00000000000..fb1e859b884 --- /dev/null +++ b/crates/bindings-csharp/Runtime/Internal/CanonicalName.cs @@ -0,0 +1,169 @@ +namespace SpacetimeDB.Internal; + +using System.Globalization; +using System.Text; + +internal static class CanonicalName +{ + internal static string Convert(string source, CaseConversionPolicy policy) + { + if (policy == CaseConversionPolicy.None) + { + return source; + } + + // Match the host's convert_case 0.6 default word boundaries. This runs only + // when installing mounts or initializing an immediate-scheduling name cache. + var elements = new List(); + var iterator = StringInfo.GetTextElementEnumerator(source); + while (iterator.MoveNext()) + { + elements.Add(iterator.GetTextElement()); + } + var result = new StringBuilder(); + var word = new StringBuilder(); + for (var i = 0; i <= elements.Count; i++) + { + var current = i < elements.Count ? elements[i] : ""; + var separator = current is "" or "_" or "-" or " "; + var previous = i > 0 ? elements[i - 1] : ""; + var next = i + 1 < elements.Count ? elements[i + 1] : ""; + var boundary = + separator + || (IsLower(previous) && IsUpper(current)) + || (IsDigit(previous) && (IsLower(current) || IsUpper(current))) + || ((IsLower(previous) || IsUpper(previous)) && IsDigit(current)) + || (IsUpper(previous) && IsUpper(current) && IsLower(next)); + if (boundary && word.Length > 0) + { + if (result.Length > 0) + { + result.Append('_'); + } + AppendLowercase(result, word.ToString()); + word.Clear(); + } + if (!separator) + { + word.Append(current); + } + } + return result.ToString(); + } + + private static bool IsDigit(string value) => + value.Length > 0 && value.All(c => c is >= '0' and <= '9'); + + // These comparisons classify graphemes; a case-insensitive comparison would erase + // the distinction needed by the word-boundary rules. +#pragma warning disable CA1862 + private static bool IsUpper(string value) => + (value.ToUpperInvariant() != value.ToLowerInvariant() || value.Contains('\u0130')) + && value == value.ToUpperInvariant() + && !value.EnumerateRunes().Any(HasUppercaseExpansion); + + private static bool IsLower(string value) => + ( + value.ToUpperInvariant() != value.ToLowerInvariant() + || value.EnumerateRunes().Any(HasUppercaseExpansion) + ) + && value == value.ToLowerInvariant() + && !value.Contains('\u0130'); +#pragma warning restore CA1862 + + // Unicode unconditional full-uppercase expansions used by Rust's string casing. + // .NET simple casing leaves some of these unchanged, affecting word boundaries. + private static bool HasUppercaseExpansion(Rune rune) => + rune.Value + is 0x00DF + or 0x0149 + or 0x01F0 + or 0x0390 + or 0x03B0 + or 0x0587 + or >= 0x1E96 + and <= 0x1E9A + or 0x1F50 + or 0x1F52 + or 0x1F54 + or 0x1F56 + or >= 0x1F80 + and <= 0x1FAF + or >= 0x1FB2 + and <= 0x1FB4 + or >= 0x1FB6 + and <= 0x1FB7 + or 0x1FBC + or >= 0x1FC2 + and <= 0x1FC4 + or >= 0x1FC6 + and <= 0x1FC7 + or 0x1FCC + or >= 0x1FD2 + and <= 0x1FD3 + or >= 0x1FD6 + and <= 0x1FD7 + or >= 0x1FE2 + and <= 0x1FE4 + or >= 0x1FE6 + and <= 0x1FE7 + or >= 0x1FF2 + and <= 0x1FF4 + or >= 0x1FF6 + and <= 0x1FF7 + or 0x1FFC + or >= 0xFB00 + and <= 0xFB06 + or >= 0xFB13 + and <= 0xFB17; + + private static void AppendLowercase(StringBuilder result, string word) + { + var runes = word.EnumerateRunes().ToArray(); + for (var i = 0; i < runes.Length; i++) + { + // Rust uses Unicode full lowercase mappings; .NET's invariant mapping + // is simple and omits dotted-I expansion and contextual final sigma. + if (runes[i].Value == 0x0130) + { + result.Append("i\u0307"); + } + else if ( + runes[i].Value == 0x03A3 + && HasCasedRune(runes, i, -1) + && !HasCasedRune(runes, i, 1) + ) + { + result.Append('\u03C2'); + } + else + { + result.Append(Rune.ToLowerInvariant(runes[i]).ToString()); + } + } + } + + private static bool HasCasedRune(Rune[] runes, int index, int direction) + { + for (var i = index + direction; i >= 0 && i < runes.Length; i += direction) + { + var category = Rune.GetUnicodeCategory(runes[i]); + if ( + category + is UnicodeCategory.NonSpacingMark + or UnicodeCategory.EnclosingMark + or UnicodeCategory.Format + or UnicodeCategory.ModifierLetter + or UnicodeCategory.ModifierSymbol + ) + { + continue; + } + return Rune.ToUpperInvariant(runes[i]) != Rune.ToLowerInvariant(runes[i]) + || HasUppercaseExpansion(runes[i]) + || runes[i].Value == 0x0130 + || category == UnicodeCategory.TitlecaseLetter; + } + return false; + } +} diff --git a/crates/bindings-csharp/Runtime/Internal/ITable.cs b/crates/bindings-csharp/Runtime/Internal/ITable.cs index 51e6fa0e6ee..4ea680b97f3 100644 --- a/crates/bindings-csharp/Runtime/Internal/ITable.cs +++ b/crates/bindings-csharp/Runtime/Internal/ITable.cs @@ -82,6 +82,8 @@ public interface ITableView static abstract T ReadGenFields(BinaryReader reader, T row); + static virtual string LookupName => tableName; + // These are static helpers that codegen can use. private class RawTableIter(FFI.TableId tableId) : RawTableIterBase @@ -96,7 +98,7 @@ protected override void IterStart(out FFI.RowIter handle) => private static readonly Lazy tableId_ = new(() => { - var name_bytes = System.Text.Encoding.UTF8.GetBytes(tableName); + var name_bytes = System.Text.Encoding.UTF8.GetBytes(View.LookupName); FFI.table_id_from_name(name_bytes, name_bytes.Length, out var out_); return out_; }); diff --git a/crates/bindings-csharp/Runtime/Internal/Module.cs b/crates/bindings-csharp/Runtime/Internal/Module.cs index 438c3439146..67eaa5180eb 100644 --- a/crates/bindings-csharp/Runtime/Internal/Module.cs +++ b/crates/bindings-csharp/Runtime/Internal/Module.cs @@ -2,234 +2,10 @@ namespace SpacetimeDB.Internal; using System; using System.Collections.Generic; -using System.Linq; using System.Runtime.InteropServices; using SpacetimeDB; using SpacetimeDB.BSATN; -partial class RawModuleDefV10 -{ - private readonly Typespace typespace = new(); - private readonly List typeDefs = []; - private readonly List tableDefs = []; - private readonly List scheduleDefs = []; - private readonly List reducerDefs = []; - private readonly List lifecycleReducerDefs = []; - private readonly List procedureDefs = []; - private readonly List httpHandlerDefs = []; - private readonly List httpRouteDefs = []; - private readonly List viewDefs = []; - private readonly List viewPrimaryKeyDefs = []; - private readonly List environment = []; - private readonly List rowLevelSecurityDefs = []; - private readonly Dictionary> defaultValuesByTable = - new(StringComparer.Ordinal); - - private SpacetimeDB.CaseConversionPolicy? caseConversionPolicy = null; - private readonly List explicitNames = []; - - // Note: this intends to generate a valid identifier, but it's not guaranteed to be unique as it's not proper mangling. - // Fix it up to a different mangling scheme if it causes problems. - private static string GetFriendlyName(Type type) => - type.IsGenericType - ? $"{type.Name[..type.Name.IndexOf('`')]}_{string.Join("_", type.GetGenericArguments().Select(GetFriendlyName))}" - : type.Name; - - private static RawScopedTypeNameV10 MakeScopedTypeName(Type type) => - new([], GetFriendlyName(type)); - - internal AlgebraicType.Ref RegisterType(Func makeType) - { - var typeList = typespace.Types; - var typeRef = new AlgebraicType.Ref(typeList.Count); - // Put a dummy self-reference just so that we get stable index even if `makeType` recursively adds more types. - typeList.Add(typeRef); - typeList[typeRef.Ref_] = makeType(typeRef); - typeDefs.Add( - new RawTypeDefV10( - SourceName: MakeScopedTypeName(typeof(T)), - Ty: (uint)typeRef.Ref_, - CustomOrdering: true - ) - ); - return typeRef; - } - - internal void RegisterReducer(RawReducerDefV10 reducer, Lifecycle? lifecycle) - { - reducerDefs.Add(reducer); - if (lifecycle is { } lifecycleSpec) - { - lifecycleReducerDefs.Add( - new RawLifeCycleReducerDefV10(lifecycleSpec, reducer.SourceName) - ); - reducer.Visibility = FunctionVisibility.Private; - } - } - - internal void RegisterProcedure(RawProcedureDefV10 procedure) => procedureDefs.Add(procedure); - - internal void RegisterHttpHandler(RawHttpHandlerDefV10 handler) => httpHandlerDefs.Add(handler); - - internal bool HasHttpHandler(string sourceName) => - httpHandlerDefs.Any(handler => handler.SourceName == sourceName); - - internal void RegisterHttpRoute(RawHttpRouteDefV10 route) => httpRouteDefs.Add(route); - - internal void RegisterTable(RawTableDefV10 table, RawScheduleDefV10? schedule) - { - tableDefs.Add(table); - if (schedule is { } scheduleDef) - { - scheduleDefs.Add(scheduleDef); - } - } - - internal void RegisterView(RawViewDefV10 view) => viewDefs.Add(view); - - internal void RegisterEnvironment(EnvironmentDeclaration declaration) => - environment.Add(declaration); - - internal void RegisterViewPrimaryKey(string viewSourceName, IEnumerable columns) => - viewPrimaryKeyDefs.Add(new RawViewPrimaryKeyDefV10(viewSourceName, [.. columns])); - - internal void RegisterRowLevelSecurity(RawRowLevelSecurityDefV9 rls) => - rowLevelSecurityDefs.Add(rls); - - internal void RegisterTableDefaultValue(string table, ushort colId, byte[] value) - { - if (!defaultValuesByTable.TryGetValue(table, out var defaults)) - { - defaults = []; - defaultValuesByTable.Add(table, defaults); - } - defaults.Add(new RawColumnDefaultValueV10(colId, [.. value])); - } - - internal void SetCaseConversionPolicy(SpacetimeDB.CaseConversionPolicy policy) => - caseConversionPolicy = policy; - - internal void RegisterExplicitTableName(string sourceName, string canonicalName) => - explicitNames.Add(new ExplicitNameEntry.Table(new NameMapping(sourceName, canonicalName))); - - internal void RegisterExplicitFunctionName(string sourceName, string canonicalName) => - explicitNames.Add( - new ExplicitNameEntry.Function(new NameMapping(sourceName, canonicalName)) - ); - - internal void RegisterExplicitIndexName(string sourceName, string canonicalName) => - explicitNames.Add(new ExplicitNameEntry.Index(new NameMapping(sourceName, canonicalName))); - - internal RawModuleDefV10 BuildModuleDefinition() - { - var builtTables = new List(tableDefs.Count); - foreach (var table in tableDefs) - { - defaultValuesByTable.TryGetValue(table.SourceName, out var defaults); - builtTables.Add( - new RawTableDefV10( - SourceName: table.SourceName, - ProductTypeRef: table.ProductTypeRef, - PrimaryKey: table.PrimaryKey, - Indexes: table.Indexes, - Constraints: table.Constraints, - Sequences: table.Sequences, - TableType: table.TableType, - TableAccess: table.TableAccess, - DefaultValues: defaults is null ? [] : [.. defaults], - IsEvent: table.IsEvent - ) - ); - } - - var internalFunctions = lifecycleReducerDefs - .Select(l => l.FunctionName) - .Concat(scheduleDefs.Select(s => s.FunctionName)) - .ToHashSet(StringComparer.Ordinal); - - foreach (var reducer in reducerDefs) - { - if (internalFunctions.Contains(reducer.SourceName)) - { - reducer.Visibility = FunctionVisibility.Private; - } - } - - foreach (var procedure in procedureDefs) - { - if (internalFunctions.Contains(procedure.SourceName)) - { - procedure.Visibility = FunctionVisibility.Private; - } - } - - var sections = new List - { - new RawModuleDefV10Section.Typespace(typespace), - new RawModuleDefV10Section.Environment(environment), - }; - - if (typeDefs.Count > 0) - { - sections.Add(new RawModuleDefV10Section.Types(typeDefs)); - } - if (builtTables.Count > 0) - { - sections.Add(new RawModuleDefV10Section.Tables(builtTables)); - } - if (reducerDefs.Count > 0) - { - sections.Add(new RawModuleDefV10Section.Reducers(reducerDefs)); - } - if (procedureDefs.Count > 0) - { - sections.Add(new RawModuleDefV10Section.Procedures(procedureDefs)); - } - if (httpHandlerDefs.Count > 0) - { - sections.Add(new RawModuleDefV10Section.HttpHandlers(httpHandlerDefs)); - } - if (httpRouteDefs.Count > 0) - { - sections.Add(new RawModuleDefV10Section.HttpRoutes(httpRouteDefs)); - } - if (viewDefs.Count > 0) - { - sections.Add(new RawModuleDefV10Section.Views(viewDefs)); - } - if (viewPrimaryKeyDefs.Count > 0) - { - sections.Add(new RawModuleDefV10Section.ViewPrimaryKeys(viewPrimaryKeyDefs)); - } - if (scheduleDefs.Count > 0) - { - sections.Add(new RawModuleDefV10Section.Schedules(scheduleDefs)); - } - if (lifecycleReducerDefs.Count > 0) - { - sections.Add(new RawModuleDefV10Section.LifeCycleReducers(lifecycleReducerDefs)); - } - // TODO: Add sections for Event tables and Case conversion policy (mirrors Rust `raw_def/v10.rs` TODO). - if (caseConversionPolicy is { } policy) - { - sections.Add(new RawModuleDefV10Section.CaseConversionPolicy(policy)); - } - if (explicitNames.Count > 0) - { - sections.Add( - new RawModuleDefV10Section.ExplicitNames(new ExplicitNames([.. explicitNames])) - ); - } - if (rowLevelSecurityDefs.Count > 0) - { - sections.Add(new RawModuleDefV10Section.RowLevelSecurity(rowLevelSecurityDefs)); - } - - Sections = sections; - return this; - } -} - public static class Module { // Workaround for NativeAOT-LLVM IL scanner bug: @@ -265,37 +41,41 @@ private static void EnsureNativeAotTypeRoots() } } - private static readonly RawModuleDefV10 moduleDef = new(); + public static readonly ModuleBuilder RootBuilder = new(); - private static class ReducerCache - where R : IReducer, new() - { - public static readonly R Instance = new(); - } + private static NamespaceRegistry? namespaces; - private static class ProcedureCache

- where P : IProcedure, new() + public static void InstallNamespaces(NamespaceRegistry registry) { - public static readonly P Instance = new(); - } + if (namespaces is not null) + { + throw new InvalidOperationException("Module namespaces have already been installed."); + } - private static class HttpHandlerCache - where H : IHttpHandler, new() - { - public static readonly H Instance = new(); + namespaces = registry; } - private static class ViewDispatcherCache - where TDispatcher : IView, new() - { - public static readonly TDispatcher Instance = new(); - } + public static string ResolveName(string assemblyIdentity, string localName) => + ( + namespaces + ?? throw new InvalidOperationException("Module namespaces have not been installed.") + ).Resolve(assemblyIdentity, localName); - private static class AnonymousViewDispatcherCache - where TDispatcher : IAnonymousView, new() - { - public static readonly TDispatcher Instance = new(); - } + public static string ResolveFunctionName( + string assemblyIdentity, + string sourceName, + string? explicitName + ) => + ( + namespaces + ?? throw new InvalidOperationException("Module namespaces have not been installed.") + ).ResolveFunction(assemblyIdentity, sourceName, explicitName); + + public static SqlTableName ResolveSqlName(string assemblyIdentity, string localName) => + ( + namespaces + ?? throw new InvalidOperationException("Module namespaces have not been installed.") + ).ResolveSqlName(assemblyIdentity, localName); private static Func< Identity, @@ -303,11 +83,34 @@ private static Func< Random, Timestamp, IReducerContext - >? newReducerContext = null; - private static Func? newViewContext = null; - private static Func? newAnonymousViewContext = null; + >? newReducerContext = +#if NET10_0_OR_GREATER + (identity, connectionId, random, time) => + new SpacetimeDB.ReducerContext(identity, connectionId, random, time); +#else + null; +#endif + private static Func? newViewContext = +#if NET10_0_OR_GREATER + identity => new ViewContext(identity, new LocalReadOnly()); +#else + null; +#endif + private static Func? newAnonymousViewContext = +#if NET10_0_OR_GREATER + () => new AnonymousViewContext(new LocalReadOnly()); +#else + null; +#endif private static Func? newHandlerContext = +#if NET10_0_OR_GREATER + ( + random, + time + ) => new HandlerContext(random, time); +#else null; +#endif private static Func< Identity, @@ -315,7 +118,13 @@ private static Func< Random, Timestamp, IProcedureContext - >? newProcedureContext = null; + >? newProcedureContext = +#if NET10_0_OR_GREATER + (identity, connectionId, random, time) => + new ProcedureContext(identity, connectionId, random, time); +#else + null; +#endif public static void SetReducerContextConstructor( Func ctor @@ -335,9 +144,15 @@ public static void SetViewContextConstructor(Func ctor) public static void SetAnonymousViewContextConstructor(Func ctor) => newAnonymousViewContext = ctor; - public readonly struct TypeRegistrar() : ITypeRegistrar + public readonly struct TypeRegistrar : ITypeRegistrar { private readonly Dictionary types = []; + private readonly ModuleBuilder target; + + public TypeRegistrar() + : this(RootBuilder) { } + + internal TypeRegistrar(ModuleBuilder target) => this.target = target; // Registers type in the module definition. // @@ -349,121 +164,62 @@ public readonly struct TypeRegistrar() : ITypeRegistrar // e.g. self-recursion even before the algebraic type itself is constructed. public AlgebraicType.Ref RegisterType(Func makeType) { - // Store for the closure access. - var types = this.types; if (types.TryGetValue(typeof(T), out var existingTypeRef)) { return existingTypeRef; } - return moduleDef.RegisterType(typeRef => - { - // Store the type reference in the dictionary so that we can resolve it later and to avoid infinite recursion inside `makeType`. - types.Add(typeof(T), typeRef); - return makeType(typeRef); - }); + + // Passes types down to register the type reference in the dictionary so that we can resolve it later and to avoid infinite recursion inside `makeType`. + return target.RegisterType(types, makeType); } } - static readonly TypeRegistrar typeRegistrar = new(); - public static void RegisterReducer() - where R : IReducer, new() - { - var reducer = ReducerCache.Instance; - moduleDef.RegisterReducer(reducer.MakeReducerDef(typeRegistrar), reducer.Lifecycle); - } + where R : IReducer, new() => RootBuilder.RegisterReducer(); public static void RegisterProcedure

() - where P : IProcedure, new() - { - var procedure = ProcedureCache

.Instance; - moduleDef.RegisterProcedure(procedure.MakeProcedureDef(typeRegistrar)); - } + where P : IProcedure, new() => RootBuilder.RegisterProcedure

(); public static void RegisterHttpHandler() - where H : IHttpHandler, new() - { - var handler = HttpHandlerCache.Instance; - moduleDef.RegisterHttpHandler(handler.MakeHandlerDef()); - } + where H : IHttpHandler, new() => RootBuilder.RegisterHttpHandler(); - public static void RegisterHttpRouter(SpacetimeDB.Router router) - { - foreach (var route in router.GetRoutes()) - { - if (!moduleDef.HasHttpHandler(route.HandlerFunction)) - { - throw new ArgumentException( - $"HTTP router references unknown handler `{route.HandlerFunction}`", - nameof(router) - ); - } - - moduleDef.RegisterHttpRoute( - new RawHttpRouteDefV10( - HandlerFunction: route.HandlerFunction, - Method: route.Method, - Path: route.Path - ) - ); - } - } + public static void RegisterHttpRouter(SpacetimeDB.Router router) => + RootBuilder.RegisterHttpRouter(router); public static void RegisterTable() where T : IStructuralReadWrite, new() - where View : ITableView, new() - { - moduleDef.RegisterTable(View.MakeTableDesc(typeRegistrar), View.MakeScheduleDesc()); - } + where View : ITableView, new() => RootBuilder.RegisterTable(); public static void RegisterView() - where TDispatcher : IView, new() - { - var dispatcher = ViewDispatcherCache.Instance; - var def = dispatcher.MakeViewDef(typeRegistrar); - moduleDef.RegisterView(def); - } + where TDispatcher : IView, new() => RootBuilder.RegisterView(); public static void RegisterAnonymousView() - where TDispatcher : IAnonymousView, new() - { - var dispatcher = AnonymousViewDispatcherCache.Instance; - var def = dispatcher.MakeAnonymousViewDef(typeRegistrar); - moduleDef.RegisterView(def); - } + where TDispatcher : IAnonymousView, new() => + RootBuilder.RegisterAnonymousView(); public static void RegisterEnvironment(EnvironmentDeclaration declaration) => - moduleDef.RegisterEnvironment(declaration); + RootBuilder.RegisterEnvironment(declaration); public static void RegisterViewPrimaryKey(string viewSourceName, string[] columns) => - moduleDef.RegisterViewPrimaryKey(viewSourceName, columns); + RootBuilder.RegisterViewPrimaryKey(viewSourceName, columns); - public static void RegisterClientVisibilityFilter(Filter rlsFilter) - { - if (rlsFilter is Filter.Sql(var rlsSql)) - { - moduleDef.RegisterRowLevelSecurity(new RawRowLevelSecurityDefV9 { Sql = rlsSql }); - } - else - { - throw new Exception($"Unimplemented row level security type: {rlsFilter}"); - } - } + public static void RegisterClientVisibilityFilter(Filter rlsFilter) => + RootBuilder.RegisterClientVisibilityFilter(rlsFilter); public static void RegisterTableDefaultValue(string table, ushort colId, byte[] value) => - moduleDef.RegisterTableDefaultValue(table, colId, value); + RootBuilder.RegisterTableDefaultValue(table, colId, value); public static void SetCaseConversionPolicy(SpacetimeDB.CaseConversionPolicy policy) => - moduleDef.SetCaseConversionPolicy(policy); + RootBuilder.SetCaseConversionPolicy(policy); public static void RegisterExplicitTableName(string sourceName, string canonicalName) => - moduleDef.RegisterExplicitTableName(sourceName, canonicalName); + RootBuilder.RegisterExplicitTableName(sourceName, canonicalName); public static void RegisterExplicitFunctionName(string sourceName, string canonicalName) => - moduleDef.RegisterExplicitFunctionName(sourceName, canonicalName); + RootBuilder.RegisterExplicitFunctionName(sourceName, canonicalName); public static void RegisterExplicitIndexName(string sourceName, string canonicalName) => - moduleDef.RegisterExplicitIndexName(sourceName, canonicalName); + RootBuilder.RegisterExplicitIndexName(sourceName, canonicalName); public static byte[] Consume(this BytesSource source) { @@ -652,7 +408,7 @@ public static void __describe_module__(BytesSink description) EnsureNativeAotTypeRoots(); try { - var module = moduleDef.BuildModuleDefinition(); + var module = RootBuilder.BuildModuleDefinition(); RawModuleDef versioned = new RawModuleDef.V10(module); var moduleBytes = IStructuralReadWrite.ToBytes(new RawModuleDef.BSATN(), versioned); description.Write(moduleBytes); @@ -675,12 +431,7 @@ public partial class Local ///

/// Read-only database access for view contexts. -/// The code generator will extend this partial class to add table accessors. +/// On .NET 10 the generator provides assembly-scoped extension properties. +/// On .NET 8 generated modules declare their own type with table accessors. /// -public sealed partial class LocalReadOnly -{ - // This class is intentionally empty - the code generator will add - // read-only table accessors for each table in the module. - // Example generated code: - // public Internal.ViewHandles.UserReadOnly User => new(); -} +public sealed partial class LocalReadOnly { } diff --git a/crates/bindings-csharp/Runtime/Internal/ModuleBuilder.cs b/crates/bindings-csharp/Runtime/Internal/ModuleBuilder.cs new file mode 100644 index 00000000000..6be3adf4669 --- /dev/null +++ b/crates/bindings-csharp/Runtime/Internal/ModuleBuilder.cs @@ -0,0 +1,365 @@ +namespace SpacetimeDB.Internal; + +using System; +using System.Collections.Generic; +using System.Linq; +using SpacetimeDB.BSATN; + +public sealed class ModuleBuilder +{ + private Module.TypeRegistrar TypeRegistrar { get; } + + public ModuleBuilder() => TypeRegistrar = new Module.TypeRegistrar(this); + + private static class ReducerCache + where R : IReducer, new() + { + public static readonly R Instance = new(); + } + + private static class ProcedureCache

+ where P : IProcedure, new() + { + public static readonly P Instance = new(); + } + + private static class HttpHandlerCache + where H : IHttpHandler, new() + { + public static readonly H Instance = new(); + } + + private static class ViewDispatcherCache + where TDispatcher : IView, new() + { + public static readonly TDispatcher Instance = new(); + } + + private static class AnonymousViewDispatcherCache + where TDispatcher : IAnonymousView, new() + { + public static readonly TDispatcher Instance = new(); + } + + private readonly Typespace typespace = new(); + private readonly List submoduleDefs = []; + private readonly List typeDefs = []; + private readonly List tableDefs = []; + private readonly List scheduleDefs = []; + private readonly List reducerDefs = []; + private readonly List lifecycleReducerDefs = []; + private readonly List procedureDefs = []; + private readonly List httpHandlerDefs = []; + private readonly List httpRouteDefs = []; + private readonly List viewDefs = []; + private readonly List viewPrimaryKeyDefs = []; + private readonly List environment = []; + private readonly List rowLevelSecurityDefs = []; + private readonly Dictionary> defaultValuesByTable = + new(StringComparer.Ordinal); + + private SpacetimeDB.CaseConversionPolicy? caseConversionPolicy = null; + private readonly List explicitNames = []; + + // Note: this intends to generate a valid identifier, but it's not guaranteed to be unique as it's not proper mangling. + // Fix it up to a different mangling scheme if it causes problems. + private static string GetFriendlyName(Type type) => + type.IsGenericType + ? $"{type.Name[..type.Name.IndexOf('`')]}_{string.Join("_", type.GetGenericArguments().Select(GetFriendlyName))}" + : type.Name; + + private static RawScopedTypeNameV10 MakeScopedTypeName(Type type) => + new([], GetFriendlyName(type)); + + internal void RegisterSubmodule(RawSubmoduleV10 submodule) => submoduleDefs.Add(submodule); + + public void RegisterSubmodule(string accessor, string? name, ModuleBuilder child) + { + RegisterSubmodule(new RawSubmoduleV10(accessor, child.BuildModuleDefinition())); + if (name is not null) + { + explicitNames.Add(new ExplicitNameEntry.Namespace(new NameMapping(accessor, name))); + } + } + + // Receives types to store the reference in the dictionary so that we can resolve it later and to avoid infinite recursion inside `makeType`. + internal AlgebraicType.Ref RegisterType( + Dictionary types, + Func makeType + ) + { + var typeList = typespace.Types; + var typeRef = new AlgebraicType.Ref(typeList.Count); + types.Add(typeof(T), typeRef); + // Put a dummy self-reference just so that we get stable index even if `makeType` recursively adds more types. + typeList.Add(typeRef); + typeList[typeRef.Ref_] = makeType(typeRef); + typeDefs.Add( + new RawTypeDefV10( + SourceName: MakeScopedTypeName(typeof(T)), + Ty: (uint)typeRef.Ref_, + CustomOrdering: true + ) + ); + return typeRef; + } + + public void RegisterReducer() + where R : IReducer, new() + { + var reducer = ReducerCache.Instance; + RegisterReducer(reducer.MakeReducerDef(TypeRegistrar), reducer.Lifecycle); + } + + internal void RegisterReducer(RawReducerDefV10 reducer, Lifecycle? lifecycle) + { + reducerDefs.Add(reducer); + if (lifecycle is { } lifecycleSpec) + { + lifecycleReducerDefs.Add( + new RawLifeCycleReducerDefV10(lifecycleSpec, reducer.SourceName) + ); + reducer.Visibility = FunctionVisibility.Private; + } + } + + public void RegisterProcedure

() + where P : IProcedure, new() + { + var procedure = ProcedureCache

.Instance; + RegisterProcedure(procedure.MakeProcedureDef(TypeRegistrar)); + } + + internal void RegisterProcedure(RawProcedureDefV10 procedure) => procedureDefs.Add(procedure); + + public void RegisterHttpHandler() + where H : IHttpHandler, new() + { + var handler = HttpHandlerCache.Instance; + RegisterHttpHandler(handler.MakeHandlerDef()); + } + + internal void RegisterHttpHandler(RawHttpHandlerDefV10 handler) => httpHandlerDefs.Add(handler); + + public void RegisterHttpRouter(SpacetimeDB.Router router) + { + foreach (var route in router.GetRoutes()) + { + if (!HasHttpHandler(route.HandlerFunction)) + { + throw new ArgumentException( + $"HTTP router references unknown handler `{route.HandlerFunction}`", + nameof(router) + ); + } + + RegisterHttpRoute( + new RawHttpRouteDefV10( + HandlerFunction: route.HandlerFunction, + Method: route.Method, + Path: route.Path + ) + ); + } + } + + internal bool HasHttpHandler(string sourceName) => + httpHandlerDefs.Any(handler => handler.SourceName == sourceName); + + internal void RegisterHttpRoute(RawHttpRouteDefV10 route) => httpRouteDefs.Add(route); + + public void RegisterTable() + where T : IStructuralReadWrite, new() + where View : ITableView, new() => + RegisterTable(View.MakeTableDesc(TypeRegistrar), View.MakeScheduleDesc()); + + internal void RegisterTable(RawTableDefV10 table, RawScheduleDefV10? schedule) + { + tableDefs.Add(table); + if (schedule is { } scheduleDef) + { + scheduleDefs.Add(scheduleDef); + } + } + + public void RegisterView() + where TDispatcher : IView, new() + { + var dispatcher = ViewDispatcherCache.Instance; + var def = dispatcher.MakeViewDef(TypeRegistrar); + RegisterView(def); + } + + public void RegisterAnonymousView() + where TDispatcher : IAnonymousView, new() + { + var dispatcher = AnonymousViewDispatcherCache.Instance; + var def = dispatcher.MakeAnonymousViewDef(TypeRegistrar); + RegisterView(def); + } + + internal void RegisterView(RawViewDefV10 view) + { + // Several descriptors may share this builder. IDs are local to the composed + // definition, with independent sequences for anonymous and sender views. + view.Index = (uint)viewDefs.Count(previous => previous.IsAnonymous == view.IsAnonymous); + viewDefs.Add(view); + } + + public void RegisterEnvironment(EnvironmentDeclaration declaration) => + environment.Add(declaration); + + public void RegisterViewPrimaryKey(string viewSourceName, IEnumerable columns) => + viewPrimaryKeyDefs.Add(new RawViewPrimaryKeyDefV10(viewSourceName, [.. columns])); + + public void RegisterClientVisibilityFilter(Filter rlsFilter) + { + if (rlsFilter is Filter.Sql(var rlsSql)) + { + RegisterRowLevelSecurity(new RawRowLevelSecurityDefV9 { Sql = rlsSql }); + } + else + { + throw new Exception($"Unimplemented row level security type: {rlsFilter}"); + } + } + + internal void RegisterRowLevelSecurity(RawRowLevelSecurityDefV9 rls) => + rowLevelSecurityDefs.Add(rls); + + public void RegisterTableDefaultValue(string table, ushort colId, byte[] value) + { + if (!defaultValuesByTable.TryGetValue(table, out var defaults)) + { + defaults = []; + defaultValuesByTable.Add(table, defaults); + } + defaults.Add(new RawColumnDefaultValueV10(colId, [.. value])); + } + + public void SetCaseConversionPolicy(SpacetimeDB.CaseConversionPolicy policy) => + caseConversionPolicy = policy; + + public void RegisterExplicitTableName(string sourceName, string canonicalName) => + explicitNames.Add(new ExplicitNameEntry.Table(new NameMapping(sourceName, canonicalName))); + + public void RegisterExplicitFunctionName(string sourceName, string canonicalName) => + explicitNames.Add( + new ExplicitNameEntry.Function(new NameMapping(sourceName, canonicalName)) + ); + + public void RegisterExplicitIndexName(string sourceName, string canonicalName) => + explicitNames.Add(new ExplicitNameEntry.Index(new NameMapping(sourceName, canonicalName))); + + internal RawModuleDefV10 BuildModuleDefinition() + { + var builtTables = new List(tableDefs.Count); + foreach (var table in tableDefs) + { + defaultValuesByTable.TryGetValue(table.SourceName, out var defaults); + builtTables.Add( + new RawTableDefV10( + SourceName: table.SourceName, + ProductTypeRef: table.ProductTypeRef, + PrimaryKey: table.PrimaryKey, + Indexes: table.Indexes, + Constraints: table.Constraints, + Sequences: table.Sequences, + TableType: table.TableType, + TableAccess: table.TableAccess, + DefaultValues: defaults is null ? [] : [.. defaults], + IsEvent: table.IsEvent + ) + ); + } + + var internalFunctions = lifecycleReducerDefs + .Select(l => l.FunctionName) + .Concat(scheduleDefs.Select(s => s.FunctionName)) + .ToHashSet(StringComparer.Ordinal); + + foreach (var reducer in reducerDefs) + { + if (internalFunctions.Contains(reducer.SourceName)) + { + reducer.Visibility = FunctionVisibility.Private; + } + } + + foreach (var procedure in procedureDefs) + { + if (internalFunctions.Contains(procedure.SourceName)) + { + procedure.Visibility = FunctionVisibility.Private; + } + } + + var sections = new List + { + new RawModuleDefV10Section.Typespace(typespace), + new RawModuleDefV10Section.Environment(environment), + }; + + if (submoduleDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.Submodules([.. submoduleDefs])); + } + if (typeDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.Types(typeDefs)); + } + if (builtTables.Count > 0) + { + sections.Add(new RawModuleDefV10Section.Tables(builtTables)); + } + if (reducerDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.Reducers(reducerDefs)); + } + if (procedureDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.Procedures(procedureDefs)); + } + if (httpHandlerDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.HttpHandlers(httpHandlerDefs)); + } + if (httpRouteDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.HttpRoutes(httpRouteDefs)); + } + if (viewDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.Views(viewDefs)); + } + if (viewPrimaryKeyDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.ViewPrimaryKeys(viewPrimaryKeyDefs)); + } + if (scheduleDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.Schedules(scheduleDefs)); + } + if (lifecycleReducerDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.LifeCycleReducers(lifecycleReducerDefs)); + } + // TODO: Add sections for Event tables and Case conversion policy (mirrors Rust `raw_def/v10.rs` TODO). + if (caseConversionPolicy is { } policy) + { + sections.Add(new RawModuleDefV10Section.CaseConversionPolicy(policy)); + } + if (explicitNames.Count > 0) + { + sections.Add( + new RawModuleDefV10Section.ExplicitNames(new ExplicitNames([.. explicitNames])) + ); + } + if (rowLevelSecurityDefs.Count > 0) + { + sections.Add(new RawModuleDefV10Section.RowLevelSecurity(rowLevelSecurityDefs)); + } + + return new RawModuleDefV10(sections); + } +} diff --git a/crates/bindings-csharp/Runtime/Internal/NamespaceRegistry.cs b/crates/bindings-csharp/Runtime/Internal/NamespaceRegistry.cs new file mode 100644 index 00000000000..3b35500cc76 --- /dev/null +++ b/crates/bindings-csharp/Runtime/Internal/NamespaceRegistry.cs @@ -0,0 +1,77 @@ +namespace SpacetimeDB.Internal; + +///

Immutable assembly placement installed before module registration. +public sealed class NamespaceRegistry +{ + private readonly Dictionary< + string, + (string Accessor, string Canonical, CaseConversionPolicy Policy) + > mounts = new(StringComparer.Ordinal); + private readonly CaseConversionPolicy rootPolicy; + + public NamespaceRegistry( + string rootIdentity, + CaseConversionPolicy rootPolicy, + IEnumerable<( + string AssemblyIdentity, + string Accessor, + string? Name, + CaseConversionPolicy Policy + )> mounts + ) + { + this.rootPolicy = rootPolicy; + foreach (var mount in mounts) + { + if (mount.AssemblyIdentity == rootIdentity) + { + throw new ArgumentException("The root assembly cannot be mounted.", nameof(mounts)); + } + + if ( + !this.mounts.TryAdd( + mount.AssemblyIdentity, + ( + mount.Accessor, + mount.Name ?? CanonicalName.Convert(mount.Accessor, rootPolicy), + mount.Policy + ) + ) + ) + { + throw new ArgumentException( + $"Assembly '{mount.AssemblyIdentity}' is mounted more than once.", + nameof(mounts) + ); + } + } + } + + private string? ResolveNamespace(string assemblyIdentity) => + mounts.TryGetValue(assemblyIdentity, out var mount) + && !mount.Accessor.Equals("public", StringComparison.OrdinalIgnoreCase) + ? mount.Accessor + : null; + + public string ResolveFunction(string assemblyIdentity, string sourceName, string? explicitName) + { + if ( + mounts.TryGetValue(assemblyIdentity, out var mount) + && !mount.Accessor.Equals("public", StringComparison.OrdinalIgnoreCase) + ) + { + return mount.Canonical + + "." + + (explicitName ?? CanonicalName.Convert(sourceName, mount.Policy)); + } + return explicitName ?? CanonicalName.Convert(sourceName, rootPolicy); + } + + public string Resolve(string assemblyIdentity, string localName) => + ResolveNamespace(assemblyIdentity) is { } name ? name + "." + localName : localName; + + public SqlTableName ResolveSqlName(string assemblyIdentity, string localName) => + ResolveNamespace(assemblyIdentity) is { } name + ? new SqlTableName(name, localName) + : new SqlTableName(localName); +} diff --git a/crates/bindings-csharp/Runtime/ModuleContexts.cs b/crates/bindings-csharp/Runtime/ModuleContexts.cs new file mode 100644 index 00000000000..aaa8649d997 --- /dev/null +++ b/crates/bindings-csharp/Runtime/ModuleContexts.cs @@ -0,0 +1,256 @@ +#if NET10_0_OR_GREATER +namespace SpacetimeDB; + +using System.Diagnostics.CodeAnalysis; + +#pragma warning disable STDB_UNSTABLE +#pragma warning disable CA1822 // Preserve the existing instance-based context API. + +public sealed class Local : LocalBase { } + +public sealed record ReducerContext : DbContext, Internal.IReducerContext +{ + public DatabaseEnvironment Env => default; + public readonly Identity Sender; + public readonly ConnectionId? ConnectionId; + public readonly Random Rng; + public readonly Timestamp Timestamp; + public readonly AuthCtx SenderAuth; + + // **Note:** must be 0..=u32::MAX + internal int CounterUuid; + public Identity DatabaseIdentity => Internal.IReducerContext.GetDatabaseIdentity(); + + // We keep this property for compatibility with existing module code. + [global::System.Obsolete( + "ReducerContext.Identity is deprecated. Use DatabaseIdentity instead." + )] + public Identity Identity => DatabaseIdentity; + + internal ReducerContext( + Identity identity, + ConnectionId? connectionId, + Random random, + Timestamp time, + AuthCtx? senderAuth = null + ) + { + Sender = identity; + ConnectionId = connectionId; + Rng = random; + Timestamp = time; + SenderAuth = senderAuth ?? AuthCtx.BuildFromSystemTables(connectionId, identity); + CounterUuid = 0; + } + + /// + /// Create a new random `v4` using the built-in RNG. + /// + /// + /// This method fills the random bytes using the context RNG. + /// + /// + /// + /// var uuid = ctx.NewUuidV4(); + /// Log.Info(uuid); + /// + /// + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + /// + /// Create a new sortable `v7` using the built-in RNG, monotonic counter, + /// and timestamp. + /// + /// + /// A newly generated `v7` that is monotonically ordered + /// and suitable for use as a primary key or for ordered storage. + /// + /// + /// Thrown if generation fails. + /// + /// + /// + /// [SpacetimeDB.Reducer] + /// public static Guid GenerateUuidV7(ReducerContext ctx) + /// { + /// Guid uuid = ctx.NewUuidV7(); + /// Log.Info(uuid); + /// } + /// + /// + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } +} + +public readonly struct QueryBuilder { } + +public sealed partial class ProcedureContext : global::SpacetimeDB.ProcedureContextBase +{ + private readonly Local _db = new(); + + internal ProcedureContext( + Identity identity, + ConnectionId? connectionId, + Random random, + Timestamp time + ) + : base(identity, connectionId, random, time) { } + + protected internal override global::SpacetimeDB.LocalBase CreateLocal() => _db; + + protected override global::SpacetimeDB.ProcedureTxContextBase CreateTxContext( + Internal.TxContext inner + ) => _cached ??= new ProcedureTxContext(inner); + + private ProcedureTxContext? _cached; + + public Local Db => _db; + + public TResult WithTx(Func body) => + base.WithTx(tx => body((ProcedureTxContext)tx)); + + public TxOutcome TryWithTx( + Func> body + ) + where TError : Exception => base.TryWithTx(tx => body((ProcedureTxContext)tx)); + + /// + /// Create a new random `v4` using the built-in RNG. + /// + /// + /// This method fills the random bytes using the context RNG. + /// + /// + /// + /// var uuid = ctx.NewUuidV4(); + /// Log.Info(uuid); + /// + /// + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + /// + /// Create a new sortable `v7` using the built-in RNG, monotonic counter, + /// and timestamp. + /// + /// + /// A newly generated `v7` that is monotonically ordered + /// and suitable for use as a primary key or for ordered storage. + /// + /// + /// Thrown if UUID generation fails. + /// + /// + /// + /// [SpacetimeDB.Procedure] + /// public static Guid GenerateUuidV7(ReducerContext ctx) + /// { + /// Guid uuid = ctx.NewUuidV7(); + /// Log.Info(uuid); + /// } + /// + /// + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } +} + +public sealed partial class HandlerContext : global::SpacetimeDB.HandlerContextBase +{ + private readonly Local _db = new(); + + internal HandlerContext(Random random, Timestamp time) + : base(random, time) { } + + protected override global::SpacetimeDB.LocalBase CreateLocal() => _db; + + protected override global::SpacetimeDB.HandlerTxContextBase CreateTxContext( + Internal.TxContext inner + ) => _cached ??= new HandlerTxContext(inner); + + private HandlerTxContext? _cached; + + [Experimental("STDB_UNSTABLE")] + public TResult WithTx(Func body) => + base.WithTx(tx => body((HandlerTxContext)tx)); + + [Experimental("STDB_UNSTABLE")] + public TxOutcome TryWithTx( + Func> body + ) + where TError : Exception => base.TryWithTx(tx => body((HandlerTxContext)tx)); + + public Uuid NewUuidV4() + { + var bytes = new byte[16]; + Rng.NextBytes(bytes); + return Uuid.FromRandomBytesV4(bytes); + } + + public Uuid NewUuidV7() + { + var bytes = new byte[4]; + Rng.NextBytes(bytes); + return Uuid.FromCounterV7(ref CounterUuid, Timestamp, bytes); + } +} + +public sealed class ProcedureTxContext : global::SpacetimeDB.ProcedureTxContextBase +{ + internal ProcedureTxContext(Internal.TxContext inner) + : base(inner) { } + + public new Local Db => (Local)base.Db; +} + +[Experimental("STDB_UNSTABLE")] +public sealed class HandlerTxContext : global::SpacetimeDB.HandlerTxContextBase +{ + internal HandlerTxContext(Internal.TxContext inner) + : base(inner) { } + + public new Local Db => (Local)base.Db; +} + +public sealed record ViewContext : DbContext, Internal.IViewContext +{ + public DatabaseEnvironment Env => default; + public Identity Sender { get; } + + public QueryBuilder From => default; + + internal ViewContext(Identity sender, Internal.LocalReadOnly db) + : base(db) + { + Sender = sender; + } +} + +public sealed record AnonymousViewContext + : DbContext, + Internal.IAnonymousViewContext +{ + public DatabaseEnvironment Env => default; + public QueryBuilder From => default; + + internal AnonymousViewContext(Internal.LocalReadOnly db) + : base(db) { } +} + +#endif diff --git a/crates/codegen/Cargo.toml b/crates/codegen/Cargo.toml index 9d362a09ade..afb6ab6968e 100644 --- a/crates/codegen/Cargo.toml +++ b/crates/codegen/Cargo.toml @@ -21,6 +21,7 @@ serde_json.workspace = true fs-err.workspace = true insta.workspace = true regex.workspace = true +tempfile.workspace = true spacetimedb-testing = { path = "../testing" } [lints] diff --git a/crates/codegen/src/csharp.rs b/crates/codegen/src/csharp.rs index 931bf205484..e01c48cf7bc 100644 --- a/crates/codegen/src/csharp.rs +++ b/crates/codegen/src/csharp.rs @@ -15,8 +15,10 @@ use crate::{indent_scope, CodegenOptions, OutputFile}; use convert_case::{Case, Casing}; use spacetimedb_lib::sats::layout::PrimitiveType; use spacetimedb_primitives::ColId; -use spacetimedb_schema::def::{BTreeAlgorithm, IndexAlgorithm, ModuleDef, TableDef, TypeDef}; -use spacetimedb_schema::identifier::Identifier; +use spacetimedb_schema::def::{ + BTreeAlgorithm, IndexAlgorithm, ModuleDef, ProcedureDef, ReducerDef, TableDef, TypeDef, ViewDef, +}; +use spacetimedb_schema::identifier::{Identifier, NamespacePath}; use spacetimedb_schema::schema::TableSchema; use spacetimedb_schema::type_for_generate::{ AlgebraicTypeDef, AlgebraicTypeUse, PlainEnumTypeDef, ProductTypeDef, SumTypeDef, TypespaceForGenerate, @@ -503,9 +505,244 @@ pub struct Csharp<'opts> { } impl Lang for Csharp<'_> { + fn generate_table_file_from_schema(&self, module: &ModuleDef, table: &TableDef, schema: TableSchema) -> OutputFile { + self.scope(module) + .generate_table_file_from_schema(module, table, schema) + } + + fn generate_type_files(&self, module: &ModuleDef, typ: &TypeDef) -> Vec { + self.scope(module).generate_type_files(module, typ) + } + + fn generate_reducer_file(&self, module: &ModuleDef, reducer: &ReducerDef) -> OutputFile { + self.scope(module).generate_reducer_file(module, reducer) + } + + fn generate_procedure_file(&self, module: &ModuleDef, procedure: &ProcedureDef) -> OutputFile { + self.scope(module).generate_procedure_file(module, procedure) + } + + fn generate_submodule_table_file(&self, module: &ModuleDef, table: &TableDef) -> OutputFile { + scoped_file( + module.accessor_path(), + self.scope(module).generate_table_file(module, table), + ) + } + + fn generate_submodule_view_file(&self, module: &ModuleDef, view: &ViewDef) -> OutputFile { + scoped_file( + module.accessor_path(), + self.scope(module).generate_view_file(module, view), + ) + } + + fn generate_submodule_reducer_file(&self, module: &ModuleDef, reducer: &ReducerDef) -> OutputFile { + scoped_file( + module.accessor_path(), + self.scope(module).generate_reducer_file(module, reducer), + ) + } + + fn generate_submodule_procedure_file(&self, module: &ModuleDef, procedure: &ProcedureDef) -> OutputFile { + scoped_file( + module.accessor_path(), + self.scope(module).generate_procedure_file(module, procedure), + ) + } + + fn generate_global_files(&self, module: &ModuleDef, options: &CodegenOptions) -> Vec { + let mut files = self.scope(module).generate_global_files(module, options); + self.child_files(module, &mut files); + files + } +} + +impl Csharp<'_> { + fn scope(&self, module: &ModuleDef) -> CsharpScope<'_> { + let namespace = clr_namespace(self.namespace, module.accessor_path()); + CsharpScope { + namespace, + root_namespace: self.namespace, + path: module.path().clone(), + } + } + + fn child_files(&self, module: &ModuleDef, files: &mut Vec) { + for child in module.submodules().values() { + let path = child.accessor_path(); + let scope = self.scope(child); + // Child typespaces are independent, including types used only by functions. + for typ in child.types() { + files.extend( + scope + .generate_type_files(child, typ) + .into_iter() + .map(|file| scoped_file(path, file)), + ); + } + files.push(scoped_file(path, scope.child_globals(child))); + self.child_files(child, files); + } + } +} + +struct CsharpScope<'a> { + namespace: String, + root_namespace: &'a str, + // Canonical database path, never a C# member or CLR namespace path. + path: NamespacePath, +} + +fn scoped_file(path: &NamespacePath, mut file: OutputFile) -> OutputFile { + file.filename = format!("{}/{}", path.join_segments("/"), file.filename); + file +} + +fn clr_namespace(root: &str, path: &NamespacePath) -> String { + let mut namespace = root.to_owned(); + for segment in path.segments() { + // Keep namespace accessors verbatim; @ also handles keyword identifiers. + write!(namespace, ".@{segment}").unwrap(); + } + namespace +} + +fn member_path(path: &NamespacePath) -> String { + path.segments().iter().map(|segment| format!("@{segment}.")).collect() +} + +impl CsharpScope<'_> { + fn root_type(&self, name: &str) -> String { + if self.path.is_empty() { + name.to_owned() + } else { + format!("global::{}.{name}", self.root_namespace) + } + } + + fn sql_name(&self, name: &Identifier) -> String { + match self.path.segments() { + [] => format!("new global::SpacetimeDB.SqlTableName({:?})", name.deref()), + [namespace] => format!( + "new global::SpacetimeDB.SqlTableName({namespace:?}, {:?})", + name.deref() + ), + _ => panic!("Nested namespaces are not supported by C# bindings"), + } + } + + fn child_members(&self, output: &mut CodeIndenter, module: &ModuleDef, container: &str) { + for child in module.submodules().values() { + let name = child.mount_accessor_name().unwrap(); + let namespace = clr_namespace(self.root_namespace, child.accessor_path()); + if container == "From" { + writeln!(output, "public global::{namespace}.From @{name} {{ get; }} = new();"); + } else { + writeln!(output, "public global::{namespace}.{container} @{name} {{ get; }}"); + } + } + } + + fn function_container(&self, output: &mut CodeIndenter, module: &ModuleDef, container: &str) { + writeln!(output, "public sealed partial class {container} : RemoteBase"); + indented_block(output, |output| { + self.child_members(output, module, container); + let conn = self.root_type("DbConnection"); + if module.submodules().is_empty() { + writeln!(output, "internal {container}({conn} conn) : base(conn) {{ }}"); + } else { + writeln!(output, "internal {container}({conn} conn) : base(conn)"); + indented_block(output, |output| { + for child in module.submodules().values() { + let name = child.mount_accessor_name().unwrap(); + writeln!(output, "@{name} = new(conn);"); + if container == "RemoteReducers" { + writeln!(output, "@{name}.InternalOnUnhandledReducerError += (ctx, error) => InternalOnUnhandledReducerError?.Invoke(ctx, error);"); + } + } + }); + } + if container == "RemoteReducers" { + let context = self.root_type("ReducerEventContext"); + if !self.path.is_empty() + && module.submodules().is_empty() + && iter_reducers(module, crate::CodegenVisibility::OnlyPublic) + .next() + .is_none() + { + // An empty namespace cannot raise an error; avoid an unused backing event. + writeln!(output, "internal event Action<{context}, Exception>? InternalOnUnhandledReducerError {{ add {{ }} remove {{ }} }}"); + } else { + writeln!( + output, + "internal event Action<{context}, Exception>? InternalOnUnhandledReducerError;" + ); + } + } + }); + writeln!(output); + } + + fn from(&self, output: &mut CodeIndenter, module: &ModuleDef, options: &CodegenOptions) { + writeln!(output, "public sealed class From"); + indented_block(output, |output| { + self.child_members(output, module, "From"); + for (name, accessor_name, product_type_ref) in iter_table_names_and_types(module, options.visibility) { + let method_name = accessor_name.deref().to_case(Case::Pascal); + let row_type = type_ref_name(module, product_type_ref); + let table_name_lit = if self.path.is_empty() { + format!("{:?}", name.deref()) + } else { + format!("RemoteTables.{method_name}Handle.SqlName") + }; + writeln!(output, "public global::SpacetimeDB.Table<{row_type}, {method_name}Cols, {method_name}IxCols> {method_name}() => new({table_name_lit}, new {method_name}Cols({table_name_lit}), new {method_name}IxCols({table_name_lit}));"); + } + }); + writeln!(output); + } + + fn child_globals(&self, module: &ModuleDef) -> OutputFile { + let mut output = CsharpAutogen::new(&self.namespace, &["System.Collections.Generic"], false); + self.function_container(&mut output, module, "RemoteReducers"); + self.function_container(&mut output, module, "RemoteProcedures"); + writeln!(output, "public sealed partial class RemoteTables"); + indented_block(&mut output, |output| { + self.child_members(output, module, "RemoteTables"); + writeln!( + output, + "internal RemoteTables(global::{}.DbConnection conn, Action register)", + self.root_namespace + ); + indented_block(output, |output| { + for (_, accessor, _) in iter_table_names_and_types(module, crate::CodegenVisibility::OnlyPublic) { + writeln!( + output, + "register({} = new(conn));", + accessor.deref().to_case(Case::Pascal) + ); + } + for child in module.submodules().values() { + let name = child.mount_accessor_name().unwrap(); + writeln!(output, "@{name} = new(conn, register);"); + } + }); + }); + self.from(&mut output, module, &CodegenOptions::default()); + writeln!(output, "public abstract partial class Reducer"); + indented_block(&mut output, |output| writeln!(output, "private Reducer() {{ }}")); + writeln!(output, "public abstract partial class Procedure"); + indented_block(&mut output, |output| writeln!(output, "private Procedure() {{ }}")); + OutputFile { + filename: "Namespace.g.cs".to_owned(), + code: output.into_inner(), + } + } +} + +impl Lang for CsharpScope<'_> { fn generate_table_file_from_schema(&self, module: &ModuleDef, table: &TableDef, schema: TableSchema) -> OutputFile { let mut output = CsharpAutogen::new( - self.namespace, + &self.namespace, &[ "SpacetimeDB.BSATN", "SpacetimeDB.ClientApi", @@ -520,6 +757,7 @@ impl Lang for Csharp<'_> { let csharp_table_name = table.accessor_name.deref().to_case(Case::Pascal); let csharp_table_class_name = csharp_table_name.clone() + "Handle"; let table_type = type_ref_name(module, table.product_type_ref); + let context = self.root_type("EventContext"); let base_class = if table.is_event { "RemoteEventTableHandle" @@ -528,10 +766,25 @@ impl Lang for Csharp<'_> { }; writeln!( output, - "public sealed class {csharp_table_class_name} : {base_class}" + "public sealed class {csharp_table_class_name} : {base_class}<{context}, {table_type}>" ); indented_block(output, |output| { - writeln!(output, "public override string RemoteTableName => \"{}\";", table.name); + writeln!( + output, + "public override string RemoteTableName => \"{}{}\";", + self.path, table.name + ); + if !self.path.is_empty() { + writeln!( + output, + "internal static readonly global::SpacetimeDB.SqlTableName SqlName = {};", + self.sql_name(&table.name) + ); + writeln!( + output, + "protected override global::SpacetimeDB.SqlTableName RemoteSqlTableName => SqlName;" + ); + } writeln!(output); // If this is a table, we want to generate event accessor and indexes @@ -679,9 +932,10 @@ impl Lang for Csharp<'_> { ); } + let connection = self.root_type("DbConnection"); writeln!( output, - "internal {csharp_table_class_name}(DbConnection conn) : base(conn)" + "internal {csharp_table_class_name}({connection} conn) : base(conn)" ); indented_block(output, |output| { for csharp_index_name in &index_names { @@ -741,7 +995,12 @@ impl Lang for Csharp<'_> { ); } writeln!(output); - writeln!(output, "public {cols_owner_name}Cols(string tableName)"); + let name_type = if self.path.is_empty() { + "string" + } else { + "global::SpacetimeDB.SqlTableName" + }; + writeln!(output, "public {cols_owner_name}Cols({name_type} tableName)"); indented_block(output, |output| { for (field_name, field_type) in &product_type.elements { let prop = field_name.deref().to_case(Case::Pascal); @@ -776,7 +1035,12 @@ impl Lang for Csharp<'_> { ); } writeln!(output); - writeln!(output, "public {cols_owner_name}IxCols(string tableName)"); + let name_type = if self.path.is_empty() { + "string" + } else { + "global::SpacetimeDB.SqlTableName" + }; + writeln!(output, "public {cols_owner_name}IxCols({name_type} tableName)"); indented_block(output, |output| { for (i, (field_name, field_type)) in product_type.elements.iter().enumerate() { if !ix_col_positions.contains(&i) { @@ -806,10 +1070,10 @@ impl Lang for Csharp<'_> { let name = collect_case(Case::Pascal, typ.accessor_name.name_segments()); let filename = format!("Types/{name}.g.cs"); let code = match &module.typespace_for_generate()[typ.ty] { - AlgebraicTypeDef::Sum(sum) => autogen_csharp_sum(module, name.clone(), sum, self.namespace), - AlgebraicTypeDef::Product(prod) => autogen_csharp_tuple(module, name.clone(), prod, self.namespace), + AlgebraicTypeDef::Sum(sum) => autogen_csharp_sum(module, name.clone(), sum, &self.namespace), + AlgebraicTypeDef::Product(prod) => autogen_csharp_tuple(module, name.clone(), prod, &self.namespace), AlgebraicTypeDef::PlainEnum(plain_enum) => { - autogen_csharp_plain_enum(name.clone(), plain_enum, self.namespace) + autogen_csharp_plain_enum(name.clone(), plain_enum, &self.namespace) } }; @@ -818,7 +1082,7 @@ impl Lang for Csharp<'_> { fn generate_reducer_file(&self, module: &ModuleDef, reducer: &spacetimedb_schema::def::ReducerDef) -> OutputFile { let mut output = CsharpAutogen::new( - self.namespace, + &self.namespace, &[ "SpacetimeDB.ClientApi", "System.Collections.Generic", @@ -829,6 +1093,7 @@ impl Lang for Csharp<'_> { writeln!(output, "public sealed partial class RemoteReducers : RemoteBase"); indented_block(&mut output, |output| { + let context = self.root_type("ReducerEventContext"); let func_name_pascal_case = reducer.accessor_name.deref().to_case(Case::Pascal); let delegate_separator = if reducer.params_for_generate.elements.is_empty() { "" @@ -837,11 +1102,11 @@ impl Lang for Csharp<'_> { }; let (func_params, func_args) = - build_func_params_and_args(module, reducer.params_for_generate.into_iter(), self.namespace); + build_func_params_and_args(module, reducer.params_for_generate.into_iter(), &self.namespace); writeln!( output, - "public delegate void {func_name_pascal_case}Handler(ReducerEventContext ctx{delegate_separator}{func_params});" + "public delegate void {func_name_pascal_case}Handler({context} ctx{delegate_separator}{func_params});" ); writeln!( output, @@ -862,7 +1127,7 @@ impl Lang for Csharp<'_> { writeln!( output, - "public bool Invoke{func_name_pascal_case}(ReducerEventContext ctx, Reducer.{func_name_pascal_case} args)" + "public bool Invoke{func_name_pascal_case}({context} ctx, Reducer.{func_name_pascal_case} args)" ); indented_block(output, |output| { writeln!(output, "if (On{func_name_pascal_case} == null)"); @@ -899,12 +1164,17 @@ impl Lang for Csharp<'_> { writeln!(output, "public abstract partial class Reducer"); indented_block(&mut output, |output| { + let base_type = if self.path.is_empty() { + "Reducer, IReducerArgs".to_owned() + } else { + format!("global::{}.Reducer, IReducerArgs", self.root_namespace) + }; autogen_csharp_product_common( module, output, reducer.accessor_name.deref().to_case(Case::Pascal), &reducer.params_for_generate, - "Reducer, IReducerArgs", + &base_type, |output| { if !reducer.params_for_generate.elements.is_empty() { writeln!(output); @@ -926,7 +1196,7 @@ impl Lang for Csharp<'_> { procedure: &spacetimedb_schema::def::ProcedureDef, ) -> OutputFile { let mut output = CsharpAutogen::new( - self.namespace, + &self.namespace, &[ "SpacetimeDB.ClientApi", "System.Collections.Generic", @@ -945,8 +1215,8 @@ impl Lang for Csharp<'_> { }; let (func_params, func_args) = - build_func_params_and_args(module, procedure.params_for_generate.into_iter(), self.namespace); - let return_type_str = ty_fmt_with_ns(module, &procedure.return_type_for_generate, self.namespace); + build_func_params_and_args(module, procedure.params_for_generate.into_iter(), &self.namespace); + let return_type_str = ty_fmt_with_ns(module, &procedure.return_type_for_generate, &self.namespace); // Generate the clean public API that users call to allow us of BSATN.Decode<> then reflect to the proper return type writeln!( output, @@ -1000,7 +1270,7 @@ impl Lang for Csharp<'_> { output, procedure.accessor_name.deref().to_case(Case::Pascal).to_string(), &procedure.return_type_for_generate, - self.namespace, + &self.namespace, ); autogen_csharp_product_common( module, @@ -1012,7 +1282,11 @@ impl Lang for Csharp<'_> { if !procedure.params_for_generate.elements.is_empty() { writeln!(output); } - writeln!(output, "string IProcedureArgs.ProcedureName => \"{}\";", procedure.name); + writeln!( + output, + "string IProcedureArgs.ProcedureName => \"{}{}\";", + self.path, procedure.name + ); }, ); writeln!(output); @@ -1029,7 +1303,7 @@ impl Lang for Csharp<'_> { fn generate_global_files(&self, module: &ModuleDef, options: &CodegenOptions) -> Vec { let mut output = CsharpAutogen::new( - self.namespace, + &self.namespace, &[ "SpacetimeDB.ClientApi", "System.Collections.Generic", @@ -1038,27 +1312,12 @@ impl Lang for Csharp<'_> { true, // print the version in the globals file ); - writeln!(output, "public sealed partial class RemoteReducers : RemoteBase"); - indented_block(&mut output, |output| { - writeln!(output, "internal RemoteReducers(DbConnection conn) : base(conn) {{ }}"); - writeln!( - output, - "internal event Action? InternalOnUnhandledReducerError;" - ) - }); - writeln!(output); - - writeln!(output, "public sealed partial class RemoteProcedures : RemoteBase"); - indented_block(&mut output, |output| { - writeln!( - output, - "internal RemoteProcedures(DbConnection conn) : base(conn) {{ }}" - ); - }); - writeln!(output); + self.function_container(&mut output, module, "RemoteReducers"); + self.function_container(&mut output, module, "RemoteProcedures"); writeln!(output, "public sealed partial class RemoteTables : RemoteTablesBase"); indented_block(&mut output, |output| { + self.child_members(output, module, "RemoteTables"); writeln!(output, "public RemoteTables(DbConnection conn)"); indented_block(output, |output| { for (_, accessor_name, _) in iter_table_names_and_types(module, options.visibility) { @@ -1068,6 +1327,10 @@ impl Lang for Csharp<'_> { accessor_name.deref().to_case(Case::Pascal) ); } + for child in module.submodules().values() { + let name = child.mount_accessor_name().unwrap(); + writeln!(output, "@{name} = new(conn, AddTable);"); + } }); }); writeln!(output); @@ -1084,24 +1347,38 @@ impl Lang for Csharp<'_> { let method_name = accessor_name.deref().to_case(Case::Pascal); writeln!(output, "new QueryBuilder().From.{method_name}().ToSql(),"); } + let mut child_tables = module.all_tables_with_prefix(); + child_tables.sort_by(|(a_path, _, a), (b_path, _, b)| { + (a_path, &a.accessor_name).cmp(&(b_path, &b.accessor_name)) + }); + for (_, owner, table) in child_tables.into_iter().filter(|(path, _, table)| { + !path.is_empty() && table.table_access == spacetimedb_lib::db::raw_def::v9::TableAccess::Public + }) { + writeln!( + output, + "new QueryBuilder().From.{}{}().ToSql(),", + member_path(owner.accessor_path()), + table.accessor_name.deref().to_case(Case::Pascal) + ); + } + for (_, owner, view) in module + .all_views_with_prefix() + .into_iter() + .filter(|(path, _, _)| !path.is_empty()) + { + writeln!( + output, + "new QueryBuilder().From.{}{}().ToSql(),", + member_path(owner.accessor_path()), + view.accessor_name.deref().to_case(Case::Pascal) + ); + } }); writeln!(output, ";"); }); writeln!(output); - writeln!(output, "public sealed class From"); - indented_block(&mut output, |output| { - for (name, accessor_name, product_type_ref) in iter_table_names_and_types(module, options.visibility) { - let method_name = accessor_name.deref().to_case(Case::Pascal); - let row_type = type_ref_name(module, product_type_ref); - let table_name_lit = format!("{:?}", name.deref()); - writeln!( - output, - "public global::SpacetimeDB.Table<{row_type}, {method_name}Cols, {method_name}IxCols> {method_name}() => new({table_name_lit}, new {method_name}Cols({table_name_lit}), new {method_name}IxCols({table_name_lit}));" - ); - } - }); - writeln!(output); + self.from(&mut output, module, options); writeln!(output, "public sealed class TypedSubscriptionBuilder"); indented_block(&mut output, |output| { @@ -1160,7 +1437,12 @@ impl Lang for Csharp<'_> { writeln!(output, "public abstract partial class Reducer"); indented_block(&mut output, |output| { // Prevent instantiation of this class from outside. - writeln!(output, "private Reducer() {{ }}"); + let visibility = if module.submodules().is_empty() { + "private" + } else { + "private protected" + }; + writeln!(output, "{visibility} Reducer() {{ }}"); }); writeln!(output); @@ -1241,6 +1523,16 @@ impl Lang for Csharp<'_> { "Reducer.{reducer_name} args => Reducers.Invoke{reducer_name}(eventContext, args)," ); } + for (_, owner, reducer) in module + .all_reducers_with_prefix() + .into_iter() + .filter(|(path, _, reducer)| !path.is_empty() && !reducer.visibility.is_private()) + { + let namespace = clr_namespace(self.root_namespace, owner.accessor_path()); + let member = member_path(owner.accessor_path()); + let name = reducer.accessor_name.deref().to_case(Case::Pascal); + writeln!(output, "global::{namespace}.Reducer.{name} args => Reducers.{member}Invoke{name}(eventContext, args),"); + } writeln!( output, r#"_ => throw new ArgumentOutOfRangeException("Reducer", $"Unknown reducer {{reducer}}")"# diff --git a/crates/codegen/tests/codegen.rs b/crates/codegen/tests/codegen.rs index 8116c0291fc..699f1dac7bf 100644 --- a/crates/codegen/tests/codegen.rs +++ b/crates/codegen/tests/codegen.rs @@ -10,6 +10,11 @@ fn compiled_module() -> &'static ModuleDef { .get_or_init(|| CompiledModule::compile("module-test", CompilationMode::Debug).extract_schema_blocking()) } +fn compiled_typescript_module() -> &'static ModuleDef { + static MODULE: OnceLock = OnceLock::new(); + MODULE.get_or_init(|| CompiledModule::compile("module-test-ts", CompilationMode::Debug).extract_schema_blocking()) +} + macro_rules! declare_tests { ($($name:ident => $lang:expr,)*) => ($( #[test] @@ -70,8 +75,8 @@ fn test_typescript_table_handles_are_camel_case() { /// submodule, so this checks the TypeScript output of one that does. #[test] fn submodule_names_use_canonical_wire_names_and_accessor_paths() { - let module = CompiledModule::compile("module-test-ts", CompilationMode::Debug).extract_schema_blocking(); - let files = generate(&module, &TypeScript, &CodegenOptions::default()); + let module = compiled_typescript_module(); + let files = generate(module, &TypeScript, &CodegenOptions::default()); let filenames: Vec<_> = files.iter().map(|f| f.filename.clone()).collect(); let code = files.into_iter().map(|f| f.code).collect::>().join("\n"); @@ -123,3 +128,108 @@ fn submodule_names_use_canonical_wire_names_and_accessor_paths() { "generated files must live under the accessor namespace directory; got {filenames:?}" ); } + +#[test] +fn csharp_client_for_typescript_submodule_compiles_and_runs() { + let typescript = compiled_typescript_module(); + compile_csharp_client( + generate( + typescript, + &Csharp { + namespace: "SpacetimeDB", + }, + &CodegenOptions::default(), + ), + r#"class Program { static void Main() { + var conn = new SpacetimeDB.DbConnection(); + try { + if (conn.Db.myLib.LibData.RemoteTableName != "my_lib.libData") throw new System.Exception(conn.Db.myLib.LibData.RemoteTableName); + if (((SpacetimeDB.IReducerArgs)new SpacetimeDB.myLib.Reducer.LibInsert("value")).ReducerName != "my_lib.lib_insert") throw new System.Exception("wrong reducer name"); + if (((SpacetimeDB.IProcedureArgs)new SpacetimeDB.myLib.Procedure.LibCountArgs()).ProcedureName != "my_lib.lib_count") throw new System.Exception("wrong procedure name"); + var sql = new SpacetimeDB.QueryBuilder().From.myLib.LibData().ToSql(); + if (!sql.Contains("\"my_lib\".\"libData\"") || sql.Contains("myLib")) throw new System.Exception(sql); + if (!System.Linq.Enumerable.Contains(SpacetimeDB.QueryBuilder.AllTablesSqlQueries(), sql)) throw new System.Exception("missing namespace subscription"); + } finally { conn.Disconnect(); } + } }"#, + ); +} + +fn compile_csharp_client(files: Vec, program: &str) { + let project = tempfile::tempdir().unwrap(); + for file in files { + let path = project.path().join(file.filename); + fs_err::create_dir_all(path.parent().unwrap()).unwrap(); + fs_err::write(path, file.code).unwrap(); + } + let repo = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../..") + .canonicalize() + .unwrap(); + // Use the local runtime, never a published package or an old NuGet cache entry. + let config = project.path().join("NuGet.Config"); + fs_err::write( + &config, + format!( + r#" + + + + + + + + + +"#, + repo.display() + ), + ) + .unwrap(); + { + let result = std::process::Command::new("dotnet") + .arg("pack") + .arg(repo.join("crates/bindings-csharp/BSATN.Runtime")) + .args(["-c", "Release"]) + .arg(format!("-p:RestoreConfigFile={}", config.display())) + .output() + .expect("dotnet SDK is required for generated C# compilation"); + assert!( + result.status.success(), + "local BSATN pack failed:\n{}\n{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); + } + fs_err::write(project.path().join("Program.cs"), program).unwrap(); + fs_err::write( + project.path().join("client.csproj"), + format!( + r#" + + net8.0 + 9 + Exe + enable + SpacetimeDB.Tests + + +"#, + repo.display() + ), + ) + .unwrap(); + let result = std::process::Command::new("dotnet") + .args(["run", "--project"]) + .arg(project.path().join("client.csproj")) + .arg("-p:TreatWarningsAsErrors=true") + .arg(format!("-p:RestorePackagesPath={}/packages", project.path().display())) + .arg(format!("-p:RestoreConfigFile={}", config.display())) + .output() + .expect("dotnet SDK is required for generated C# compilation"); + assert!( + result.status.success(), + "generated client failed:\n{}\n{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); +} diff --git a/crates/testing/tests/environment.rs b/crates/testing/tests/environment.rs index 4a791ad5b10..4236868bee8 100644 --- a/crates/testing/tests/environment.rs +++ b/crates/testing/tests/environment.rs @@ -61,42 +61,86 @@ async fn expect_view_update(handle: &mut ModuleHandle) { assert_eq!(message.num_rows(), Some(2)); } -async fn check_submodule_scope(handle: &mut ModuleHandle, values: &mut Values) { - values.insert("EMPTY".into(), "root-visible".into()); - let module = publish(handle, values).await; - assert!(module - .info - .module_def - .reducer_by_name("my_lib.env_read_reducer") - .is_some()); +struct SubmoduleScopeCases { + reducer: &'static str, + procedures: &'static [&'static str], + // Canonical lookup name and SQL table expression, respectively. + views: &'static [(&'static str, &'static str)], + root_http_routes: &'static [&'static str], + secret_marker: &'static str, +} + +const TYPESCRIPT_SCOPE: SubmoduleScopeCases = SubmoduleScopeCases { + reducer: "my_lib.env_read_reducer", + procedures: &["my_lib.env_read_procedure", "my_lib.env_read_in_tx"], + views: &[ + ("my_lib.env_read_view", "my_lib.env_read_view"), + ("my_lib.env_read_sql_view", "my_lib.env_read_sql_view"), + ("env_read_root_sql_view", "env_read_root_sql_view"), + ], + root_http_routes: &["/env-child"], + secret_marker: "root-visible", +}; + +const CSHARP_SCOPE: SubmoduleScopeCases = SubmoduleScopeCases { + // The fixture omits Name: the root's default policy converts MyAuth to my_auth. + reducer: "my_auth.expect_environment", + procedures: &["my_auth.read_environment", "my_auth.read_environment_in_tx"], + // C# covers both view context types. The raw-SQL bypass cases above remain TS-only. + views: &[ + ("my_auth.environment_value", "my_auth.environment_value"), + ( + "my_auth.anonymous_environment_value", + "my_auth.anonymous_environment_value", + ), + ], + root_http_routes: &["/root-environment", "/auth-environment"], + secret_marker: "root-secret-", +}; + +async fn check_submodule_scope( + handle: &ModuleHandle, + cases: &SubmoduleScopeCases, + reducer_args: FunctionArgs, + expected_http: &str, +) { + let module = handle.client.module(); + assert!(module.info.module_def.reducer_by_name(cases.reducer).is_some()); let child = module - .call_reducer( - Identity::ZERO, - None, - None, - None, - None, - "my_lib.env_read_reducer", - FunctionArgs::Nullary, - ) + .call_reducer(Identity::ZERO, None, None, None, None, cases.reducer, reducer_args) .await; - assert!(child.is_err() || child.unwrap().outcome.into_result().is_err()); - for procedure in ["my_lib.env_read_procedure", "my_lib.env_read_in_tx"] { + let error = match child { + Err(error) => format!("{error:#}"), + Ok(result) => format!( + "{:?}", + result + .outcome + .into_result() + .expect_err("submodule reducer read the root environment") + ), + }; + assert!( + !error.contains(cases.secret_marker), + "reducer error exposed environment data" + ); + for &procedure in cases.procedures { assert!(module.info.module_def.procedure_by_name(procedure).is_some()); let result = module .call_procedure(Identity::ZERO, None, None, procedure, FunctionArgs::Nullary) .await; - assert!(result.result.is_err(), "submodule procedure read the root environment"); + let error = result + .result + .expect_err("submodule procedure read the root environment"); + assert!( + !format!("{error:#}").contains(cases.secret_marker), + "procedure error exposed environment data" + ); } - for view in [ - "my_lib.env_read_view", - "my_lib.env_read_sql_view", - "env_read_root_sql_view", - ] { + for &(view, sql_table) in cases.views { assert!(module.info.module_def.view_by_name_with_module(view).is_some()); let result = spacetimedb::sql::execute::run( module.relational_db().clone(), - format!("SELECT * FROM {view}"), + format!("SELECT * FROM {sql_table}"), AuthCtx::for_current(Identity::ZERO), Some(module.info.subscriptions.clone()), Some(module.clone()), @@ -110,17 +154,22 @@ async fn check_submodule_scope(handle: &mut ModuleHandle, values: &mut Values) { Err(error) => { let error = format!("{error:#}"); assert!(!error.contains("not found"), "view failed before dispatch: {error}"); - assert!(!error.contains("root-visible"), "view error exposed environment data"); + assert!( + !error.contains(cases.secret_marker), + "view error exposed environment data" + ); } } } // HTTP routes are root entries today. Calling an exported child callback // as an ordinary helper retains that root entry's authority. - assert_eq!( - &handle.call_http_route_get("/env-child").await.unwrap()[..], - b"root-visible" - ); + for route in cases.root_http_routes { + assert_eq!( + handle.call_http_route_get(route).await.unwrap().as_ref(), + expected_http.as_bytes() + ); + } } // Qualification can pin locally built inputs without invoking a nested build. @@ -292,7 +341,9 @@ fn exercise_fixture(name: &str) { } } if name == "module-test-ts" { - check_submodule_scope(&mut handle, &mut values).await; + values.insert("EMPTY".into(), "root-visible".into()); + publish(&handle, &values).await; + check_submodule_scope(&handle, &TYPESCRIPT_SCOPE, FunctionArgs::Nullary, "root-visible").await; } for key in ["UNDECLARED", "A=B"] { let result = handle @@ -343,6 +394,67 @@ fn csharp_environment_publish_and_checked_reads() { exercise_fixture("module-test-cs"); } +#[test] +#[serial] +fn namespace_csharp_environment_security() { + compiled_fixture("namespace-environment-test-cs").with_module_async_with_environment( + DEFAULT_CONFIG, + Values::from([ + ("NAMESPACE_TEST".into(), "root-secret-first".into()), + ("PUBLIC_LIBRARY_TEST".into(), "public-library-secret".into()), + ]), + |handle| async move { + for value in [Some("root-secret-first"), Some("root-secret-second"), Some(""), None] { + let mut values = Values::from([("PUBLIC_LIBRARY_TEST".into(), "public-library-secret".into())]); + if let Some(value) = value { + values.insert("NAMESPACE_TEST".into(), value.into()); + } + let module = publish(&handle, &values).await; + let expected = value.unwrap_or("unset"); + handle + .call_reducer_binary("expect_environment", &product![value]) + .await + .unwrap(); + check_submodule_scope( + &handle, + &CSHARP_SCOPE, + FunctionArgs::Bsatn(bsatn::to_vec(&product![value]).unwrap().into()), + expected, + ) + .await; + // Denied child calls must not leave subsequent root calls in the child scope. + // The root procedure also checks ordinary library helpers and transactions. + assert_eq!( + handle.call_procedure_with_args("read_environment", "[]").await.unwrap(), + AlgebraicValue::String(expected.into()) + ); + assert_eq!( + handle + .call_procedure_with_args("read_public_environment", "[]") + .await + .unwrap(), + AlgebraicValue::String("public-library-secret".into()) + ); + for view in ["environment_value", "anonymous_environment_value"] { + assert_eq!( + sql(&module, &format!("SELECT * FROM {view}")).await, + vec![product![expected]] + ); + } + let denied = handle + .call_procedure_with_args("read_environment_key", r#"["UNDECLARED"]"#) + .await + .expect_err("even root calls must not read undeclared keys"); + assert!(!format!("{denied:#}").contains(CSHARP_SCOPE.secret_marker)); + assert_eq!( + handle.call_procedure_with_args("read_environment", "[]").await.unwrap(), + AlgebraicValue::String(expected.into()) + ); + } + }, + ); +} + #[cfg(feature = "allow_loopback_http_for_tests")] #[test] #[serial] diff --git a/crates/testing/tests/standalone_integration_test.rs b/crates/testing/tests/standalone_integration_test.rs index 8214e527120..3dde72f5479 100644 --- a/crates/testing/tests/standalone_integration_test.rs +++ b/crates/testing/tests/standalone_integration_test.rs @@ -99,6 +99,150 @@ fn test_calling_a_reducer_csharp() { test_calling_a_reducer_in_module("module-test-cs"); } +#[test] +#[serial] +fn namespace_csharp_root_selected_at_publish() { + init(); + + // Build the dependency first, then reuse its managed DLL without rebuilding or changing its project. + let dependency = CompiledModule::compile("root-selection-dependency-cs", CompilationMode::Debug); + dependency.with_module_async(DEFAULT_CONFIG, |module| async move { + module + .call_reducer_binary("dependency_entry", &product![]) + .await + .unwrap(); + assert!(module.read_log(None).await.contains("dependency published as root")); + }); + + // Both assemblies contain generated host entrypoint declarations. Only the published root's + // declarations must become native exports; otherwise publishing produces duplicate symbols. + CompiledModule::compile("root-selection-consumer-cs", CompilationMode::Debug).with_module_async( + DEFAULT_CONFIG, + |module| async move { + module.call_reducer_binary("consumer_entry", &product![]).await.unwrap(); + assert!(module.read_log(None).await.contains("consumer published as root")); + module + .call_reducer_binary("dependency_entry", &product![]) + .await + .unwrap(); + assert!(module.read_log(None).await.contains("dependency published as root")); + }, + ); +} + +#[test] +#[serial] +fn namespace_csharp_cross_namespace_calls() { + init(); + CompiledModule::compile("namespace-test-cs", CompilationMode::Debug).with_module_async( + DEFAULT_CONFIG, + |mut module| async move { + // Mirror test_submodule_in_module: enter the root through the websocket API, + // then delegate to exported library callbacks using the same context object. + module + .send_reducer_and_recv_update( + r#"{"CallReducer":{"reducer":"add_auth_user","args":"[12]","request_id":0,"flags":0}}"#.to_string(), + 0, + ) + .await + .unwrap(); + assert_eq!(read_logs(&module).await, ["Auth users: 1"]); + assert_eq!( + module.call_procedure_with_args("count_auth_users", "[]").await.unwrap(), + AlgebraicValue::U64(1) + ); + assert_eq!( + module.call_http_route_get("/root-auth-count").await.unwrap().as_ref(), + b"1" + ); + + // The library's own route remains registered alongside the root's route. + assert_eq!(module.call_http_route_get("/auth-count").await.unwrap().as_ref(), b"1"); + assert_eq!( + module + .call_procedure_with_args("class.count_users", "[]") + .await + .unwrap(), + AlgebraicValue::U64(0) + ); + assert_eq!( + module.call_procedure_with_args("count_users", "[]").await.unwrap(), + AlgebraicValue::U64(1), + "delegation must not also insert into the root or Audit table" + ); + }, + ); +} + +#[test] +#[serial] +fn namespace_csharp_canonical_name_resolution() { + use spacetimedb_lib::db::raw_def::v10::{CaseConversionPolicy, ExplicitNames, RawModuleDefV10Builder}; + use spacetimedb_schema::def::ModuleDef; + init(); + CompiledModule::compile("namespace-test-cs", CompilationMode::Debug).with_module_async( + DEFAULT_CONFIG, + |module| async move { + // Derive expected names with the actual host validator, not a second test-side converter. + for accessor in ["MyHTTP2Auth", "public", ""] { + for root_none in [false, true] { + for child_none in [false, true] { + for (source, explicit) in [ + ("HTTP2ReducerTick", None), + ("__my__XMLParser99", None), + ("already_snake_case", None), + ("SourceName", Some("ExplicitNAME")), + ] { + let mut root = RawModuleDefV10Builder::new(); + root.set_case_conversion_policy(if root_none { + CaseConversionPolicy::None + } else { + CaseConversionPolicy::SnakeCase + }); + let mut child = RawModuleDefV10Builder::new(); + child.set_case_conversion_policy(if child_none { + CaseConversionPolicy::None + } else { + CaseConversionPolicy::SnakeCase + }); + let named = !accessor.is_empty() && accessor != "public"; + let target = if named { &mut child } else { &mut root }; + target.add_reducer(source, spacetimedb_lib::ProductType::unit()); + if let Some(name) = explicit { + let mut names = ExplicitNames::default(); + names.insert_function(source, name); + target.add_explicit_names(names); + } + if named { + root.add_submodule(accessor, child.finish()); + } + let schema: ModuleDef = root.finish().try_into().unwrap(); + let expected = schema.all_reducers_with_prefix()[0].2.name.to_string(); + let args = serde_json::json!([ + accessor, + null, + source, + explicit.map(|name| serde_json::json!({"some": name})), + root_none, + child_none + ]) + .to_string(); + assert_eq!( + module + .call_procedure_with_args("resolve_schedule_name", &args) + .await + .unwrap(), + AlgebraicValue::String(expected.into()), + "{args}" + ); + } + } + } + } + }, + ); +} + #[test] #[serial] fn test_calling_a_reducer_typescript() { diff --git a/modules/namespace-environment-test-cs/Lib.cs b/modules/namespace-environment-test-cs/Lib.cs new file mode 100644 index 00000000000..aa6b3124845 --- /dev/null +++ b/modules/namespace-environment-test-cs/Lib.cs @@ -0,0 +1,69 @@ +using SpacetimeDB; + +[assembly: Namespace(typeof(AuthLib.Functions), Accessor = "MyAuth")] + +namespace NamespaceRoot; + +[SpacetimeDB.Env] +public struct EnvironmentSchema +{ + public string? NAMESPACE_TEST; +} + +public static partial class Functions +{ + [Procedure] + public static string ReadEnvironment(ProcedureContext ctx) + { + var value = ctx.Env.NAMESPACE_TEST; + if (AuthLib.Functions.ReadEnvironment(ctx) != (value ?? "unset")) + { + throw new Exception("Library helper must retain root environment access"); + } + + if (AuthLib.Functions.ReadEnvironmentInTx(ctx) != (value ?? "unset")) + { + throw new Exception("Library transaction helper must retain root environment access"); + } + + return ctx.WithTx(tx => + { + if (tx.Env.NAMESPACE_TEST != value) + { + throw new Exception("Root transaction environment mismatch"); + } + + return value ?? "unset"; + }); + } + + [HttpRouter] + public static Router Routes() => + Router.New().Get("/root-environment", new Handler(nameof(RootEnvironment))); + + [Reducer] + public static void ExpectEnvironment(ReducerContext ctx, string? expected) + { + if (ctx.Env.NAMESPACE_TEST != expected) + { + throw new Exception("Root environment mismatch"); + } + + AuthLib.Functions.ExpectEnvironment(ctx, expected); + } + + [Procedure] + public static string? ReadEnvironmentKey(ProcedureContext ctx, string key) => ctx.Env.Get(key); + + [HttpHandler] + public static HttpResponse RootEnvironment(HandlerContext ctx, HttpRequest request) => + AuthLib.Functions.EnvironmentHandler(ctx, request); + + [View(Accessor = "EnvironmentValue", Public = true)] + public static AuthLib.EnvironmentValue? EnvironmentValue(ViewContext ctx) => + AuthLib.Functions.EnvironmentValue(ctx); + + [View(Accessor = "AnonymousEnvironmentValue", Public = true)] + public static AuthLib.EnvironmentValue? AnonymousEnvironmentValue(AnonymousViewContext ctx) => + AuthLib.Functions.AnonymousEnvironmentValue(ctx); +} diff --git a/modules/namespace-environment-test-cs/README.md b/modules/namespace-environment-test-cs/README.md new file mode 100644 index 00000000000..ec3997b827b --- /dev/null +++ b/modules/namespace-environment-test-cs/README.md @@ -0,0 +1,30 @@ +# Namespace Environment Security Fixture + +Run with `cargo test -p spacetimedb-testing --test environment namespace_csharp_environment_security`. +The test is also included by the `namespace_csharp` selector. The fixture requires .NET 10. + +The `environment` suite shares `check_submodule_scope` between this test and +`typescript_environment_publish_and_checked_reads`. The case lists record each +language's entrypoint names and coverage: TypeScript additionally tests raw-SQL +bypass attempts; C# tests both sender and anonymous view contexts. C#-specific +declaration composition, root controls, and value-update checks stay in this test. + +The root declares an optional environment key. AuthLib is registered in `MyAuth`; +PublicLib is discovered automatically and contributes an environment declaration +and procedure to `public`. + +The test publishes a real value, replaces it, sets it to empty, and removes it. It verifies: + +- Root reads and ordinary cross-assembly helpers retain root authority. +- Host-dispatched namespaced reducers, procedures (including transactions), and + sender/anonymous views cannot read the root environment. +- A rejected call does not prevent subsequent root reads, or expose the value in errors. +- Root callers still cannot read undeclared keys. +- A dependency registered in `public` can declare and read environment keys. +- HTTP routes remain root entries, including dependency-defined routes; handlers + and handler transactions retain root authority. + +Root views intentionally expose the test value as a positive control. Child views +intentionally fail, so this fixture is separate from the general namespace client +regression that subscribes to all public tables and views. As in the TypeScript +environment tests, failed views may return no rows instead of an error (issue #5912). diff --git a/modules/namespace-environment-test-cs/libraries/AuthLib/AuthLib.csproj b/modules/namespace-environment-test-cs/libraries/AuthLib/AuthLib.csproj new file mode 100644 index 00000000000..05c7687b3b1 --- /dev/null +++ b/modules/namespace-environment-test-cs/libraries/AuthLib/AuthLib.csproj @@ -0,0 +1,11 @@ + + + net10.0 + NamespaceEnvironmentAuthLib + $(AssemblyName) + + + + + + diff --git a/modules/namespace-environment-test-cs/libraries/AuthLib/Lib.cs b/modules/namespace-environment-test-cs/libraries/AuthLib/Lib.cs new file mode 100644 index 00000000000..868ca30fa51 --- /dev/null +++ b/modules/namespace-environment-test-cs/libraries/AuthLib/Lib.cs @@ -0,0 +1,55 @@ +using SpacetimeDB; + +#pragma warning disable STDB_UNSTABLE + +namespace AuthLib; + +[SpacetimeDB.Type] +public partial struct EnvironmentValue +{ + public string Value; +} + +public static partial class Functions +{ + [Procedure] + public static string ReadEnvironment(ProcedureContext ctx) => + ctx.Env.Get("NAMESPACE_TEST") ?? "unset"; + + [HttpRouter] + public static Router Routes() => + Router.New().Get("/auth-environment", new Handler(nameof(EnvironmentHandler))); + + [Reducer] + public static void ExpectEnvironment(ReducerContext ctx, string? expected) + { + if (ctx.Env.Get("NAMESPACE_TEST") != expected) + { + throw new Exception("Library environment mismatch"); + } + } + + [Procedure] + public static string ReadEnvironmentInTx(ProcedureContext ctx) => + ctx.WithTx(tx => tx.Env.Get("NAMESPACE_TEST") ?? "unset"); + + [HttpHandler] + public static HttpResponse EnvironmentHandler(HandlerContext ctx, HttpRequest request) + { + var value = ctx.Env.Get("NAMESPACE_TEST"); + if (ctx.WithTx(tx => tx.Env.Get("NAMESPACE_TEST")) != value) + { + throw new Exception("Handler transaction environment mismatch"); + } + + return new(200, HttpVersion.Http11, [], HttpBody.FromString(value ?? "unset")); + } + + [View(Accessor = "EnvironmentValue", Public = true)] + public static EnvironmentValue? EnvironmentValue(ViewContext ctx) => + new EnvironmentValue { Value = ctx.Env.Get("NAMESPACE_TEST") ?? "unset" }; + + [View(Accessor = "AnonymousEnvironmentValue", Public = true)] + public static EnvironmentValue? AnonymousEnvironmentValue(AnonymousViewContext ctx) => + new EnvironmentValue { Value = ctx.Env.Get("NAMESPACE_TEST") ?? "unset" }; +} diff --git a/modules/namespace-environment-test-cs/libraries/PublicLib/Lib.cs b/modules/namespace-environment-test-cs/libraries/PublicLib/Lib.cs new file mode 100644 index 00000000000..4e651699937 --- /dev/null +++ b/modules/namespace-environment-test-cs/libraries/PublicLib/Lib.cs @@ -0,0 +1,24 @@ +using SpacetimeDB; + +namespace PublicLib; + +[SpacetimeDB.Env] +public struct EnvironmentSchema +{ + public string? PUBLIC_LIBRARY_TEST; +} + +public static partial class Functions +{ + [Procedure] + public static string ReadPublicEnvironment(ProcedureContext ctx) + { + var value = ctx.Env.PUBLIC_LIBRARY_TEST; + if (ctx.WithTx(tx => tx.Env.PUBLIC_LIBRARY_TEST) != value) + { + throw new Exception("Public library transaction environment mismatch"); + } + + return value ?? "unset"; + } +} diff --git a/modules/namespace-environment-test-cs/libraries/PublicLib/PublicLib.csproj b/modules/namespace-environment-test-cs/libraries/PublicLib/PublicLib.csproj new file mode 100644 index 00000000000..4433be5c78d --- /dev/null +++ b/modules/namespace-environment-test-cs/libraries/PublicLib/PublicLib.csproj @@ -0,0 +1,11 @@ + + + net10.0 + NamespaceEnvironmentPublicLib + $(AssemblyName) + + + + + + diff --git a/modules/namespace-environment-test-cs/namespace-environment-test-cs.csproj b/modules/namespace-environment-test-cs/namespace-environment-test-cs.csproj new file mode 100644 index 00000000000..17958d46503 --- /dev/null +++ b/modules/namespace-environment-test-cs/namespace-environment-test-cs.csproj @@ -0,0 +1,12 @@ + + + net10.0 + + + + + + + + + diff --git a/modules/namespace-test-cs/Lib.cs b/modules/namespace-test-cs/Lib.cs new file mode 100644 index 00000000000..76d771f4cf7 --- /dev/null +++ b/modules/namespace-test-cs/Lib.cs @@ -0,0 +1,180 @@ +using SpacetimeDB; + +[assembly: Namespace(typeof(AuthLib.Marker), Accessor = "MyAuth", Name = "auth_data")] +[assembly: Namespace(typeof(AuditLib.Marker), Accessor = "class")] + +namespace NamespaceRoot; + +[Table(Accessor = "User", Public = true)] +public partial struct User +{ + [PrimaryKey] + public uint Id; +} + +[SpacetimeDB.Type] +public partial struct AuthSummary +{ + public uint Score; +} + +public static partial class Functions +{ + // Compare the runtime resolver with host validation, including naming policies + // that differ from this fixture's own policy, without publishing extra modules. + [Procedure] + public static string ResolveScheduleName( + ProcedureContext ctx, + string accessor, + string? namespaceName, + string sourceName, + string? functionName, + bool rootNone, + bool childNone + ) => + new SpacetimeDB.Internal.NamespaceRegistry( + "root", + rootNone ? CaseConversionPolicy.None : CaseConversionPolicy.SnakeCase, + accessor.Length == 0 + ? [] + : + [ + ( + "dependency", + accessor, + namespaceName, + childNone ? CaseConversionPolicy.None : CaseConversionPolicy.SnakeCase + ), + ] + ).ResolveFunction(accessor.Length == 0 ? "root" : "dependency", sourceName, functionName); + + [Reducer] + public static void AddAuthUser(ReducerContext ctx, uint id) + { + AuthLib.Functions.Add(ctx, id); + Log.Info($"Auth users: {AuthLib.Functions.Count(ctx)}"); + } + + [Procedure] + public static ulong CountAuthUsers(ProcedureContext ctx) => AuthLib.Functions.CountUsers(ctx); + + [HttpHandler] + public static HttpResponse RootAuthCount(HandlerContext ctx, HttpRequest request) => + AuthLib.Functions.AuthCount(ctx, request); + + [HttpRouter] + public static Router Routes() => + Router.New().Get("/root-auth-count", SpacetimeDB.Handlers.RootAuthCount); + +#pragma warning disable STDB_UNSTABLE + [ClientVisibilityFilter] + public static readonly Filter ProtectedRows = new Filter.Sql( + "SELECT * FROM auth_data.protected_row WHERE owner = :sender" + ); +#pragma warning restore STDB_UNSTABLE + + // Test setup deliberately permits writing for either client; RLS restricts reads, not reducers. + [Reducer] + public static void WriteProtectedRow(ReducerContext ctx, uint id, Identity owner, uint value) + { + var row = new AuthLib.ProtectedRow + { + Id = id, + Owner = owner, + Value = value, + }; + if (ctx.Db.MyAuth.ProtectedRow.Id.Find(id) is null) + { + ctx.Db.MyAuth.ProtectedRow.Insert(row); + } + else + { + ctx.Db.MyAuth.ProtectedRow.Id.Update(row); + } + } + + [Reducer] + public static void Exercise(ReducerContext ctx) + { + if ( + !ReferenceEquals(ctx.Db.User.Id, ctx.Db.User.Id) + || !ReferenceEquals(ctx.Db.MyAuth.User.Id, ctx.Db.MyAuth.User.Id) + || !ReferenceEquals(ctx.Db.MyAuth.User.ByScore, ctx.Db.MyAuth.User.ByScore) + || ReferenceEquals(ctx.Db.User.Id, ctx.Db.MyAuth.User.Id) + || ReferenceEquals(ctx.Db.MyAuth.User.Id, ctx.Db.@class.User.Id) + ) + { + throw new Exception("Index handles must be reused within, but not across, table scopes."); + } + + ctx.Db.User.Insert(new User { Id = 2 }); + AuthLib.Functions.Insert(ctx, 2); + ctx.Db.MyAuth.User.Insert(new AuthLib.User { Id = 3, Score = 43 }); + ctx.Db.@class.User.Insert(new AuditLib.User { Id = 4, Message = "consumer" }); + if ( + ctx.Db.User.Count != 1 + || AuthLib.Functions.Count(ctx) != 2 + || ctx.Db.@class.User.Count != 1 + || ctx.Db.ExtraRow.Count != 1 + ) + { + throw new Exception("Namespace counts are not isolated."); + } + + var row = ctx.Db.MyAuth.User.Id.Find(2)!.Value; + row.Score = 99; + ctx.Db.MyAuth.User.Id.Update(row); + if (ctx.Db.MyAuth.User.ByScore.Filter(99u).Single().Id != 2) + { + throw new Exception("Mounted index lookup failed."); + } + + if (!ctx.Db.MyAuth.User.Id.Delete(3) || ctx.Db.MyAuth.User.Count != 1) + { + throw new Exception("Mounted unique deletion failed."); + } + + Log.Info("namespace composition works"); + } + + [Procedure] + public static ulong CountUsers(ProcedureContext ctx) => + ctx.WithTx(tx => tx.Db.User.Count + tx.Db.MyAuth.User.Count + tx.Db.@class.User.Count); + + [Procedure] + public static uint WriteAcrossNamespaces(ProcedureContext ctx, uint id, bool fail) => + ctx.WithTx(tx => + { + tx.Db.User.Insert(new User { Id = id }); + AuthLib.Functions.Insert(tx, id); + tx.Db.@class.User.Insert(new AuditLib.User { Id = id, Message = "procedure" }); + if (fail) + { + throw new Exception("cross-namespace procedure rollback"); + } + + return tx.Db.MyAuth.User.Id.Find(id)!.Value.Score; + }); + + [View(Accessor = "Users", Public = true)] + public static User? Users(ViewContext ctx) => ctx.Db.User.Id.Find(2); + + [View(Accessor = "QueryUsers", Public = true)] + public static IQuery QueryUsers(AnonymousViewContext ctx) => + ctx.From.User().LeftSemijoin(ctx.From.MyAuth.User(), (root, auth) => root.Id.Eq(auth.Id)); + + [View(Accessor = "QueryUsersRight", Public = true)] + public static IQuery QueryUsersRight(ViewContext ctx) => + AuthLib.Functions.Query(ctx).RightSemijoin(ctx.From.User(), (auth, root) => auth.Id.Eq(root.Id)); + + [View(Accessor = "QueryExtra", Public = true)] + public static IQuery QueryExtra(AnonymousViewContext ctx) => + ctx.From.ExtraRow().Where(row => row.Id.Eq(7u)); + + [View(Accessor = "AuthUsers", Public = true)] + public static List AuthUsers(ViewContext ctx) => + ctx + .Db.MyAuth.User.ByScore.Filter(99u) + .Select(row => new AuthSummary { Score = row.Score }) + .ToList(); +} diff --git a/modules/namespace-test-cs/libraries/AuditLib/AuditLib.csproj b/modules/namespace-test-cs/libraries/AuditLib/AuditLib.csproj new file mode 100644 index 00000000000..1de85406f46 --- /dev/null +++ b/modules/namespace-test-cs/libraries/AuditLib/AuditLib.csproj @@ -0,0 +1,11 @@ + + + net10.0 + NamespaceAuditLib + $(AssemblyName) + + + + + + diff --git a/modules/namespace-test-cs/libraries/AuditLib/Lib.cs b/modules/namespace-test-cs/libraries/AuditLib/Lib.cs new file mode 100644 index 00000000000..ccab3d00dd6 --- /dev/null +++ b/modules/namespace-test-cs/libraries/AuditLib/Lib.cs @@ -0,0 +1,23 @@ +using SpacetimeDB; + +namespace AuditLib; + +public class Marker { } + +[Table(Accessor = "User", Public = true)] +public partial struct User +{ + [PrimaryKey] + public uint Id; + public string Message; +} + +public static partial class Functions +{ + [Reducer] + public static void Add(ReducerContext ctx, uint id) => + ctx.Db.User.Insert(new User { Id = id, Message = "audit" }); + + [Procedure] + public static ulong CountUsers(ProcedureContext ctx) => ctx.WithTx(tx => tx.Db.User.Count); +} diff --git a/modules/namespace-test-cs/libraries/AuditLib/Scheduled.cs b/modules/namespace-test-cs/libraries/AuditLib/Scheduled.cs new file mode 100644 index 00000000000..dac8bc2a193 --- /dev/null +++ b/modules/namespace-test-cs/libraries/AuditLib/Scheduled.cs @@ -0,0 +1,176 @@ +using SpacetimeDB; + +#pragma warning disable STDB_UNSTABLE + +namespace AuditLib; + +[Table( + Accessor = "ReducerJob", + Name = "reducer_jobs", + Scheduled = nameof(ScheduledFunctions.ReducerTick), + ScheduledAt = nameof(Due) +)] +public partial struct ReducerJob +{ + [PrimaryKey, AutoInc] + public ulong Id; + public uint JobId; + public ScheduleAt Due; + public uint Payload; +} + +[Table( + Accessor = "ProcedureJob", + Name = "procedure_jobs", + Scheduled = nameof(ScheduledFunctions.ProcedureTick), + ScheduledAt = nameof(Due) +)] +public partial struct ProcedureJob +{ + [PrimaryKey, AutoInc] + public ulong Id; + public uint JobId; + public uint Payload; + public ScheduleAt Due; +} + +[Table(Accessor = "ScheduleResult", Public = true)] +public partial struct ScheduleResult +{ + [PrimaryKey] + public uint JobId; + public uint Payload; + public string Kind; + public uint Executions; + public ulong ScheduledId; +} + +public static partial class ScheduledFunctions +{ + private const uint PayloadBase = 2000; + + [Reducer] + public static void StartSchedules(ReducerContext ctx) + { + var due = new ScheduleAt.Time(ctx.Timestamp + new TimeDuration(100_000)); + ctx.Db.ReducerJob.Insert( + new ReducerJob + { + JobId = 1, + Due = due, + Payload = PayloadBase + 1, + } + ); + ctx.Db.ProcedureJob.Insert( + new ProcedureJob + { + JobId = 2, + Due = due, + Payload = PayloadBase + 2, + } + ); + VolatileNonatomicScheduleImmediateReducerTick( + new ReducerJob + { + JobId = 3, + Due = due, + Payload = PayloadBase + 3, + } + ); + VolatileNonatomicScheduleImmediateProcedureTick( + new ProcedureJob + { + JobId = 4, + Due = due, + Payload = PayloadBase + 4, + } + ); + ctx.Db.ReducerJob.Insert( + new ReducerJob + { + JobId = 5, + Due = new ScheduleAt.Interval(new TimeDuration(100_000)), + Payload = PayloadBase + 5, + } + ); + } + + [Reducer(Name = "run_reducer_job")] + public static void ReducerTick(ReducerContext ctx, ReducerJob job) + { + var previous = ctx.Db.ScheduleResult.JobId.Find(job.JobId); + var result = new ScheduleResult + { + JobId = job.JobId, + Payload = job.Payload, + Kind = "reducer", + Executions = (previous?.Executions ?? 0) + 1, + ScheduledId = job.Id, + }; + if (previous is null) + { + ctx.Db.ScheduleResult.Insert(result); + } + else + { + ctx.Db.ScheduleResult.JobId.Update(result); + } + } + + [Procedure(Name = "run_procedure_job")] + public static void ProcedureTick(ProcedureContext ctx, ProcedureJob job) + { + ctx.WithTx(tx => + { + var previous = tx.Db.ScheduleResult.JobId.Find(job.JobId); + var result = new ScheduleResult + { + JobId = job.JobId, + Payload = job.Payload, + Kind = "procedure", + Executions = (previous?.Executions ?? 0) + 1, + ScheduledId = job.Id, + }; + if (previous is null) + { + tx.Db.ScheduleResult.Insert(result); + } + else + { + tx.Db.ScheduleResult.JobId.Update(result); + } + + return 0; + }); + } + + [Reducer] + public static void CancelSchedules(ReducerContext ctx) + { + var repeat = ctx.Db.ScheduleResult.JobId.Find(5)!.Value; + if (repeat.Executions < 2) + { + throw new Exception("Repeating schedule has not run twice."); + } + + ctx.Db.ReducerJob.Id.Delete(repeat.ScheduledId); + ctx.Db.ScheduleResult.Insert( + new ScheduleResult + { + JobId = 6, + Payload = PayloadBase + 6, + Kind = "cancel", + Executions = repeat.Executions, + } + ); + // This later job provides a scheduler-driven observation point after cancellation. + ctx.Db.ReducerJob.Insert( + new ReducerJob + { + JobId = 7, + Due = new ScheduleAt.Time(ctx.Timestamp + new TimeDuration(500_000)), + Payload = PayloadBase + 7, + } + ); + } +} diff --git a/modules/namespace-test-cs/libraries/AuthLib/AuthLib.csproj b/modules/namespace-test-cs/libraries/AuthLib/AuthLib.csproj new file mode 100644 index 00000000000..1e9afde0747 --- /dev/null +++ b/modules/namespace-test-cs/libraries/AuthLib/AuthLib.csproj @@ -0,0 +1,11 @@ + + + net10.0 + NamespaceAuthLib + $(AssemblyName) + + + + + + diff --git a/modules/namespace-test-cs/libraries/AuthLib/Lib.cs b/modules/namespace-test-cs/libraries/AuthLib/Lib.cs new file mode 100644 index 00000000000..9f4db5a0680 --- /dev/null +++ b/modules/namespace-test-cs/libraries/AuthLib/Lib.cs @@ -0,0 +1,116 @@ +using SpacetimeDB; + +#pragma warning disable STDB_UNSTABLE + +namespace AuthLib; + +public class Marker { } + +[Table(Accessor = "ProtectedRow", Public = true)] +public partial struct ProtectedRow +{ + [PrimaryKey] + public uint Id; + public Identity Owner; + public uint Value; +} + +[Table(Accessor = "User", Name = "auth_users", Public = true)] +[SpacetimeDB.Index.BTree(Accessor = "ByScore", Columns = [nameof(Score)])] +public partial struct User +{ + [PrimaryKey] + public uint Id; + public uint Score; +} + +[Table(Accessor = "Notice", Public = true, Event = true)] +public partial struct Notice +{ + public uint Id; +} + +[Table(Accessor = "Secret")] +public partial struct Secret +{ + public uint Id; +} + +public static partial class Functions +{ + public static void Insert(ReducerContext ctx, uint id) => + ctx.Db.User.Insert(new User { Id = id, Score = 42 }); + + public static void Insert(ProcedureTxContext ctx, uint id) => + ctx.Db.User.Insert(new User { Id = id, Score = 42 }); + + public static ulong Count(ReducerContext ctx) => ctx.Db.User.Count; + + public static FromWhere Query(ViewContext ctx) => + ctx.From.User().Where(row => row.Score.Eq(99u)); + + [View(Accessor = "QueryUsers", Public = true)] + public static IQuery QueryUsers(ViewContext ctx) => Query(ctx); + + [Reducer] + public static void Add(ReducerContext ctx, uint id) + { + Insert(ctx, id); + ctx.Db.Notice.Insert(new Notice { Id = id }); + ctx.Db.Secret.Insert(new Secret { Id = id }); + } + + [Reducer] + public static void Fail(ReducerContext ctx, uint id) + { + Insert(ctx, id); + throw new Exception("namespace rollback"); + } + + [Reducer] + public static void Update(ReducerContext ctx, uint id, uint score) + { + var row = ctx.Db.User.Id.Find(id)!.Value; + row.Score = score; + ctx.Db.User.Id.Update(row); + } + + [Reducer] + public static void Remove(ReducerContext ctx, uint id) => ctx.Db.User.Id.Delete(id); + + [Procedure] + public static uint ReadScore(ProcedureContext ctx, uint id) => + ctx.WithTx(tx => tx.Db.User.Id.Find(id)?.Score ?? throw new Exception("missing auth user")); + + [Procedure] + public static ulong CountUsers(ProcedureContext ctx) => ctx.WithTx(tx => tx.Db.User.Count); + + [View(Accessor = "Users", Public = true)] + public static User? Users(ViewContext ctx) + { + if ( + !ReferenceEquals(ctx.Db.User.Id, ctx.Db.User.Id) + || !ReferenceEquals(ctx.Db.User.ByScore, ctx.Db.User.ByScore) + ) + { + throw new Exception("Read-only index handles must be reused."); + } + + return ctx.Db.User.Id.Find(2); + } + + [View(Accessor = "AnonymousUsers", Public = true)] + public static User? AnonymousUsers(AnonymousViewContext ctx) => ctx.Db.User.Id.Find(2); + + [HttpHandler] + public static HttpResponse AuthCount(HandlerContext ctx, HttpRequest request) => + new( + 200, + HttpVersion.Http11, + [], + HttpBody.FromString(ctx.WithTx(tx => tx.Db.User.Count).ToString()) + ); + + [HttpRouter] + public static Router Routes() => Router.New().Get("/auth-count", Handlers.AuthCount); +} diff --git a/modules/namespace-test-cs/libraries/AuthLib/Scheduled.cs b/modules/namespace-test-cs/libraries/AuthLib/Scheduled.cs new file mode 100644 index 00000000000..a6521e94117 --- /dev/null +++ b/modules/namespace-test-cs/libraries/AuthLib/Scheduled.cs @@ -0,0 +1,176 @@ +using SpacetimeDB; + +#pragma warning disable STDB_UNSTABLE + +namespace AuthLib; + +[Table( + Accessor = "ReducerJob", + Name = "reducer_jobs", + Scheduled = nameof(ScheduledFunctions.ReducerTick), + ScheduledAt = nameof(Due) +)] +public partial struct ReducerJob +{ + [PrimaryKey, AutoInc] + public ulong Id; + public uint JobId; + public ScheduleAt Due; + public uint Payload; +} + +[Table( + Accessor = "ProcedureJob", + Name = "procedure_jobs", + Scheduled = nameof(ScheduledFunctions.ProcedureTick), + ScheduledAt = nameof(Due) +)] +public partial struct ProcedureJob +{ + [PrimaryKey, AutoInc] + public ulong Id; + public uint JobId; + public uint Payload; + public ScheduleAt Due; +} + +[Table(Accessor = "ScheduleResult", Public = true)] +public partial struct ScheduleResult +{ + [PrimaryKey] + public uint JobId; + public uint Payload; + public string Kind; + public uint Executions; + public ulong ScheduledId; +} + +public static partial class ScheduledFunctions +{ + private const uint PayloadBase = 1000; + + [Reducer] + public static void StartSchedules(ReducerContext ctx) + { + var due = new ScheduleAt.Time(ctx.Timestamp + new TimeDuration(100_000)); + ctx.Db.ReducerJob.Insert( + new ReducerJob + { + JobId = 1, + Due = due, + Payload = PayloadBase + 1, + } + ); + ctx.Db.ProcedureJob.Insert( + new ProcedureJob + { + JobId = 2, + Due = due, + Payload = PayloadBase + 2, + } + ); + VolatileNonatomicScheduleImmediateReducerTick( + new ReducerJob + { + JobId = 3, + Due = due, + Payload = PayloadBase + 3, + } + ); + VolatileNonatomicScheduleImmediateProcedureTick( + new ProcedureJob + { + JobId = 4, + Due = due, + Payload = PayloadBase + 4, + } + ); + ctx.Db.ReducerJob.Insert( + new ReducerJob + { + JobId = 5, + Due = new ScheduleAt.Interval(new TimeDuration(100_000)), + Payload = PayloadBase + 5, + } + ); + } + + [Reducer(Name = "run_reducer_job")] + public static void ReducerTick(ReducerContext ctx, ReducerJob job) + { + var previous = ctx.Db.ScheduleResult.JobId.Find(job.JobId); + var result = new ScheduleResult + { + JobId = job.JobId, + Payload = job.Payload, + Kind = "reducer", + Executions = (previous?.Executions ?? 0) + 1, + ScheduledId = job.Id, + }; + if (previous is null) + { + ctx.Db.ScheduleResult.Insert(result); + } + else + { + ctx.Db.ScheduleResult.JobId.Update(result); + } + } + + [Procedure(Name = "run_procedure_job")] + public static void ProcedureTick(ProcedureContext ctx, ProcedureJob job) + { + ctx.WithTx(tx => + { + var previous = tx.Db.ScheduleResult.JobId.Find(job.JobId); + var result = new ScheduleResult + { + JobId = job.JobId, + Payload = job.Payload, + Kind = "procedure", + Executions = (previous?.Executions ?? 0) + 1, + ScheduledId = job.Id, + }; + if (previous is null) + { + tx.Db.ScheduleResult.Insert(result); + } + else + { + tx.Db.ScheduleResult.JobId.Update(result); + } + + return 0; + }); + } + + [Reducer] + public static void CancelSchedules(ReducerContext ctx) + { + var repeat = ctx.Db.ScheduleResult.JobId.Find(5)!.Value; + if (repeat.Executions < 2) + { + throw new Exception("Repeating schedule has not run twice."); + } + + ctx.Db.ReducerJob.Id.Delete(repeat.ScheduledId); + ctx.Db.ScheduleResult.Insert( + new ScheduleResult + { + JobId = 6, + Payload = PayloadBase + 6, + Kind = "cancel", + Executions = repeat.Executions, + } + ); + // This later job provides a scheduler-driven observation point after cancellation. + ctx.Db.ReducerJob.Insert( + new ReducerJob + { + JobId = 7, + Due = new ScheduleAt.Time(ctx.Timestamp + new TimeDuration(500_000)), + Payload = PayloadBase + 7, + } + ); + } +} diff --git a/modules/namespace-test-cs/libraries/ExtraLib/ExtraLib.csproj b/modules/namespace-test-cs/libraries/ExtraLib/ExtraLib.csproj new file mode 100644 index 00000000000..5005d086a77 --- /dev/null +++ b/modules/namespace-test-cs/libraries/ExtraLib/ExtraLib.csproj @@ -0,0 +1,11 @@ + + + net10.0 + NamespaceExtraLib + $(AssemblyName) + + + + + + diff --git a/modules/namespace-test-cs/libraries/ExtraLib/Lib.cs b/modules/namespace-test-cs/libraries/ExtraLib/Lib.cs new file mode 100644 index 00000000000..d3688e339fe --- /dev/null +++ b/modules/namespace-test-cs/libraries/ExtraLib/Lib.cs @@ -0,0 +1,19 @@ +using SpacetimeDB; + +namespace ExtraLib; + +[Table(Public = true)] +public partial struct ExtraRow +{ + [PrimaryKey] + public uint Id; +} + +public static partial class Functions +{ + [Reducer] + public static void Extra(ReducerContext ctx) => ctx.Db.ExtraRow.Insert(new ExtraRow { Id = 7 }); + + [View(Accessor = "ExtraRows", Public = true)] + public static ExtraRow? Rows(ViewContext ctx) => ctx.Db.ExtraRow.Id.Find(7); +} diff --git a/modules/namespace-test-cs/namespace-test-cs.csproj b/modules/namespace-test-cs/namespace-test-cs.csproj new file mode 100644 index 00000000000..c662db79336 --- /dev/null +++ b/modules/namespace-test-cs/namespace-test-cs.csproj @@ -0,0 +1,13 @@ + + + net10.0 + + + + + + + + + + diff --git a/modules/root-selection-consumer-cs/Lib.cs b/modules/root-selection-consumer-cs/Lib.cs new file mode 100644 index 00000000000..3e29a1f2870 --- /dev/null +++ b/modules/root-selection-consumer-cs/Lib.cs @@ -0,0 +1,14 @@ +using SpacetimeDB; + +public static partial class Consumer +{ + [Reducer] + public static void ConsumerEntry(ReducerContext ctx) + { + if (Dependency.Answer() != 42) + { + throw new InvalidOperationException("Referenced assembly returned the wrong result."); + } + Log.Info("consumer published as root"); + } +} diff --git a/modules/root-selection-consumer-cs/root-selection-consumer-cs.csproj b/modules/root-selection-consumer-cs/root-selection-consumer-cs.csproj new file mode 100644 index 00000000000..49a4ed4decf --- /dev/null +++ b/modules/root-selection-consumer-cs/root-selection-consumer-cs.csproj @@ -0,0 +1,13 @@ + + + net10.0 + + + + + ../root-selection-dependency-cs/bin/$(Configuration)/net10.0/wasi-wasm/RootSelectionDependency.dll + + + + + diff --git a/modules/root-selection-dependency-cs/Lib.cs b/modules/root-selection-dependency-cs/Lib.cs new file mode 100644 index 00000000000..44eb90a995f --- /dev/null +++ b/modules/root-selection-dependency-cs/Lib.cs @@ -0,0 +1,14 @@ +using System.Runtime.CompilerServices; +using SpacetimeDB; + +public static partial class Dependency +{ + [MethodImpl(MethodImplOptions.NoInlining)] + public static int Answer() => 42; + + [Reducer] + public static void DependencyEntry(ReducerContext ctx) + { + Log.Info("dependency published as root"); + } +} diff --git a/modules/root-selection-dependency-cs/root-selection-dependency-cs.csproj b/modules/root-selection-dependency-cs/root-selection-dependency-cs.csproj new file mode 100644 index 00000000000..bacc83d4a65 --- /dev/null +++ b/modules/root-selection-dependency-cs/root-selection-dependency-cs.csproj @@ -0,0 +1,13 @@ + + + net10.0 + RootSelectionDependency + + $(AssemblyName) + $(MSBuildProjectDirectory)/bin/$(Configuration)/net10.0/wasi-wasm/native/StdbModule.wasm + + + + + + diff --git a/sdks/csharp/DEVELOP.md b/sdks/csharp/DEVELOP.md index 2ffd13c1476..71a27a4e530 100644 --- a/sdks/csharp/DEVELOP.md +++ b/sdks/csharp/DEVELOP.md @@ -48,6 +48,23 @@ When SDK code needs to refer to generated types, we have two options: The most important generated types are `RemoteTables` -- also known as the **client cache** -- and `RemoteReducers`. `RemoteTables` stores the local view of subscribed data from the database. For a `DbConnection conn`, `conn.Db` is an instance of `RemoteTables`. `RemoteReducers` allows calling reducers on the server, and is accessible at `conn.Reducers`. Types are also generated for all server-side types referred to by tables or modules. +### Namespace bindings + +Suppose a dependency is mounted with `Accessor = "MyAuth", Name = "auth_data"`. +Generated C# clients expose its tables through +`conn.Db.MyAuth`, reducers through `conn.Reducers.MyAuth`, procedures through +`conn.Procedures.MyAuth`, and query factories through `q.From.MyAuth`. +Generated SQL and network messages use the database namespace `auth_data`. +The C# accessor remains `MyAuth`. When `Name` is omitted, the host derives the +database namespace from the accessor using the root module's case policy. + +The `--namespace` option of `spacetime generate` controls where generated C# +classes are declared; it does not name or rename database namespaces. With +`--namespace Game.Bindings`, a root `User` row becomes `Game.Bindings.User`, +while a `User` row in that dependency becomes +`Game.Bindings.MyAuth.User`. Their table handles remain `conn.Db.User` and +`conn.Db.MyAuth.User`, respectively. + ### Runtime Structure Most of the core logic of the SDK lives in [`DbConnectionBase<...>`](./src/SpacetimeDBClient.cs). This handles: @@ -99,4 +116,3 @@ We could deduplicate multiply-subscribed rows server-side, but this represents a There is also a class `MultiDictionaryDelta`. This represents a pre-processed batch of changes to a `MultiDictionary`. We prepare `MultiDictionaryDelta`s on a background thread and `Apply` them on the main thread. This allows us to do at least some work without blocking the main thread. Note that if multiple subscriptions are subscribed to a row, when a server-side transaction updates that row, exactly the right number of updates will be sent over the network, in a single `ServerMessage`. `MultiDictionary` and `MultiDictionaryDelta` rely on this guarantee for correct operation, and will throw exceptions in debug mode if it is not met. - diff --git a/sdks/csharp/examples~/regression-tests/client/module_bindings/SpacetimeDBClient.g.cs b/sdks/csharp/examples~/regression-tests/client/module_bindings/SpacetimeDBClient.g.cs index f17f888e1c8..b6f5cd73dfa 100644 --- a/sdks/csharp/examples~/regression-tests/client/module_bindings/SpacetimeDBClient.g.cs +++ b/sdks/csharp/examples~/regression-tests/client/module_bindings/SpacetimeDBClient.g.cs @@ -1,7 +1,7 @@ // 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.4.1 (commit ed95086da83809e1e621aae0066b0970a4130a3e). +// This was generated using spacetimedb cli version 2.10.1 (commit 7109fe86a665ba5404389ce72ffc63131bf576cc). #nullable enable diff --git a/sdks/csharp/examples~/regression-tests/namespaces/Program.cs b/sdks/csharp/examples~/regression-tests/namespaces/Program.cs new file mode 100644 index 00000000000..a3ea26bee9f --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/Program.cs @@ -0,0 +1,566 @@ +using System; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using SpacetimeDB; +using SpacetimeDB.Types; + +internal static class Program +{ + private static void Require(bool condition, string message) + { + if (!condition) + { + throw new Exception(message); + } + } + + private static void Main() + { + var host = + Environment.GetEnvironmentVariable("SPACETIMEDB_SERVER_URL") ?? "http://localhost:3000"; + if (host == "local") + { + host = "http://localhost:3000"; + } + + var connected = false; + Exception? connectionError = null; + var conn = DbConnection + .Builder() + .WithUri(host) + .WithDatabaseName("namespace-tests") + .OnConnect((_, _, _) => connected = true) + .OnConnectError(error => connectionError = error) + .OnDisconnect( + (_, error) => connectionError = error ?? new Exception("Unexpected disconnect") + ) + .Build(); + + void Wait(Func done, string phase) + { + var timer = Stopwatch.StartNew(); + while (!done()) + { + if (connectionError != null) + { + throw connectionError; + } + + if (timer.Elapsed > TimeSpan.FromSeconds(30)) + { + throw new TimeoutException(phase); + } + + conn.FrameTick(); + Thread.Sleep(5); + } + if (connectionError != null) + { + throw connectionError; + } + } + + void Unsubscribe(SubscriptionHandle handle) + { + var done = false; + handle.UnsubscribeThen(_ => done = true); + Wait(() => done, "unsubscribe"); + } + + void EmptyCache() + { + Require( + conn.Db.User.Count == 0 + && conn.Db.MyAuth.User.Count == 0 + && conn.Db.@class.User.Count == 0 + && conn.Db.MyAuth.ScheduleResult.Count == 0 + && conn.Db.@class.ScheduleResult.Count == 0 + && conn.Db.ExtraRow.Count == 0, + "Unsubscribe must clear every namespace's table cache" + ); + Require( + conn.Db.Users.Count == 0 + && conn.Db.MyAuth.Users.Count == 0 + && conn.Db.MyAuth.QueryUsers.Count == 0 + && conn.Db.MyAuth.AnonymousUsers.Count == 0 + && conn.Db.AuthUsers.Count == 0 + && conn.Db.QueryUsers.Count == 0 + && conn.Db.QueryUsersRight.Count == 0 + && conn.Db.QueryExtra.Count == 0, + "Unsubscribe must clear view caches" + ); + } + + try + { + Wait(() => connected, "connect"); + Require( + conn.Db.MyAuth.User.RemoteTableName == "auth_data.auth_users", + "Explicit table wire name" + ); + Require( + new QueryBuilder().From.MyAuth.User().ToSql() + == "SELECT * FROM \"auth_data\".\"auth_users\"", + "Accessor query must use the canonical namespace and table name" + ); + Require( + conn.Db.@class.User.RemoteTableName == "class.user", + "Keyword namespace wire name" + ); + Require( + !QueryBuilder.AllTablesSqlQueries().Any(sql => sql.Contains("secret")), + "Subscribe-all must omit private child tables" + ); + + var applied = false; + var subscription = conn.SubscriptionBuilder() + .OnApplied(_ => applied = true) + .OnError((_, error) => throw error) + .AddQuery(q => q.From.User()) + .AddQuery(q => q.From.MyAuth.User()) + .AddQuery(q => q.From.@class.User()) + .AddQuery(q => q.From.ExtraRow()) + .AddQuery(q => q.From.Users()) + .AddQuery(q => q.From.MyAuth.Users()) + .AddQuery(q => q.From.MyAuth.AnonymousUsers()) + .AddQuery(q => q.From.MyAuth.QueryUsers()) + .AddQuery(q => q.From.MyAuth.Notice()) + .Subscribe(); + Wait(() => applied, "typed subscription"); + EmptyCache(); + + conn.Reducers.Extra(); + Wait( + () => conn.Db.ExtraRow.Count == 1, + "dependency automatically registered in public" + ); + var exerciseDone = false; + var atomicInsert = false; + conn.Db.User.OnInsert += (ctx, row) => + { + if (row.Id != 2) + { + return; + } + + Require( + ctx.Db.MyAuth.User.Id.Find(2)?.Score == 99 + && ctx.Db.@class.User.Id.Find(4)?.Message == "consumer", + "Root callback must see the complete cross-namespace transaction" + ); + atomicInsert = true; + }; + conn.Reducers.OnExercise += (ctx) => + { + Require(ctx.Event.Status is Status.Committed, "Exercise failed"); + exerciseDone = true; + }; + conn.Reducers.Exercise(); + Wait( + () => + exerciseDone + && atomicInsert + && conn.Db.MyAuth.Users.Count == 1 + && conn.Db.MyAuth.AnonymousUsers.Count == 1 + && conn.Db.MyAuth.QueryUsers.Count == 1, + "cross-library helper writes and views" + ); + Require( + conn.Db.User.Count == 1 + && conn.Db.MyAuth.User.Count == 1 + && conn.Db.@class.User.Count == 1, + "Same-named table caches must be independent" + ); + + var joinApplied = false; + var joins = conn.SubscriptionBuilder() + .OnApplied(_ => joinApplied = true) + .OnError((_, error) => throw error) + .AddQuery(q => + q.From.User().LeftSemijoin(q.From.MyAuth.User(), (r, a) => r.Id.Eq(a.Id)) + ) + .AddQuery(q => + q.From.User().RightSemijoin(q.From.MyAuth.User(), (r, a) => r.Id.Eq(a.Id)) + ) + .AddQuery(q => q.From.MyAuth.User().Where(c => c.Score.Eq(99u))) + .Subscribe(); + Wait(() => joinApplied, "cross-namespace semijoins and filter"); + Require( + conn.Db.User.Count == 1 && conn.Db.MyAuth.User.Count == 1, + "Overlapping queries duplicate rows" + ); + Unsubscribe(joins); + Require( + conn.Db.User.Count == 1 && conn.Db.MyAuth.User.Count == 1, + "Overlapping unsubscribe removed live rows" + ); + + var authAdded = false; + var auditAdded = false; + var notices = 0; + conn.Db.MyAuth.Notice.OnInsert += (_, row) => + { + Require(row.Id == 10, "Event routed to wrong namespace"); + notices++; + }; + conn.Reducers.MyAuth.OnAdd += (ctx, id) => + { + Require(ctx.Event.Status is Status.Committed && id == 10, "Auth reducer result"); + Require(ctx.Db.MyAuth.User.Id.Find(id)?.Score == 42, "Auth reducer callback cache"); + authAdded = true; + }; + conn.Reducers.@class.OnAdd += (ctx, id) => + { + Require(ctx.Event.Status is Status.Committed && id == 10, "Audit reducer result"); + Require( + ctx.Db.@class.User.Id.Find(id)?.Message == "audit", + "Audit reducer callback cache" + ); + auditAdded = true; + }; + conn.Reducers.MyAuth.Add(10); + conn.Reducers.@class.Add(10); + Wait( + () => authAdded && auditAdded && notices == 1, + "same-named reducers and event table" + ); + Require( + conn.Db.User.Count == 1 + && conn.Db.MyAuth.User.Count == 2 + && conn.Db.@class.User.Count == 2, + "Namespaced reducers changed the wrong table" + ); + + var procedures = 0; + conn.Procedures.CountUsers( + (_, result) => + { + Require(result.IsSuccess && result.Value == 5, "Root procedure"); + procedures++; + } + ); + conn.Procedures.MyAuth.CountUsers( + (_, result) => + { + Require(result.IsSuccess && result.Value == 2, "Auth procedure"); + procedures++; + } + ); + conn.Procedures.@class.CountUsers( + (_, result) => + { + Require(result.IsSuccess && result.Value == 2, "Audit procedure"); + procedures++; + } + ); + conn.Procedures.MyAuth.ReadScore( + 10, + (_, result) => + { + Require(result.IsSuccess && result.Value == 42, "Procedure return value"); + procedures++; + } + ); + conn.Procedures.MyAuth.ReadScore( + 999, + (_, result) => + { + Require( + !result.IsSuccess && result.Error != null, + "Procedure failure callback" + ); + procedures++; + } + ); + Wait(() => procedures == 5, "namespaced procedure callbacks"); + + var updated = false; + conn.Db.MyAuth.User.OnUpdate += (ctx, before, after) => + { + Require( + before.Id == 10 && before.Score == 42 && after.Score == 77, + "Update callback values" + ); + Require( + ctx.Db.MyAuth.User.ByScore.Filter(77u).Single().Id == 10, + "Updated index cache" + ); + updated = true; + }; + conn.Reducers.MyAuth.Update(10, 77); + Wait(() => updated, "namespaced update"); + var remote = conn.Db.MyAuth.User.RemoteQuery("WHERE id = 10"); + Wait(() => remote.IsCompleted, "namespaced RemoteQuery"); + Require( + remote.GetAwaiter().GetResult().Single().Score == 77, + "RemoteQuery result decoding" + ); + var privateDenied = false; + conn.SubscriptionBuilder() + .OnApplied(_ => throw new Exception("A non-owner subscribed to private child data")) + .OnError((_, _) => privateDenied = true) + .Subscribe(new[] { "SELECT * FROM \"auth_data\".secret" }); + Wait(() => privateDenied, "private child subscription rejection"); + + var failed = false; + conn.OnUnhandledReducerError += (_, error) => + { + Require(error.Message.Contains("namespace rollback"), "Unexpected reducer failure"); + failed = true; + }; + conn.Reducers.MyAuth.Fail(999); + Wait(() => failed, "child error forwarded to root"); + var rolledBack = conn.Db.MyAuth.User.RemoteQuery("WHERE id = 999"); + Wait(() => rolledBack.IsCompleted, "rollback verification"); + Require( + rolledBack.GetAwaiter().GetResult().Length == 0, + "Failed reducer committed a row" + ); + + var deleted = false; + conn.Db.MyAuth.User.OnDelete += (ctx, row) => + { + if (row.Id != 10) + { + return; + } + + Require( + ctx.Db.MyAuth.User.Id.Find(10) == null + && ctx.Db.@class.User.Id.Find(10) != null, + "Deletion crossed namespace boundaries" + ); + deleted = true; + }; + conn.Reducers.MyAuth.Remove(10); + Wait(() => deleted, "namespaced deletion"); + Unsubscribe(subscription); + EmptyCache(); + var uncached = conn.Db.MyAuth.User.RemoteQuery(""); + Wait(() => uncached.IsCompleted, "unsubscribed RemoteQuery"); + Require( + uncached.GetAwaiter().GetResult().Single().Id == 2, + "Unsubscribed RemoteQuery result" + ); + EmptyCache(); + + var allApplied = false; + var all = conn.SubscriptionBuilder() + .OnApplied(_ => allApplied = true) + .OnError((_, error) => throw error) + .SubscribeToAllTables(); + Wait(() => allApplied, "subscribe-all initial rows"); + Require( + conn.Db.User.Count == 1 + && conn.Db.MyAuth.User.Count == 1 + && conn.Db.@class.User.Count == 2 + && conn.Db.ExtraRow.Count == 1 + && conn.Db.Users.Count == 1 + && conn.Db.MyAuth.Users.Count == 1 + && conn.Db.MyAuth.AnonymousUsers.Count == 1 + && conn.Db.MyAuth.QueryUsers.Count == 1 + && conn.Db.AuthUsers.Count == 1 + && conn.Db.QueryUsers.Count == 1 + && conn.Db.QueryUsersRight.Count == 1 + && conn.Db.QueryExtra.Count == 1, + "Subscribe-all omitted child tables or views" + ); + Require(notices == 1, "Event rows must not be replayed as persistent rows"); + + foreach (var reducers in new object[] { conn.Reducers.MyAuth, conn.Reducers.@class }) + { + Require( + reducers.GetType().GetMethod("ReducerTick") == null + && reducers.GetType().GetMethod("RunReducerJob") == null, + "Scheduled reducers must not have client call methods" + ); + } + foreach ( + var procedureCalls in new object[] + { + conn.Procedures.MyAuth, + conn.Procedures.@class, + } + ) + { + Require( + procedureCalls.GetType().GetMethod("ProcedureTick") == null + && procedureCalls.GetType().GetMethod("RunProcedureJob") == null, + "Scheduled procedures must not have client call methods" + ); + } + + conn.Reducers.MyAuth.StartSchedules(); + Wait( + () => + conn.Db.MyAuth.ScheduleResult.Count == 5 + && conn.Db.MyAuth.ScheduleResult.JobId.Find(5)?.Executions >= 2, + "Auth one-shot, immediate, and repeating schedules" + ); + Require( + conn.Db.@class.ScheduleResult.Count == 0, + "Auth schedules must not execute Audit functions or write Audit tables" + ); + conn.Reducers.@class.StartSchedules(); + Wait( + () => + conn.Db.@class.ScheduleResult.Count == 5 + && conn.Db.@class.ScheduleResult.JobId.Find(5)?.Executions >= 2, + "Audit one-shot, immediate, and repeating schedules" + ); + conn.Reducers.MyAuth.CancelSchedules(); + conn.Reducers.@class.CancelSchedules(); + Wait( + () => + conn.Db.MyAuth.ScheduleResult.JobId.Find(7) != null + && conn.Db.@class.ScheduleResult.JobId.Find(7) != null, + "Post-cancellation scheduled jobs" + ); + + void CheckSchedules( + (uint JobId, uint Payload, string Kind, uint Executions, ulong ScheduledId)[] rows, + uint payloadBase + ) + { + Require( + rows.Length == 7, + "Each namespace must have exactly seven schedule results" + ); + foreach (var row in rows) + { + Require(row.Payload == payloadBase + row.JobId, "Scheduled argument payload"); + var kind = + row.JobId == 6 ? "cancel" + : row.JobId == 2 || row.JobId == 4 ? "procedure" + : "reducer"; + Require(row.Kind == kind, "Scheduled function dispatch category"); + Require( + row.JobId == 5 || row.JobId == 6 + ? row.Executions >= 2 + : row.Executions == 1, + "One-shot jobs must run once; repeating jobs must run at least twice" + ); + Require( + row.JobId == 3 || row.JobId == 4 || row.JobId == 6 + ? row.ScheduledId == 0 + : row.ScheduledId > 0, + "Table-backed schedules must receive their generated primary key" + ); + } + Require( + rows.Single(row => row.JobId == 5).Executions + == rows.Single(row => row.JobId == 6).Executions, + "Deleting a repeating schedule must stop further executions" + ); + } + CheckSchedules( + conn.Db.MyAuth.ScheduleResult.Iter() + .Select(row => + (row.JobId, row.Payload, row.Kind, row.Executions, row.ScheduledId) + ) + .ToArray(), + 1000 + ); + CheckSchedules( + conn.Db.@class.ScheduleResult.Iter() + .Select(row => + (row.JobId, row.Payload, row.Kind, row.Executions, row.ScheduledId) + ) + .ToArray(), + 2000 + ); + Require( + conn.Db.User.Count == 1 + && conn.Db.MyAuth.User.Count == 1 + && conn.Db.@class.User.Count == 2, + "Schedules must leave unrelated tables unchanged" + ); + + var transactionInserts = 0; + void CheckTransactionInsert(EventContext ctx, uint id) + { + if (id < 20) + { + return; + } + + Require(id == 20, "A rolled-back procedure emitted an insert"); + Require( + ctx.Db.User.Id.Find(id) != null + && ctx.Db.MyAuth.User.Id.Find(id)?.Score == 42 + && ctx.Db.@class.User.Id.Find(id)?.Message == "procedure", + "Every insert callback must see the whole procedure transaction" + ); + transactionInserts++; + } + conn.Db.User.OnInsert += (ctx, row) => CheckTransactionInsert(ctx, row.Id); + conn.Db.MyAuth.User.OnInsert += (ctx, row) => CheckTransactionInsert(ctx, row.Id); + conn.Db.@class.User.OnInsert += (ctx, row) => CheckTransactionInsert(ctx, row.Id); + + var transactionCommitted = false; + conn.Procedures.WriteAcrossNamespaces( + 20, + false, + (_, result) => + { + Require(result.IsSuccess && result.Value == 42, "Procedure transaction commit"); + transactionCommitted = true; + } + ); + Wait( + () => transactionCommitted && transactionInserts == 3, + "Committed cross-namespace procedure transaction" + ); + var transactionFailed = false; + conn.Procedures.WriteAcrossNamespaces( + 21, + true, + (_, result) => + { + Require( + !result.IsSuccess && result.Error != null, + "Procedure transaction must report failure" + ); + transactionFailed = true; + } + ); + Wait(() => transactionFailed, "Failed cross-namespace procedure transaction"); + + // Query the host as well as the cache: no subscription update alone does not prove rollback. + var rootWrites = conn.Db.User.RemoteQuery("WHERE id >= 20"); + var authWrites = conn.Db.MyAuth.User.RemoteQuery("WHERE id >= 20"); + var auditWrites = conn.Db.@class.User.RemoteQuery("WHERE id >= 20"); + Wait( + () => rootWrites.IsCompleted && authWrites.IsCompleted && auditWrites.IsCompleted, + "Procedure transaction persistence" + ); + Require(rootWrites.GetAwaiter().GetResult().Single().Id == 20, "Root write rollback"); + var authWrite = authWrites.GetAwaiter().GetResult().Single(); + var auditWrite = auditWrites.GetAwaiter().GetResult().Single(); + Require(authWrite.Id == 20 && authWrite.Score == 42, "Auth write rollback"); + Require( + auditWrite.Id == 20 && auditWrite.Message == "procedure", + "Audit write rollback" + ); + Require( + transactionInserts == 3 + && conn.Db.User.Count == 2 + && conn.Db.MyAuth.User.Count == 2 + && conn.Db.@class.User.Count == 3 + && conn.Db.User.Id.Find(21) == null + && conn.Db.MyAuth.User.Id.Find(21) == null + && conn.Db.@class.User.Id.Find(21) == null, + "Failed procedure must leave all three subscription caches unchanged" + ); + Unsubscribe(all); + EmptyCache(); + RootRlsTests.Run(host); + Console.WriteLine("Namespace integration passed"); + } + finally + { + conn.Disconnect(); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/README.md b/sdks/csharp/examples~/regression-tests/namespaces/README.md new file mode 100644 index 00000000000..682bb271d2c --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/README.md @@ -0,0 +1,58 @@ +# Namespace Integration Test + +Runs generated clients against the .NET 10 module in `modules/namespace-test-cs`. +The .NET 8 run verifies backward compatibility; +the .NET 10 run verifies the newer client runtime. +Both retain C# 9 to enforce the generated-code language baseline. +The Auth dependency uses `Accessor = "MyAuth"` and `Name = "auth_data"`: +C# expressions use `MyAuth`, while generated SQL and wire names use `auth_data`. + +The existing `sdks/csharp/tools~/run-regression-tests.sh 10` harness generates the +bindings and runs this client on both frameworks, clearing and republishing the +`namespace-tests` database before each run. +The namespace scenario is skipped in the .NET 8 **module** pass. CI already runs +both harness passes. + +For a focused run, from the repository root, with a local server running and local +C# packages configured as described in `sdks/csharp/DEVELOP.md`: + +```sh +cargo spacetime generate -y -l csharp -o sdks/csharp/examples~/regression-tests/namespaces/module_bindings --module-path modules/namespace-test-cs --build-options="--dotnet-version 10" +for framework in net8.0 net10.0; do + cargo spacetime publish --dotnet-version 10 -c -y --server local -p modules/namespace-test-cs namespace-tests + dotnet run --framework "$framework" --project sdks/csharp/examples~/regression-tests/namespaces/client.csproj +done +``` + +The publish command deletes existing data in the test database. Republish before +each client run. For a nondefault server, pass its URL to publish and set +`SPACETIMEDB_SERVER_URL` to that same URL for the client. + +Coverage: + +- Root and two mounted libraries with different row types named `User`, plus a + dependency automatically registered in `public`, without a namespace declaration. +- Distinct namespace accessor and canonical name, explicit table names, and a C# + keyword namespace accessor. +- Typed subscriptions, filtered queries, both semijoin directions, and overlapping + subscriptions without duplicate rows or premature cache removal. +- Cross-library helper writes and callbacks observing the complete transaction. +- A procedure transaction writing root and both namespace tables, including a + library-local transaction helper. Checks commit, rollback after an exception, + atomic subscription callbacks, and persisted results through one-off queries. +- Same-named reducers/procedures in different namespaces, procedure success/error + callbacks, and child reducer failures forwarded to the root connection. +- Insert/update/delete callbacks, unique/B-tree indexes, and reducer rollback. +- Event rows, private-table access rejection, procedural/anonymous/query views. +- Root-defined RLS on a public namespaced table: two distinct non-owner clients, + typed/raw subscriptions, initial rows, live inserts/updates, ownership transfer, + filtered one-off queries, and unsubscribe cleanup. No library-defined RLS rules. +- `RemoteQuery` result decoding and no subscription-cache population by one-off queries. +- Subscribe-all initial rows, no replay of past events, and unsubscribe cache cleanup. +- Same-named scheduled reducers/procedures in both namespaces, with explicit function + and table names and custom scheduled-at columns. Covers one-shot and immediate + execution, repeating reducer cancellation, argument payloads, generated keys, + namespace isolation, and absence of scheduled functions from client call APIs. + +Environment access and namespace isolation are covered separately by +`namespace_csharp_environment_security` in `crates/testing/tests/environment.rs`. diff --git a/sdks/csharp/examples~/regression-tests/namespaces/RootRlsTests.cs b/sdks/csharp/examples~/regression-tests/namespaces/RootRlsTests.cs new file mode 100644 index 00000000000..a4b34762546 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/RootRlsTests.cs @@ -0,0 +1,192 @@ +using System; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using SpacetimeDB; +using SpacetimeDB.Types; + +internal static class RootRlsTests +{ + private static void Require(bool condition, string message) + { + if (!condition) + { + throw new Exception(message); + } + } + + public static void Run(string host) + { + Identity? firstIdentity = null; + Identity? secondIdentity = null; + Exception? error = null; + var first = DbConnection + .Builder() + .WithUri(host) + .WithDatabaseName("namespace-tests") + .OnConnect((_, identity, _) => firstIdentity = identity) + .OnConnectError(e => error = e) + .Build(); + var second = DbConnection + .Builder() + .WithUri(host) + .WithDatabaseName("namespace-tests") + .OnConnect((_, identity, _) => secondIdentity = identity) + .OnConnectError(e => error = e) + .Build(); + + void Wait(Func done, string phase) + { + var timer = Stopwatch.StartNew(); + while (!done()) + { + if (error != null) + { + throw error; + } + + if (timer.Elapsed > TimeSpan.FromSeconds(30)) + { + throw new TimeoutException("Root RLS: " + phase); + } + + first.FrameTick(); + second.FrameTick(); + Thread.Sleep(5); + } + if (error != null) + { + throw error; + } + } + + try + { + Wait(() => firstIdentity != null && secondIdentity != null, "connect"); + var firstOwner = firstIdentity ?? throw new Exception("Missing first identity"); + var secondOwner = secondIdentity ?? throw new Exception("Missing second identity"); + Require(!firstOwner.Equals(secondOwner), "RLS clients must have distinct identities"); + var writes = 0; + first.Reducers.OnWriteProtectedRow += (ctx, _, _, _) => + { + Require(ctx.Event.Status is Status.Committed, "RLS fixture write failed"); + writes++; + }; + void Write(uint id, Identity owner, uint value) + { + var expected = writes + 1; + first.Reducers.WriteProtectedRow(id, owner, value); + Wait(() => writes == expected, "write"); + } + + Write(1, firstOwner, 10); + Write(2, secondOwner, 20); + + var inserts = new int[2]; + var updates = new int[2]; + var deletes = new int[2]; + var clients = new[] { first, second }; + var identities = new[] { firstOwner, secondOwner }; + for (var i = 0; i < clients.Length; i++) + { + var index = i; + clients[i].Db.MyAuth.ProtectedRow.OnInsert += (_, row) => + { + Require(row.Owner.Equals(identities[index]), "RLS leaked an insert"); + inserts[index]++; + }; + clients[i].Db.MyAuth.ProtectedRow.OnUpdate += (_, before, after) => + { + Require( + before.Owner.Equals(identities[index]) + && after.Owner.Equals(identities[index]), + "RLS leaked an update" + ); + updates[index]++; + }; + clients[i].Db.MyAuth.ProtectedRow.OnDelete += (_, row) => + { + Require(row.Owner.Equals(identities[index]), "RLS leaked a deletion"); + deletes[index]++; + }; + } + + var applied = 0; + var firstSub = first + .SubscriptionBuilder() + .OnApplied(_ => applied++) + .OnError((_, e) => error = e) + .AddQuery(q => q.From.MyAuth.ProtectedRow()) + .Subscribe(); + var secondSub = second + .SubscriptionBuilder() + .OnApplied(_ => applied++) + .OnError((_, e) => error = e) + .Subscribe(new[] { "SELECT * FROM \"auth_data\".protected_row" }); + Wait(() => applied == 2, "initial subscriptions"); + Require(first.Db.MyAuth.ProtectedRow.Iter().Single().Id == 1, "First initial RLS rows"); + Require( + second.Db.MyAuth.ProtectedRow.Iter().Single().Id == 2, + "Second initial RLS rows" + ); + + Write(1, firstOwner, 11); + Write(2, secondOwner, 21); + Wait(() => updates[0] == 1 && updates[1] == 1, "visible updates"); + Require( + first.Db.MyAuth.ProtectedRow.Iter().Single().Value == 11, + "First updated value" + ); + Require( + second.Db.MyAuth.ProtectedRow.Iter().Single().Value == 21, + "Second updated value" + ); + + // Changing ownership must remove the old owner's row and insert it for the new owner. + Write(1, secondOwner, 12); + Wait(() => deletes[0] == 1 && inserts[1] == 2, "ownership transfer"); + Require(first.Db.MyAuth.ProtectedRow.Count == 0, "Old owner retained the row"); + Require(second.Db.MyAuth.ProtectedRow.Count == 2, "New owner did not receive the row"); + Write(3, firstOwner, 30); + Wait(() => inserts[0] == 2, "live insert"); + + var firstQuery = first.Db.MyAuth.ProtectedRow.RemoteQuery(""); + var secondQuery = second.Db.MyAuth.ProtectedRow.RemoteQuery(""); + Wait(() => firstQuery.IsCompleted && secondQuery.IsCompleted, "filtered RemoteQuery"); + Require(firstQuery.GetAwaiter().GetResult().Single().Id == 3, "First RemoteQuery RLS"); + Require( + secondQuery + .GetAwaiter() + .GetResult() + .Select(row => row.Id) + .OrderBy(id => id) + .SequenceEqual(new uint[] { 1, 2 }), + "Second RemoteQuery RLS" + ); + Require( + inserts[0] == 2 + && inserts[1] == 2 + && updates[0] == 1 + && updates[1] == 1 + && deletes[0] == 1 + && deletes[1] == 0, + "Hidden changes must not produce callbacks" + ); + + var unsubscribed = 0; + firstSub.UnsubscribeThen(_ => unsubscribed++); + secondSub.UnsubscribeThen(_ => unsubscribed++); + Wait(() => unsubscribed == 2, "unsubscribe"); + Require( + first.Db.MyAuth.ProtectedRow.Count == 0 && second.Db.MyAuth.ProtectedRow.Count == 0, + "RLS unsubscribe must clear both caches" + ); + Console.WriteLine("Root-defined RLS on a namespace table passed"); + } + finally + { + first.Disconnect(); + second.Disconnect(); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/client.csproj b/sdks/csharp/examples~/regression-tests/namespaces/client.csproj new file mode 100644 index 00000000000..719f2fd86d2 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/client.csproj @@ -0,0 +1,13 @@ + + + Exe + net8.0;net10.0 + 9 + enable + disable + true + + + + + diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Namespace.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Namespace.g.cs new file mode 100644 index 00000000000..96e74b016ae --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Namespace.g.cs @@ -0,0 +1,54 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteReducers : RemoteBase + { + internal RemoteReducers(global::SpacetimeDB.Types.DbConnection conn) : base(conn) { } + internal event Action? InternalOnUnhandledReducerError; + } + + public sealed partial class RemoteProcedures : RemoteBase + { + internal RemoteProcedures(global::SpacetimeDB.Types.DbConnection conn) : base(conn) { } + } + + public sealed partial class RemoteTables + { + internal RemoteTables(global::SpacetimeDB.Types.DbConnection conn, Action register) + { + register(AnonymousUsers = new(conn)); + register(Notice = new(conn)); + register(ProtectedRow = new(conn)); + register(QueryUsers = new(conn)); + register(ScheduleResult = new(conn)); + register(User = new(conn)); + register(Users = new(conn)); + } + } + public sealed class From + { + public global::SpacetimeDB.Table AnonymousUsers() => new(RemoteTables.AnonymousUsersHandle.SqlName, new AnonymousUsersCols(RemoteTables.AnonymousUsersHandle.SqlName), new AnonymousUsersIxCols(RemoteTables.AnonymousUsersHandle.SqlName)); + public global::SpacetimeDB.Table Notice() => new(RemoteTables.NoticeHandle.SqlName, new NoticeCols(RemoteTables.NoticeHandle.SqlName), new NoticeIxCols(RemoteTables.NoticeHandle.SqlName)); + public global::SpacetimeDB.Table ProtectedRow() => new(RemoteTables.ProtectedRowHandle.SqlName, new ProtectedRowCols(RemoteTables.ProtectedRowHandle.SqlName), new ProtectedRowIxCols(RemoteTables.ProtectedRowHandle.SqlName)); + public global::SpacetimeDB.Table QueryUsers() => new(RemoteTables.QueryUsersHandle.SqlName, new QueryUsersCols(RemoteTables.QueryUsersHandle.SqlName), new QueryUsersIxCols(RemoteTables.QueryUsersHandle.SqlName)); + public global::SpacetimeDB.Table ScheduleResult() => new(RemoteTables.ScheduleResultHandle.SqlName, new ScheduleResultCols(RemoteTables.ScheduleResultHandle.SqlName), new ScheduleResultIxCols(RemoteTables.ScheduleResultHandle.SqlName)); + public global::SpacetimeDB.Table User() => new(RemoteTables.UserHandle.SqlName, new UserCols(RemoteTables.UserHandle.SqlName), new UserIxCols(RemoteTables.UserHandle.SqlName)); + public global::SpacetimeDB.Table Users() => new(RemoteTables.UsersHandle.SqlName, new UsersCols(RemoteTables.UsersHandle.SqlName), new UsersIxCols(RemoteTables.UsersHandle.SqlName)); + } + + public abstract partial class Reducer + { + private Reducer() { } + } + public abstract partial class Procedure + { + private Procedure() { } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Procedures/CountUsers.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Procedures/CountUsers.g.cs new file mode 100644 index 00000000000..e3ada1d67ef --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Procedures/CountUsers.g.cs @@ -0,0 +1,64 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteProcedures : RemoteBase + { + public void CountUsers(ProcedureCallback callback) + { + // Convert the clean callback to the wrapper callback + InternalCountUsers((ctx, result) => + { + if (result.IsSuccess && result.Value != null) + { + callback(ctx, ProcedureCallbackResult.Success(result.Value.Value)); + } + else + { + callback(ctx, ProcedureCallbackResult.Failure(result.Error!)); + } + }); + } + + private void InternalCountUsers(ProcedureCallback callback) + { + conn.InternalCallProcedure(new Procedure.CountUsersArgs(), callback); + } + + } + + public abstract partial class Procedure + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class CountUsers + { + [DataMember(Name = "Value")] + public ulong Value; + + public CountUsers(ulong Value) + { + this.Value = Value; + } + + public CountUsers() + { + } + } + [SpacetimeDB.Type] + [DataContract] + public sealed partial class CountUsersArgs : Procedure, IProcedureArgs + { + string IProcedureArgs.ProcedureName => "auth_data.count_users"; + } + + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Procedures/ReadScore.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Procedures/ReadScore.g.cs new file mode 100644 index 00000000000..aebc61b06a1 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Procedures/ReadScore.g.cs @@ -0,0 +1,76 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteProcedures : RemoteBase + { + public void ReadScore(uint id, ProcedureCallback callback) + { + // Convert the clean callback to the wrapper callback + InternalReadScore(id, (ctx, result) => + { + if (result.IsSuccess && result.Value != null) + { + callback(ctx, ProcedureCallbackResult.Success(result.Value.Value)); + } + else + { + callback(ctx, ProcedureCallbackResult.Failure(result.Error!)); + } + }); + } + + private void InternalReadScore(uint id, ProcedureCallback callback) + { + conn.InternalCallProcedure(new Procedure.ReadScoreArgs(id), callback); + } + + } + + public abstract partial class Procedure + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ReadScore + { + [DataMember(Name = "Value")] + public uint Value; + + public ReadScore(uint Value) + { + this.Value = Value; + } + + public ReadScore() + { + } + } + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ReadScoreArgs : Procedure, IProcedureArgs + { + [DataMember(Name = "id")] + public uint Id; + + public ReadScoreArgs(uint Id) + { + this.Id = Id; + } + + public ReadScoreArgs() + { + } + + string IProcedureArgs.ProcedureName => "auth_data.read_score"; + } + + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Add.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Add.g.cs new file mode 100644 index 00000000000..5293f88722c --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Add.g.cs @@ -0,0 +1,66 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void AddHandler(global::SpacetimeDB.Types.ReducerEventContext ctx, uint id); + public event AddHandler? OnAdd; + + public void Add(uint id) + { + conn.InternalCallReducer(new Reducer.Add(id)); + } + + public bool InvokeAdd(global::SpacetimeDB.Types.ReducerEventContext ctx, Reducer.Add args) + { + if (OnAdd == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnAdd( + ctx, + args.Id + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Add : global::SpacetimeDB.Types.Reducer, IReducerArgs + { + [DataMember(Name = "id")] + public uint Id; + + public Add(uint Id) + { + this.Id = Id; + } + + public Add() + { + } + + string IReducerArgs.ReducerName => "auth_data.add"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/CancelSchedules.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/CancelSchedules.g.cs new file mode 100644 index 00000000000..f822ebdef81 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/CancelSchedules.g.cs @@ -0,0 +1,53 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void CancelSchedulesHandler(global::SpacetimeDB.Types.ReducerEventContext ctx); + public event CancelSchedulesHandler? OnCancelSchedules; + + public void CancelSchedules() + { + conn.InternalCallReducer(new Reducer.CancelSchedules()); + } + + public bool InvokeCancelSchedules(global::SpacetimeDB.Types.ReducerEventContext ctx, Reducer.CancelSchedules args) + { + if (OnCancelSchedules == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnCancelSchedules( + ctx + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class CancelSchedules : global::SpacetimeDB.Types.Reducer, IReducerArgs + { + string IReducerArgs.ReducerName => "auth_data.cancel_schedules"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Fail.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Fail.g.cs new file mode 100644 index 00000000000..0186f95ab00 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Fail.g.cs @@ -0,0 +1,66 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void FailHandler(global::SpacetimeDB.Types.ReducerEventContext ctx, uint id); + public event FailHandler? OnFail; + + public void Fail(uint id) + { + conn.InternalCallReducer(new Reducer.Fail(id)); + } + + public bool InvokeFail(global::SpacetimeDB.Types.ReducerEventContext ctx, Reducer.Fail args) + { + if (OnFail == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnFail( + ctx, + args.Id + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Fail : global::SpacetimeDB.Types.Reducer, IReducerArgs + { + [DataMember(Name = "id")] + public uint Id; + + public Fail(uint Id) + { + this.Id = Id; + } + + public Fail() + { + } + + string IReducerArgs.ReducerName => "auth_data.fail"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Remove.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Remove.g.cs new file mode 100644 index 00000000000..a8f91cc77c7 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Remove.g.cs @@ -0,0 +1,66 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void RemoveHandler(global::SpacetimeDB.Types.ReducerEventContext ctx, uint id); + public event RemoveHandler? OnRemove; + + public void Remove(uint id) + { + conn.InternalCallReducer(new Reducer.Remove(id)); + } + + public bool InvokeRemove(global::SpacetimeDB.Types.ReducerEventContext ctx, Reducer.Remove args) + { + if (OnRemove == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnRemove( + ctx, + args.Id + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Remove : global::SpacetimeDB.Types.Reducer, IReducerArgs + { + [DataMember(Name = "id")] + public uint Id; + + public Remove(uint Id) + { + this.Id = Id; + } + + public Remove() + { + } + + string IReducerArgs.ReducerName => "auth_data.remove"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/StartSchedules.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/StartSchedules.g.cs new file mode 100644 index 00000000000..8c23799360d --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/StartSchedules.g.cs @@ -0,0 +1,53 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void StartSchedulesHandler(global::SpacetimeDB.Types.ReducerEventContext ctx); + public event StartSchedulesHandler? OnStartSchedules; + + public void StartSchedules() + { + conn.InternalCallReducer(new Reducer.StartSchedules()); + } + + public bool InvokeStartSchedules(global::SpacetimeDB.Types.ReducerEventContext ctx, Reducer.StartSchedules args) + { + if (OnStartSchedules == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnStartSchedules( + ctx + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class StartSchedules : global::SpacetimeDB.Types.Reducer, IReducerArgs + { + string IReducerArgs.ReducerName => "auth_data.start_schedules"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Update.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Update.g.cs new file mode 100644 index 00000000000..f8903ce2ecb --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Reducers/Update.g.cs @@ -0,0 +1,73 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void UpdateHandler(global::SpacetimeDB.Types.ReducerEventContext ctx, uint id, uint score); + public event UpdateHandler? OnUpdate; + + public void Update(uint id, uint score) + { + conn.InternalCallReducer(new Reducer.Update(id, score)); + } + + public bool InvokeUpdate(global::SpacetimeDB.Types.ReducerEventContext ctx, Reducer.Update args) + { + if (OnUpdate == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnUpdate( + ctx, + args.Id, + args.Score + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Update : global::SpacetimeDB.Types.Reducer, IReducerArgs + { + [DataMember(Name = "id")] + public uint Id; + [DataMember(Name = "score")] + public uint Score; + + public Update( + uint Id, + uint Score + ) + { + this.Id = Id; + this.Score = Score; + } + + public Update() + { + } + + string IReducerArgs.ReducerName => "auth_data.update"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/AnonymousUsers.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/AnonymousUsers.g.cs new file mode 100644 index 00000000000..fb44c4570e5 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/AnonymousUsers.g.cs @@ -0,0 +1,49 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteTables + { + public sealed class AnonymousUsersHandle : RemoteTableHandle + { + public override string RemoteTableName => "auth_data.anonymous_users"; + internal static readonly global::SpacetimeDB.SqlTableName SqlName = new global::SpacetimeDB.SqlTableName("auth_data", "anonymous_users"); + protected override global::SpacetimeDB.SqlTableName RemoteSqlTableName => SqlName; + + internal AnonymousUsersHandle(global::SpacetimeDB.Types.DbConnection conn) : base(conn) + { + } + } + + public readonly AnonymousUsersHandle AnonymousUsers; + } + + public sealed class AnonymousUsersCols + { + public global::SpacetimeDB.Col Id { get; } + public global::SpacetimeDB.Col Score { get; } + + public AnonymousUsersCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + Score = new global::SpacetimeDB.Col(tableName, "score"); + } + } + + public sealed class AnonymousUsersIxCols + { + + public AnonymousUsersIxCols(global::SpacetimeDB.SqlTableName tableName) + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/Notice.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/Notice.g.cs new file mode 100644 index 00000000000..0186e9a7f96 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/Notice.g.cs @@ -0,0 +1,47 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteTables + { + public sealed class NoticeHandle : RemoteEventTableHandle + { + public override string RemoteTableName => "auth_data.notice"; + internal static readonly global::SpacetimeDB.SqlTableName SqlName = new global::SpacetimeDB.SqlTableName("auth_data", "notice"); + protected override global::SpacetimeDB.SqlTableName RemoteSqlTableName => SqlName; + + internal NoticeHandle(global::SpacetimeDB.Types.DbConnection conn) : base(conn) + { + } + } + + public readonly NoticeHandle Notice; + } + + public sealed class NoticeCols + { + public global::SpacetimeDB.Col Id { get; } + + public NoticeCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + } + } + + public sealed class NoticeIxCols + { + + public NoticeIxCols(global::SpacetimeDB.SqlTableName tableName) + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/ProtectedRow.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/ProtectedRow.g.cs new file mode 100644 index 00000000000..fc369d56d87 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/ProtectedRow.g.cs @@ -0,0 +1,65 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteTables + { + public sealed class ProtectedRowHandle : RemoteTableHandle + { + public override string RemoteTableName => "auth_data.protected_row"; + internal static readonly global::SpacetimeDB.SqlTableName SqlName = new global::SpacetimeDB.SqlTableName("auth_data", "protected_row"); + protected override global::SpacetimeDB.SqlTableName RemoteSqlTableName => SqlName; + + public sealed class IdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(ProtectedRow row) => row.Id; + + public IdUniqueIndex(ProtectedRowHandle table) : base(table) { } + } + + public readonly IdUniqueIndex Id; + + internal ProtectedRowHandle(global::SpacetimeDB.Types.DbConnection conn) : base(conn) + { + Id = new(this); + } + + protected override object GetPrimaryKey(ProtectedRow row) => row.Id; + } + + public readonly ProtectedRowHandle ProtectedRow; + } + + public sealed class ProtectedRowCols + { + public global::SpacetimeDB.Col Id { get; } + public global::SpacetimeDB.Col Owner { get; } + public global::SpacetimeDB.Col Value { get; } + + public ProtectedRowCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + Owner = new global::SpacetimeDB.Col(tableName, "owner"); + Value = new global::SpacetimeDB.Col(tableName, "value"); + } + } + + public sealed class ProtectedRowIxCols + { + public global::SpacetimeDB.IxCol Id { get; } + + public ProtectedRowIxCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "id"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/QueryUsers.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/QueryUsers.g.cs new file mode 100644 index 00000000000..5566d2533c5 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/QueryUsers.g.cs @@ -0,0 +1,63 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteTables + { + public sealed class QueryUsersHandle : RemoteTableHandle + { + public override string RemoteTableName => "auth_data.query_users"; + internal static readonly global::SpacetimeDB.SqlTableName SqlName = new global::SpacetimeDB.SqlTableName("auth_data", "query_users"); + protected override global::SpacetimeDB.SqlTableName RemoteSqlTableName => SqlName; + + public sealed class IdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(User row) => row.Id; + + public IdUniqueIndex(QueryUsersHandle table) : base(table) { } + } + + public readonly IdUniqueIndex Id; + + internal QueryUsersHandle(global::SpacetimeDB.Types.DbConnection conn) : base(conn) + { + Id = new(this); + } + + protected override object GetPrimaryKey(User row) => row.Id; + } + + public readonly QueryUsersHandle QueryUsers; + } + + public sealed class QueryUsersCols + { + public global::SpacetimeDB.Col Id { get; } + public global::SpacetimeDB.Col Score { get; } + + public QueryUsersCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + Score = new global::SpacetimeDB.Col(tableName, "score"); + } + } + + public sealed class QueryUsersIxCols + { + public global::SpacetimeDB.IxCol Id { get; } + + public QueryUsersIxCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "id"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/ScheduleResult.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/ScheduleResult.g.cs new file mode 100644 index 00000000000..a468054d64c --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/ScheduleResult.g.cs @@ -0,0 +1,69 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteTables + { + public sealed class ScheduleResultHandle : RemoteTableHandle + { + public override string RemoteTableName => "auth_data.schedule_result"; + internal static readonly global::SpacetimeDB.SqlTableName SqlName = new global::SpacetimeDB.SqlTableName("auth_data", "schedule_result"); + protected override global::SpacetimeDB.SqlTableName RemoteSqlTableName => SqlName; + + public sealed class JobIdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(ScheduleResult row) => row.JobId; + + public JobIdUniqueIndex(ScheduleResultHandle table) : base(table) { } + } + + public readonly JobIdUniqueIndex JobId; + + internal ScheduleResultHandle(global::SpacetimeDB.Types.DbConnection conn) : base(conn) + { + JobId = new(this); + } + + protected override object GetPrimaryKey(ScheduleResult row) => row.JobId; + } + + public readonly ScheduleResultHandle ScheduleResult; + } + + public sealed class ScheduleResultCols + { + public global::SpacetimeDB.Col JobId { get; } + public global::SpacetimeDB.Col Payload { get; } + public global::SpacetimeDB.Col Kind { get; } + public global::SpacetimeDB.Col Executions { get; } + public global::SpacetimeDB.Col ScheduledId { get; } + + public ScheduleResultCols(global::SpacetimeDB.SqlTableName tableName) + { + JobId = new global::SpacetimeDB.Col(tableName, "job_id"); + Payload = new global::SpacetimeDB.Col(tableName, "payload"); + Kind = new global::SpacetimeDB.Col(tableName, "kind"); + Executions = new global::SpacetimeDB.Col(tableName, "executions"); + ScheduledId = new global::SpacetimeDB.Col(tableName, "scheduled_id"); + } + } + + public sealed class ScheduleResultIxCols + { + public global::SpacetimeDB.IxCol JobId { get; } + + public ScheduleResultIxCols(global::SpacetimeDB.SqlTableName tableName) + { + JobId = new global::SpacetimeDB.IxCol(tableName, "job_id"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/User.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/User.g.cs new file mode 100644 index 00000000000..b64600d1798 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/User.g.cs @@ -0,0 +1,75 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteTables + { + public sealed class UserHandle : RemoteTableHandle + { + public override string RemoteTableName => "auth_data.auth_users"; + internal static readonly global::SpacetimeDB.SqlTableName SqlName = new global::SpacetimeDB.SqlTableName("auth_data", "auth_users"); + protected override global::SpacetimeDB.SqlTableName RemoteSqlTableName => SqlName; + + public sealed class IdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(User row) => row.Id; + + public IdUniqueIndex(UserHandle table) : base(table) { } + } + + public readonly IdUniqueIndex Id; + + public sealed class ByScoreIndex : BTreeIndexBase + { + protected override uint GetKey(User row) => row.Score; + + public ByScoreIndex(UserHandle table) : base(table) { } + } + + public readonly ByScoreIndex ByScore; + + internal UserHandle(global::SpacetimeDB.Types.DbConnection conn) : base(conn) + { + Id = new(this); + ByScore = new(this); + } + + protected override object GetPrimaryKey(User row) => row.Id; + } + + public readonly UserHandle User; + } + + public sealed class UserCols + { + public global::SpacetimeDB.Col Id { get; } + public global::SpacetimeDB.Col Score { get; } + + public UserCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + Score = new global::SpacetimeDB.Col(tableName, "score"); + } + } + + public sealed class UserIxCols + { + public global::SpacetimeDB.IxCol Id { get; } + public global::SpacetimeDB.IxCol Score { get; } + + public UserIxCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "id"); + Score = new global::SpacetimeDB.IxCol(tableName, "score"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/Users.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/Users.g.cs new file mode 100644 index 00000000000..d6dd72eb559 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Tables/Users.g.cs @@ -0,0 +1,49 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + public sealed partial class RemoteTables + { + public sealed class UsersHandle : RemoteTableHandle + { + public override string RemoteTableName => "auth_data.users"; + internal static readonly global::SpacetimeDB.SqlTableName SqlName = new global::SpacetimeDB.SqlTableName("auth_data", "users"); + protected override global::SpacetimeDB.SqlTableName RemoteSqlTableName => SqlName; + + internal UsersHandle(global::SpacetimeDB.Types.DbConnection conn) : base(conn) + { + } + } + + public readonly UsersHandle Users; + } + + public sealed class UsersCols + { + public global::SpacetimeDB.Col Id { get; } + public global::SpacetimeDB.Col Score { get; } + + public UsersCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + Score = new global::SpacetimeDB.Col(tableName, "score"); + } + } + + public sealed class UsersIxCols + { + + public UsersIxCols(global::SpacetimeDB.SqlTableName tableName) + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/Notice.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/Notice.g.cs new file mode 100644 index 00000000000..03be173cad2 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/Notice.g.cs @@ -0,0 +1,28 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Notice + { + [DataMember(Name = "id")] + public uint Id; + + public Notice(uint Id) + { + this.Id = Id; + } + + public Notice() + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ProcedureJob.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ProcedureJob.g.cs new file mode 100644 index 00000000000..77cf6187ad6 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ProcedureJob.g.cs @@ -0,0 +1,43 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ProcedureJob + { + [DataMember(Name = "id")] + public ulong Id; + [DataMember(Name = "job_id")] + public uint JobId; + [DataMember(Name = "payload")] + public uint Payload; + [DataMember(Name = "due")] + public SpacetimeDB.ScheduleAt Due; + + public ProcedureJob( + ulong Id, + uint JobId, + uint Payload, + SpacetimeDB.ScheduleAt Due + ) + { + this.Id = Id; + this.JobId = JobId; + this.Payload = Payload; + this.Due = Due; + } + + public ProcedureJob() + { + this.Due = null!; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ProtectedRow.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ProtectedRow.g.cs new file mode 100644 index 00000000000..a587ca613be --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ProtectedRow.g.cs @@ -0,0 +1,38 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ProtectedRow + { + [DataMember(Name = "id")] + public uint Id; + [DataMember(Name = "owner")] + public SpacetimeDB.Identity Owner; + [DataMember(Name = "value")] + public uint Value; + + public ProtectedRow( + uint Id, + SpacetimeDB.Identity Owner, + uint Value + ) + { + this.Id = Id; + this.Owner = Owner; + this.Value = Value; + } + + public ProtectedRow() + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ReducerJob.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ReducerJob.g.cs new file mode 100644 index 00000000000..8494c957ef8 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ReducerJob.g.cs @@ -0,0 +1,43 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ReducerJob + { + [DataMember(Name = "id")] + public ulong Id; + [DataMember(Name = "job_id")] + public uint JobId; + [DataMember(Name = "due")] + public SpacetimeDB.ScheduleAt Due; + [DataMember(Name = "payload")] + public uint Payload; + + public ReducerJob( + ulong Id, + uint JobId, + SpacetimeDB.ScheduleAt Due, + uint Payload + ) + { + this.Id = Id; + this.JobId = JobId; + this.Due = Due; + this.Payload = Payload; + } + + public ReducerJob() + { + this.Due = null!; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ScheduleResult.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ScheduleResult.g.cs new file mode 100644 index 00000000000..32cff37367d --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/ScheduleResult.g.cs @@ -0,0 +1,47 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ScheduleResult + { + [DataMember(Name = "job_id")] + public uint JobId; + [DataMember(Name = "payload")] + public uint Payload; + [DataMember(Name = "kind")] + public string Kind; + [DataMember(Name = "executions")] + public uint Executions; + [DataMember(Name = "scheduled_id")] + public ulong ScheduledId; + + public ScheduleResult( + uint JobId, + uint Payload, + string Kind, + uint Executions, + ulong ScheduledId + ) + { + this.JobId = JobId; + this.Payload = Payload; + this.Kind = Kind; + this.Executions = Executions; + this.ScheduledId = ScheduledId; + } + + public ScheduleResult() + { + this.Kind = ""; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/Secret.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/Secret.g.cs new file mode 100644 index 00000000000..31cff985b59 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/Secret.g.cs @@ -0,0 +1,28 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Secret + { + [DataMember(Name = "id")] + public uint Id; + + public Secret(uint Id) + { + this.Id = Id; + } + + public Secret() + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/User.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/User.g.cs new file mode 100644 index 00000000000..48be9c0f4c6 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/MyAuth/Types/User.g.cs @@ -0,0 +1,34 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@MyAuth +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class User + { + [DataMember(Name = "id")] + public uint Id; + [DataMember(Name = "score")] + public uint Score; + + public User( + uint Id, + uint Score + ) + { + this.Id = Id; + this.Score = Score; + } + + public User() + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/CountAuthUsers.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/CountAuthUsers.g.cs new file mode 100644 index 00000000000..74eb276e753 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/CountAuthUsers.g.cs @@ -0,0 +1,64 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteProcedures : RemoteBase + { + public void CountAuthUsers(ProcedureCallback callback) + { + // Convert the clean callback to the wrapper callback + InternalCountAuthUsers((ctx, result) => + { + if (result.IsSuccess && result.Value != null) + { + callback(ctx, ProcedureCallbackResult.Success(result.Value.Value)); + } + else + { + callback(ctx, ProcedureCallbackResult.Failure(result.Error!)); + } + }); + } + + private void InternalCountAuthUsers(ProcedureCallback callback) + { + conn.InternalCallProcedure(new Procedure.CountAuthUsersArgs(), callback); + } + + } + + public abstract partial class Procedure + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class CountAuthUsers + { + [DataMember(Name = "Value")] + public ulong Value; + + public CountAuthUsers(ulong Value) + { + this.Value = Value; + } + + public CountAuthUsers() + { + } + } + [SpacetimeDB.Type] + [DataContract] + public sealed partial class CountAuthUsersArgs : Procedure, IProcedureArgs + { + string IProcedureArgs.ProcedureName => "count_auth_users"; + } + + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/CountUsers.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/CountUsers.g.cs new file mode 100644 index 00000000000..a3143fd4396 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/CountUsers.g.cs @@ -0,0 +1,64 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteProcedures : RemoteBase + { + public void CountUsers(ProcedureCallback callback) + { + // Convert the clean callback to the wrapper callback + InternalCountUsers((ctx, result) => + { + if (result.IsSuccess && result.Value != null) + { + callback(ctx, ProcedureCallbackResult.Success(result.Value.Value)); + } + else + { + callback(ctx, ProcedureCallbackResult.Failure(result.Error!)); + } + }); + } + + private void InternalCountUsers(ProcedureCallback callback) + { + conn.InternalCallProcedure(new Procedure.CountUsersArgs(), callback); + } + + } + + public abstract partial class Procedure + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class CountUsers + { + [DataMember(Name = "Value")] + public ulong Value; + + public CountUsers(ulong Value) + { + this.Value = Value; + } + + public CountUsers() + { + } + } + [SpacetimeDB.Type] + [DataContract] + public sealed partial class CountUsersArgs : Procedure, IProcedureArgs + { + string IProcedureArgs.ProcedureName => "count_users"; + } + + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/ResolveScheduleName.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/ResolveScheduleName.g.cs new file mode 100644 index 00000000000..df3ede0860a --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/ResolveScheduleName.g.cs @@ -0,0 +1,101 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteProcedures : RemoteBase + { + public void ResolveScheduleName(string accessor, string? namespaceName, string sourceName, string? functionName, bool rootNone, bool childNone, ProcedureCallback callback) + { + // Convert the clean callback to the wrapper callback + InternalResolveScheduleName(accessor, namespaceName, sourceName, functionName, rootNone, childNone, (ctx, result) => + { + if (result.IsSuccess && result.Value != null) + { + callback(ctx, ProcedureCallbackResult.Success(result.Value.Value)); + } + else + { + callback(ctx, ProcedureCallbackResult.Failure(result.Error!)); + } + }); + } + + private void InternalResolveScheduleName(string accessor, string? namespaceName, string sourceName, string? functionName, bool rootNone, bool childNone, ProcedureCallback callback) + { + conn.InternalCallProcedure(new Procedure.ResolveScheduleNameArgs(accessor, namespaceName, sourceName, functionName, rootNone, childNone), callback); + } + + } + + public abstract partial class Procedure + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ResolveScheduleName + { + [DataMember(Name = "Value")] + public string Value; + + public ResolveScheduleName(string Value) + { + this.Value = Value; + } + + public ResolveScheduleName() + { + this.Value = ""; + } + } + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ResolveScheduleNameArgs : Procedure, IProcedureArgs + { + [DataMember(Name = "accessor")] + public string Accessor; + [DataMember(Name = "namespace_name")] + public string? NamespaceName; + [DataMember(Name = "source_name")] + public string SourceName; + [DataMember(Name = "function_name")] + public string? FunctionName; + [DataMember(Name = "root_none")] + public bool RootNone; + [DataMember(Name = "child_none")] + public bool ChildNone; + + public ResolveScheduleNameArgs( + string Accessor, + string? NamespaceName, + string SourceName, + string? FunctionName, + bool RootNone, + bool ChildNone + ) + { + this.Accessor = Accessor; + this.NamespaceName = NamespaceName; + this.SourceName = SourceName; + this.FunctionName = FunctionName; + this.RootNone = RootNone; + this.ChildNone = ChildNone; + } + + public ResolveScheduleNameArgs() + { + this.Accessor = ""; + this.SourceName = ""; + } + + string IProcedureArgs.ProcedureName => "resolve_schedule_name"; + } + + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/WriteAcrossNamespaces.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/WriteAcrossNamespaces.g.cs new file mode 100644 index 00000000000..f955154cb22 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Procedures/WriteAcrossNamespaces.g.cs @@ -0,0 +1,82 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteProcedures : RemoteBase + { + public void WriteAcrossNamespaces(uint id, bool fail, ProcedureCallback callback) + { + // Convert the clean callback to the wrapper callback + InternalWriteAcrossNamespaces(id, fail, (ctx, result) => + { + if (result.IsSuccess && result.Value != null) + { + callback(ctx, ProcedureCallbackResult.Success(result.Value.Value)); + } + else + { + callback(ctx, ProcedureCallbackResult.Failure(result.Error!)); + } + }); + } + + private void InternalWriteAcrossNamespaces(uint id, bool fail, ProcedureCallback callback) + { + conn.InternalCallProcedure(new Procedure.WriteAcrossNamespacesArgs(id, fail), callback); + } + + } + + public abstract partial class Procedure + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class WriteAcrossNamespaces + { + [DataMember(Name = "Value")] + public uint Value; + + public WriteAcrossNamespaces(uint Value) + { + this.Value = Value; + } + + public WriteAcrossNamespaces() + { + } + } + [SpacetimeDB.Type] + [DataContract] + public sealed partial class WriteAcrossNamespacesArgs : Procedure, IProcedureArgs + { + [DataMember(Name = "id")] + public uint Id; + [DataMember(Name = "fail")] + public bool Fail; + + public WriteAcrossNamespacesArgs( + uint Id, + bool Fail + ) + { + this.Id = Id; + this.Fail = Fail; + } + + public WriteAcrossNamespacesArgs() + { + } + + string IProcedureArgs.ProcedureName => "write_across_namespaces"; + } + + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/AddAuthUser.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/AddAuthUser.g.cs new file mode 100644 index 00000000000..5fdfece427a --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/AddAuthUser.g.cs @@ -0,0 +1,66 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void AddAuthUserHandler(ReducerEventContext ctx, uint id); + public event AddAuthUserHandler? OnAddAuthUser; + + public void AddAuthUser(uint id) + { + conn.InternalCallReducer(new Reducer.AddAuthUser(id)); + } + + public bool InvokeAddAuthUser(ReducerEventContext ctx, Reducer.AddAuthUser args) + { + if (OnAddAuthUser == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnAddAuthUser( + ctx, + args.Id + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class AddAuthUser : Reducer, IReducerArgs + { + [DataMember(Name = "id")] + public uint Id; + + public AddAuthUser(uint Id) + { + this.Id = Id; + } + + public AddAuthUser() + { + } + + string IReducerArgs.ReducerName => "add_auth_user"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/Exercise.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/Exercise.g.cs new file mode 100644 index 00000000000..81bf38f0b86 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/Exercise.g.cs @@ -0,0 +1,53 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void ExerciseHandler(ReducerEventContext ctx); + public event ExerciseHandler? OnExercise; + + public void Exercise() + { + conn.InternalCallReducer(new Reducer.Exercise()); + } + + public bool InvokeExercise(ReducerEventContext ctx, Reducer.Exercise args) + { + if (OnExercise == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnExercise( + ctx + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Exercise : Reducer, IReducerArgs + { + string IReducerArgs.ReducerName => "exercise"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/Extra.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/Extra.g.cs new file mode 100644 index 00000000000..94e0c8c3e11 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/Extra.g.cs @@ -0,0 +1,53 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void ExtraHandler(ReducerEventContext ctx); + public event ExtraHandler? OnExtra; + + public void Extra() + { + conn.InternalCallReducer(new Reducer.Extra()); + } + + public bool InvokeExtra(ReducerEventContext ctx, Reducer.Extra args) + { + if (OnExtra == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnExtra( + ctx + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Extra : Reducer, IReducerArgs + { + string IReducerArgs.ReducerName => "extra"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/WriteProtectedRow.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/WriteProtectedRow.g.cs new file mode 100644 index 00000000000..497e6dd8f7f --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Reducers/WriteProtectedRow.g.cs @@ -0,0 +1,78 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void WriteProtectedRowHandler(ReducerEventContext ctx, uint id, SpacetimeDB.Identity owner, uint value); + public event WriteProtectedRowHandler? OnWriteProtectedRow; + + public void WriteProtectedRow(uint id, SpacetimeDB.Identity owner, uint value) + { + conn.InternalCallReducer(new Reducer.WriteProtectedRow(id, owner, value)); + } + + public bool InvokeWriteProtectedRow(ReducerEventContext ctx, Reducer.WriteProtectedRow args) + { + if (OnWriteProtectedRow == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnWriteProtectedRow( + ctx, + args.Id, + args.Owner, + args.Value + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class WriteProtectedRow : Reducer, IReducerArgs + { + [DataMember(Name = "id")] + public uint Id; + [DataMember(Name = "owner")] + public SpacetimeDB.Identity Owner; + [DataMember(Name = "value")] + public uint Value; + + public WriteProtectedRow( + uint Id, + SpacetimeDB.Identity Owner, + uint Value + ) + { + this.Id = Id; + this.Owner = Owner; + this.Value = Value; + } + + public WriteProtectedRow() + { + } + + string IReducerArgs.ReducerName => "write_protected_row"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/SpacetimeDBClient.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/SpacetimeDBClient.g.cs new file mode 100644 index 00000000000..64447228388 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/SpacetimeDBClient.g.cs @@ -0,0 +1,690 @@ +// 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.11.0 (commit 2025539bb2b645718bb9f305106c40fc52d7b3af). + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteReducers : RemoteBase + { + public global::SpacetimeDB.Types.@class.RemoteReducers @class { get; } + public global::SpacetimeDB.Types.@MyAuth.RemoteReducers @MyAuth { get; } + internal RemoteReducers(DbConnection conn) : base(conn) + { + @class = new(conn); + @class.InternalOnUnhandledReducerError += (ctx, error) => InternalOnUnhandledReducerError?.Invoke(ctx, error); + @MyAuth = new(conn); + @MyAuth.InternalOnUnhandledReducerError += (ctx, error) => InternalOnUnhandledReducerError?.Invoke(ctx, error); + } + internal event Action? InternalOnUnhandledReducerError; + } + + public sealed partial class RemoteProcedures : RemoteBase + { + public global::SpacetimeDB.Types.@class.RemoteProcedures @class { get; } + public global::SpacetimeDB.Types.@MyAuth.RemoteProcedures @MyAuth { get; } + internal RemoteProcedures(DbConnection conn) : base(conn) + { + @class = new(conn); + @MyAuth = new(conn); + } + } + + public sealed partial class RemoteTables : RemoteTablesBase + { + public global::SpacetimeDB.Types.@class.RemoteTables @class { get; } + public global::SpacetimeDB.Types.@MyAuth.RemoteTables @MyAuth { get; } + public RemoteTables(DbConnection conn) + { + AddTable(AuthUsers = new(conn)); + AddTable(ExtraRow = new(conn)); + AddTable(ExtraRows = new(conn)); + AddTable(QueryExtra = new(conn)); + AddTable(QueryUsers = new(conn)); + AddTable(QueryUsersRight = new(conn)); + AddTable(User = new(conn)); + AddTable(Users = new(conn)); + @class = new(conn, AddTable); + @MyAuth = new(conn, AddTable); + } + } + + + public interface IRemoteDbContext : IDbContext + { + public event Action? OnUnhandledReducerError; + } + + public sealed class EventContext : IEventContext, IRemoteDbContext + { + private readonly DbConnection conn; + + /// + /// The event that caused this callback to run. + /// + public readonly Event Event; + + /// + /// Access to tables in the client cache, which stores a read-only replica of the remote database state. + /// + /// The returned DbView will have a method to access each table defined by the module. + /// + public RemoteTables Db => conn.Db; + /// + /// Access to reducers defined by the module. + /// + /// The returned RemoteReducers will have a method to invoke each reducer defined by the module, + /// plus methods for adding and removing callbacks on each of those reducers. + /// + public RemoteReducers Reducers => conn.Reducers; + /// + /// Access to procedures defined by the module. + /// + /// The returned RemoteProcedures will have a method to invoke each procedure defined by the module, + /// with a callback for when the procedure completes and returns a value. + /// + public RemoteProcedures Procedures => conn.Procedures; + /// + /// Returns true if the connection is active, i.e. has not yet disconnected. + /// + public bool IsActive => conn.IsActive; + /// + /// Close the connection. + /// + /// Throws an error if the connection is already closed. + /// + public void Disconnect() + { + conn.Disconnect(); + } + /// + /// Start building a subscription. + /// + /// A builder-pattern constructor for subscribing to queries, + /// causing matching rows to be replicated into the client cache. + public SubscriptionBuilder SubscriptionBuilder() => conn.SubscriptionBuilder(); + /// + /// Get the Identity of this connection. + /// + /// This method returns null if the connection was constructed anonymously + /// and we have not yet received our newly-generated Identity from the host. + /// + public Identity? Identity => conn.Identity; + /// + /// Get this connection's ConnectionId. + /// + public ConnectionId ConnectionId => conn.ConnectionId; + /// + /// Register a callback to be called when a reducer with no handler returns an error. + /// + public event Action? OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + + internal EventContext(DbConnection conn, Event Event) + { + this.conn = conn; + this.Event = Event; + } + } + + public sealed class ReducerEventContext : IReducerEventContext, IRemoteDbContext + { + private readonly DbConnection conn; + /// + /// The reducer event that caused this callback to run. + /// + public readonly ReducerEvent Event; + + /// + /// Access to tables in the client cache, which stores a read-only replica of the remote database state. + /// + /// The returned DbView will have a method to access each table defined by the module. + /// + public RemoteTables Db => conn.Db; + /// + /// Access to reducers defined by the module. + /// + /// The returned RemoteReducers will have a method to invoke each reducer defined by the module, + /// plus methods for adding and removing callbacks on each of those reducers. + /// + public RemoteReducers Reducers => conn.Reducers; + /// + /// Access to procedures defined by the module. + /// + /// The returned RemoteProcedures will have a method to invoke each procedure defined by the module, + /// with a callback for when the procedure completes and returns a value. + /// + public RemoteProcedures Procedures => conn.Procedures; + /// + /// Returns true if the connection is active, i.e. has not yet disconnected. + /// + public bool IsActive => conn.IsActive; + /// + /// Close the connection. + /// + /// Throws an error if the connection is already closed. + /// + public void Disconnect() + { + conn.Disconnect(); + } + /// + /// Start building a subscription. + /// + /// A builder-pattern constructor for subscribing to queries, + /// causing matching rows to be replicated into the client cache. + public SubscriptionBuilder SubscriptionBuilder() => conn.SubscriptionBuilder(); + /// + /// Get the Identity of this connection. + /// + /// This method returns null if the connection was constructed anonymously + /// and we have not yet received our newly-generated Identity from the host. + /// + public Identity? Identity => conn.Identity; + /// + /// Get this connection's ConnectionId. + /// + public ConnectionId ConnectionId => conn.ConnectionId; + /// + /// Register a callback to be called when a reducer with no handler returns an error. + /// + public event Action? OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + + internal ReducerEventContext(DbConnection conn, ReducerEvent reducerEvent) + { + this.conn = conn; + Event = reducerEvent; + } + } + + public sealed class ErrorContext : IErrorContext, IRemoteDbContext + { + private readonly DbConnection conn; + /// + /// The Exception that caused this error callback to be run. + /// + public readonly Exception Event; + Exception IErrorContext.Event + { + get + { + return Event; + } + } + + /// + /// Access to tables in the client cache, which stores a read-only replica of the remote database state. + /// + /// The returned DbView will have a method to access each table defined by the module. + /// + public RemoteTables Db => conn.Db; + /// + /// Access to reducers defined by the module. + /// + /// The returned RemoteReducers will have a method to invoke each reducer defined by the module, + /// plus methods for adding and removing callbacks on each of those reducers. + /// + public RemoteReducers Reducers => conn.Reducers; + /// + /// Access to procedures defined by the module. + /// + /// The returned RemoteProcedures will have a method to invoke each procedure defined by the module, + /// with a callback for when the procedure completes and returns a value. + /// + public RemoteProcedures Procedures => conn.Procedures; + /// + /// Returns true if the connection is active, i.e. has not yet disconnected. + /// + public bool IsActive => conn.IsActive; + /// + /// Close the connection. + /// + /// Throws an error if the connection is already closed. + /// + public void Disconnect() + { + conn.Disconnect(); + } + /// + /// Start building a subscription. + /// + /// A builder-pattern constructor for subscribing to queries, + /// causing matching rows to be replicated into the client cache. + public SubscriptionBuilder SubscriptionBuilder() => conn.SubscriptionBuilder(); + /// + /// Get the Identity of this connection. + /// + /// This method returns null if the connection was constructed anonymously + /// and we have not yet received our newly-generated Identity from the host. + /// + public Identity? Identity => conn.Identity; + /// + /// Get this connection's ConnectionId. + /// + public ConnectionId ConnectionId => conn.ConnectionId; + /// + /// Register a callback to be called when a reducer with no handler returns an error. + /// + public event Action? OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + + internal ErrorContext(DbConnection conn, Exception error) + { + this.conn = conn; + Event = error; + } + } + + public sealed class SubscriptionEventContext : ISubscriptionEventContext, IRemoteDbContext + { + private readonly DbConnection conn; + + /// + /// Access to tables in the client cache, which stores a read-only replica of the remote database state. + /// + /// The returned DbView will have a method to access each table defined by the module. + /// + public RemoteTables Db => conn.Db; + /// + /// Access to reducers defined by the module. + /// + /// The returned RemoteReducers will have a method to invoke each reducer defined by the module, + /// plus methods for adding and removing callbacks on each of those reducers. + /// + public RemoteReducers Reducers => conn.Reducers; + /// + /// Access to procedures defined by the module. + /// + /// The returned RemoteProcedures will have a method to invoke each procedure defined by the module, + /// with a callback for when the procedure completes and returns a value. + /// + public RemoteProcedures Procedures => conn.Procedures; + /// + /// Returns true if the connection is active, i.e. has not yet disconnected. + /// + public bool IsActive => conn.IsActive; + /// + /// Close the connection. + /// + /// Throws an error if the connection is already closed. + /// + public void Disconnect() + { + conn.Disconnect(); + } + /// + /// Start building a subscription. + /// + /// A builder-pattern constructor for subscribing to queries, + /// causing matching rows to be replicated into the client cache. + public SubscriptionBuilder SubscriptionBuilder() => conn.SubscriptionBuilder(); + /// + /// Get the Identity of this connection. + /// + /// This method returns null if the connection was constructed anonymously + /// and we have not yet received our newly-generated Identity from the host. + /// + public Identity? Identity => conn.Identity; + /// + /// Get this connection's ConnectionId. + /// + public ConnectionId ConnectionId => conn.ConnectionId; + /// + /// Register a callback to be called when a reducer with no handler returns an error. + /// + public event Action? OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + + internal SubscriptionEventContext(DbConnection conn) + { + this.conn = conn; + } + } + + public sealed class ProcedureEventContext : IProcedureEventContext, IRemoteDbContext + { + private readonly DbConnection conn; + /// + /// The procedure event that caused this callback to run. + /// + public readonly ProcedureEvent Event; + + /// + /// Access to tables in the client cache, which stores a read-only replica of the remote database state. + /// + /// The returned DbView will have a method to access each table defined by the module. + /// + public RemoteTables Db => conn.Db; + /// + /// Access to reducers defined by the module. + /// + /// The returned RemoteReducers will have a method to invoke each reducer defined by the module, + /// plus methods for adding and removing callbacks on each of those reducers. + /// + public RemoteReducers Reducers => conn.Reducers; + /// + /// Access to procedures defined by the module. + /// + /// The returned RemoteProcedures will have a method to invoke each procedure defined by the module, + /// with a callback for when the procedure completes and returns a value. + /// + public RemoteProcedures Procedures => conn.Procedures; + /// + /// Returns true if the connection is active, i.e. has not yet disconnected. + /// + public bool IsActive => conn.IsActive; + /// + /// Close the connection. + /// + /// Throws an error if the connection is already closed. + /// + public void Disconnect() + { + conn.Disconnect(); + } + /// + /// Start building a subscription. + /// + /// A builder-pattern constructor for subscribing to queries, + /// causing matching rows to be replicated into the client cache. + public SubscriptionBuilder SubscriptionBuilder() => conn.SubscriptionBuilder(); + /// + /// Get the Identity of this connection. + /// + /// This method returns null if the connection was constructed anonymously + /// and we have not yet received our newly-generated Identity from the host. + /// + public Identity? Identity => conn.Identity; + /// + /// Get this connection's ConnectionId. + /// + public ConnectionId ConnectionId => conn.ConnectionId; + /// + /// Register a callback to be called when a reducer with no handler returns an error. + /// + public event Action? OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + + internal ProcedureEventContext(DbConnection conn, ProcedureEvent Event) + { + this.conn = conn; + this.Event = Event; + } + } + + /// + /// Builder-pattern constructor for subscription queries. + /// + public sealed class SubscriptionBuilder + { + private readonly IDbConnection conn; + + private event Action? Applied; + private event Action? Error; + + /// + /// Private API, use conn.SubscriptionBuilder() instead. + /// + public SubscriptionBuilder(IDbConnection conn) + { + this.conn = conn; + } + + /// + /// Register a callback to run when the subscription is applied. + /// + public SubscriptionBuilder OnApplied( + Action callback + ) + { + Applied += callback; + return this; + } + + /// + /// Register a callback to run when the subscription fails. + /// + /// Note that this callback may run either when attempting to apply the subscription, + /// in which case Self::on_applied will never run, + /// or later during the subscription's lifetime if the module's interface changes, + /// in which case Self::on_applied may have already run. + /// + public SubscriptionBuilder OnError( + Action callback + ) + { + Error += callback; + return this; + } + + /// + /// Add a typed query to this subscription. + /// + /// This is the entry point for building subscriptions without writing SQL by hand. + /// Once a typed query is added, only typed queries may follow (SQL and typed queries cannot be mixed). + /// + public TypedSubscriptionBuilder AddQuery( + Func> build + ) + { + var typed = new TypedSubscriptionBuilder(conn, Applied, Error); + return typed.AddQuery(build); + } + + /// + /// Subscribe to the following SQL queries. + /// + /// This method returns immediately, with the data not yet added to the DbConnection. + /// The provided callbacks will be invoked once the data is returned from the remote server. + /// Data from all the provided queries will be returned at the same time. + /// + /// See the SpacetimeDB SQL docs for more information on SQL syntax: + /// https://spacetimedb.com/docs/reference/sql + /// + public SubscriptionHandle Subscribe( + string[] querySqls + ) => new(conn, Applied, Error, querySqls); + + /// + /// Subscribe to all rows from all tables. + /// + /// This method is intended as a convenience + /// for applications where client-side memory use and network bandwidth are not concerns. + /// Applications where these resources are a constraint + /// should register more precise queries via Self.Subscribe + /// in order to replicate only the subset of data which the client needs to function. + /// + /// This method should not be combined with Self.Subscribe on the same DbConnection. + /// A connection may either Self.Subscribe to particular queries, + /// or Self.SubscribeToAllTables, but not both. + /// Attempting to call Self.Subscribe + /// on a DbConnection that has previously used Self.SubscribeToAllTables, + /// or vice versa, may misbehave in any number of ways, + /// including dropping subscriptions, corrupting the client cache, or panicking. + /// + public SubscriptionHandle SubscribeToAllTables() => + new(conn, Applied, Error, QueryBuilder.AllTablesSqlQueries()); + } + + public sealed class SubscriptionHandle : SubscriptionHandleBase + { + /// + /// Internal API. Construct SubscriptionHandles using conn.SubscriptionBuilder. + /// + public SubscriptionHandle( + IDbConnection conn, + Action? onApplied, + Action? onError, + string[] querySqls + ) : base(conn, onApplied, onError, querySqls) + { } + } + + public sealed class QueryBuilder + { + public From From { get; } = new(); + + internal static string[] AllTablesSqlQueries() => new string[] + { + new QueryBuilder().From.AuthUsers().ToSql(), + new QueryBuilder().From.ExtraRow().ToSql(), + new QueryBuilder().From.ExtraRows().ToSql(), + new QueryBuilder().From.QueryExtra().ToSql(), + new QueryBuilder().From.QueryUsers().ToSql(), + new QueryBuilder().From.QueryUsersRight().ToSql(), + new QueryBuilder().From.User().ToSql(), + new QueryBuilder().From.Users().ToSql(), + new QueryBuilder().From.@MyAuth.Notice().ToSql(), + new QueryBuilder().From.@MyAuth.ProtectedRow().ToSql(), + new QueryBuilder().From.@MyAuth.ScheduleResult().ToSql(), + new QueryBuilder().From.@MyAuth.User().ToSql(), + new QueryBuilder().From.@class.ScheduleResult().ToSql(), + new QueryBuilder().From.@class.User().ToSql(), + new QueryBuilder().From.@MyAuth.QueryUsers().ToSql(), + new QueryBuilder().From.@MyAuth.Users().ToSql(), + new QueryBuilder().From.@MyAuth.AnonymousUsers().ToSql(), + } + ; + } + + public sealed class From + { + public global::SpacetimeDB.Types.@class.From @class { get; } = new(); + public global::SpacetimeDB.Types.@MyAuth.From @MyAuth { get; } = new(); + public global::SpacetimeDB.Table AuthUsers() => new("auth_users", new AuthUsersCols("auth_users"), new AuthUsersIxCols("auth_users")); + public global::SpacetimeDB.Table ExtraRow() => new("extra_row", new ExtraRowCols("extra_row"), new ExtraRowIxCols("extra_row")); + public global::SpacetimeDB.Table ExtraRows() => new("extra_rows", new ExtraRowsCols("extra_rows"), new ExtraRowsIxCols("extra_rows")); + public global::SpacetimeDB.Table QueryExtra() => new("query_extra", new QueryExtraCols("query_extra"), new QueryExtraIxCols("query_extra")); + public global::SpacetimeDB.Table QueryUsers() => new("query_users", new QueryUsersCols("query_users"), new QueryUsersIxCols("query_users")); + public global::SpacetimeDB.Table QueryUsersRight() => new("query_users_right", new QueryUsersRightCols("query_users_right"), new QueryUsersRightIxCols("query_users_right")); + public global::SpacetimeDB.Table User() => new("user", new UserCols("user"), new UserIxCols("user")); + public global::SpacetimeDB.Table Users() => new("users", new UsersCols("users"), new UsersIxCols("users")); + } + + public sealed class TypedSubscriptionBuilder + { + private readonly IDbConnection conn; + private Action? Applied; + private Action? Error; + private readonly List querySqls = new(); + + internal TypedSubscriptionBuilder(IDbConnection conn, Action? applied, Action? error) + { + this.conn = conn; + Applied = applied; + Error = error; + } + + public TypedSubscriptionBuilder OnApplied(Action callback) + { + Applied += callback; + return this; + } + + public TypedSubscriptionBuilder OnError(Action callback) + { + Error += callback; + return this; + } + + public TypedSubscriptionBuilder AddQuery(Func> build) + { + var qb = new QueryBuilder(); + querySqls.Add(build(qb).ToSql()); + return this; + } + + public SubscriptionHandle Subscribe() => new(conn, Applied, Error, querySqls.ToArray()); + } + + public abstract partial class Reducer + { + private protected Reducer() { } + } + + public abstract partial class Procedure + { + private Procedure() { } + } + + public sealed class DbConnection : DbConnectionBase + { + public override RemoteTables Db { get; } + public readonly RemoteReducers Reducers; + public readonly RemoteProcedures Procedures; + + public DbConnection() + { + Db = new(this); + Reducers = new(this); + Procedures = new(this); + } + + protected override IEventContext ToEventContext(Event Event) => + new EventContext(this, Event); + + protected override IReducerEventContext ToReducerEventContext(ReducerEvent reducerEvent) => + new ReducerEventContext(this, reducerEvent); + + protected override ISubscriptionEventContext MakeSubscriptionEventContext() => + new SubscriptionEventContext(this); + + protected override IErrorContext ToErrorContext(Exception exception) => + new ErrorContext(this, exception); + + protected override IProcedureEventContext ToProcedureEventContext(ProcedureEvent procedureEvent) => + new ProcedureEventContext(this, procedureEvent); + + protected override bool Dispatch(IReducerEventContext context, Reducer reducer) + { + var eventContext = (ReducerEventContext)context; + return reducer switch + { + Reducer.AddAuthUser args => Reducers.InvokeAddAuthUser(eventContext, args), + Reducer.Exercise args => Reducers.InvokeExercise(eventContext, args), + Reducer.WriteProtectedRow args => Reducers.InvokeWriteProtectedRow(eventContext, args), + Reducer.Extra args => Reducers.InvokeExtra(eventContext, args), + global::SpacetimeDB.Types.@class.Reducer.Add args => Reducers.@class.InvokeAdd(eventContext, args), + global::SpacetimeDB.Types.@class.Reducer.CancelSchedules args => Reducers.@class.InvokeCancelSchedules(eventContext, args), + global::SpacetimeDB.Types.@class.Reducer.StartSchedules args => Reducers.@class.InvokeStartSchedules(eventContext, args), + global::SpacetimeDB.Types.@MyAuth.Reducer.Add args => Reducers.@MyAuth.InvokeAdd(eventContext, args), + global::SpacetimeDB.Types.@MyAuth.Reducer.CancelSchedules args => Reducers.@MyAuth.InvokeCancelSchedules(eventContext, args), + global::SpacetimeDB.Types.@MyAuth.Reducer.Fail args => Reducers.@MyAuth.InvokeFail(eventContext, args), + global::SpacetimeDB.Types.@MyAuth.Reducer.Remove args => Reducers.@MyAuth.InvokeRemove(eventContext, args), + global::SpacetimeDB.Types.@MyAuth.Reducer.StartSchedules args => Reducers.@MyAuth.InvokeStartSchedules(eventContext, args), + global::SpacetimeDB.Types.@MyAuth.Reducer.Update args => Reducers.@MyAuth.InvokeUpdate(eventContext, args), + _ => throw new ArgumentOutOfRangeException("Reducer", $"Unknown reducer {reducer}") + }; + } + + public SubscriptionBuilder SubscriptionBuilder() => new(this); + public event Action OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/AuthUsers.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/AuthUsers.g.cs new file mode 100644 index 00000000000..17cebd8cd11 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/AuthUsers.g.cs @@ -0,0 +1,45 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteTables + { + public sealed class AuthUsersHandle : RemoteTableHandle + { + public override string RemoteTableName => "auth_users"; + + internal AuthUsersHandle(DbConnection conn) : base(conn) + { + } + } + + public readonly AuthUsersHandle AuthUsers; + } + + public sealed class AuthUsersCols + { + public global::SpacetimeDB.Col Score { get; } + + public AuthUsersCols(string tableName) + { + Score = new global::SpacetimeDB.Col(tableName, "score"); + } + } + + public sealed class AuthUsersIxCols + { + + public AuthUsersIxCols(string tableName) + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/ExtraRow.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/ExtraRow.g.cs new file mode 100644 index 00000000000..bf5a18779a9 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/ExtraRow.g.cs @@ -0,0 +1,59 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteTables + { + public sealed class ExtraRowHandle : RemoteTableHandle + { + public override string RemoteTableName => "extra_row"; + + public sealed class IdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(ExtraRow row) => row.Id; + + public IdUniqueIndex(ExtraRowHandle table) : base(table) { } + } + + public readonly IdUniqueIndex Id; + + internal ExtraRowHandle(DbConnection conn) : base(conn) + { + Id = new(this); + } + + protected override object GetPrimaryKey(ExtraRow row) => row.Id; + } + + public readonly ExtraRowHandle ExtraRow; + } + + public sealed class ExtraRowCols + { + public global::SpacetimeDB.Col Id { get; } + + public ExtraRowCols(string tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + } + } + + public sealed class ExtraRowIxCols + { + public global::SpacetimeDB.IxCol Id { get; } + + public ExtraRowIxCols(string tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "id"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/ExtraRows.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/ExtraRows.g.cs new file mode 100644 index 00000000000..2783f517464 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/ExtraRows.g.cs @@ -0,0 +1,45 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteTables + { + public sealed class ExtraRowsHandle : RemoteTableHandle + { + public override string RemoteTableName => "extra_rows"; + + internal ExtraRowsHandle(DbConnection conn) : base(conn) + { + } + } + + public readonly ExtraRowsHandle ExtraRows; + } + + public sealed class ExtraRowsCols + { + public global::SpacetimeDB.Col Id { get; } + + public ExtraRowsCols(string tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + } + } + + public sealed class ExtraRowsIxCols + { + + public ExtraRowsIxCols(string tableName) + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/QueryExtra.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/QueryExtra.g.cs new file mode 100644 index 00000000000..d4ed4e5e190 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/QueryExtra.g.cs @@ -0,0 +1,59 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteTables + { + public sealed class QueryExtraHandle : RemoteTableHandle + { + public override string RemoteTableName => "query_extra"; + + public sealed class IdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(ExtraRow row) => row.Id; + + public IdUniqueIndex(QueryExtraHandle table) : base(table) { } + } + + public readonly IdUniqueIndex Id; + + internal QueryExtraHandle(DbConnection conn) : base(conn) + { + Id = new(this); + } + + protected override object GetPrimaryKey(ExtraRow row) => row.Id; + } + + public readonly QueryExtraHandle QueryExtra; + } + + public sealed class QueryExtraCols + { + public global::SpacetimeDB.Col Id { get; } + + public QueryExtraCols(string tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + } + } + + public sealed class QueryExtraIxCols + { + public global::SpacetimeDB.IxCol Id { get; } + + public QueryExtraIxCols(string tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "id"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/QueryUsers.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/QueryUsers.g.cs new file mode 100644 index 00000000000..3d6fd0ffeb1 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/QueryUsers.g.cs @@ -0,0 +1,59 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteTables + { + public sealed class QueryUsersHandle : RemoteTableHandle + { + public override string RemoteTableName => "query_users"; + + public sealed class IdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(User row) => row.Id; + + public IdUniqueIndex(QueryUsersHandle table) : base(table) { } + } + + public readonly IdUniqueIndex Id; + + internal QueryUsersHandle(DbConnection conn) : base(conn) + { + Id = new(this); + } + + protected override object GetPrimaryKey(User row) => row.Id; + } + + public readonly QueryUsersHandle QueryUsers; + } + + public sealed class QueryUsersCols + { + public global::SpacetimeDB.Col Id { get; } + + public QueryUsersCols(string tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + } + } + + public sealed class QueryUsersIxCols + { + public global::SpacetimeDB.IxCol Id { get; } + + public QueryUsersIxCols(string tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "id"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/QueryUsersRight.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/QueryUsersRight.g.cs new file mode 100644 index 00000000000..789c48e05ee --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/QueryUsersRight.g.cs @@ -0,0 +1,59 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteTables + { + public sealed class QueryUsersRightHandle : RemoteTableHandle + { + public override string RemoteTableName => "query_users_right"; + + public sealed class IdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(User row) => row.Id; + + public IdUniqueIndex(QueryUsersRightHandle table) : base(table) { } + } + + public readonly IdUniqueIndex Id; + + internal QueryUsersRightHandle(DbConnection conn) : base(conn) + { + Id = new(this); + } + + protected override object GetPrimaryKey(User row) => row.Id; + } + + public readonly QueryUsersRightHandle QueryUsersRight; + } + + public sealed class QueryUsersRightCols + { + public global::SpacetimeDB.Col Id { get; } + + public QueryUsersRightCols(string tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + } + } + + public sealed class QueryUsersRightIxCols + { + public global::SpacetimeDB.IxCol Id { get; } + + public QueryUsersRightIxCols(string tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "id"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/User.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/User.g.cs new file mode 100644 index 00000000000..36347fddc14 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/User.g.cs @@ -0,0 +1,59 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteTables + { + public sealed class UserHandle : RemoteTableHandle + { + public override string RemoteTableName => "user"; + + public sealed class IdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(User row) => row.Id; + + public IdUniqueIndex(UserHandle table) : base(table) { } + } + + public readonly IdUniqueIndex Id; + + internal UserHandle(DbConnection conn) : base(conn) + { + Id = new(this); + } + + protected override object GetPrimaryKey(User row) => row.Id; + } + + public readonly UserHandle User; + } + + public sealed class UserCols + { + public global::SpacetimeDB.Col Id { get; } + + public UserCols(string tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + } + } + + public sealed class UserIxCols + { + public global::SpacetimeDB.IxCol Id { get; } + + public UserIxCols(string tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "id"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/Users.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/Users.g.cs new file mode 100644 index 00000000000..bf10755fee7 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Tables/Users.g.cs @@ -0,0 +1,45 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteTables + { + public sealed class UsersHandle : RemoteTableHandle + { + public override string RemoteTableName => "users"; + + internal UsersHandle(DbConnection conn) : base(conn) + { + } + } + + public readonly UsersHandle Users; + } + + public sealed class UsersCols + { + public global::SpacetimeDB.Col Id { get; } + + public UsersCols(string tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + } + } + + public sealed class UsersIxCols + { + + public UsersIxCols(string tableName) + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Types/AuthSummary.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Types/AuthSummary.g.cs new file mode 100644 index 00000000000..31c6b653b03 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Types/AuthSummary.g.cs @@ -0,0 +1,28 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class AuthSummary + { + [DataMember(Name = "score")] + public uint Score; + + public AuthSummary(uint Score) + { + this.Score = Score; + } + + public AuthSummary() + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Types/ExtraRow.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Types/ExtraRow.g.cs new file mode 100644 index 00000000000..1759fe6f549 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Types/ExtraRow.g.cs @@ -0,0 +1,28 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ExtraRow + { + [DataMember(Name = "id")] + public uint Id; + + public ExtraRow(uint Id) + { + this.Id = Id; + } + + public ExtraRow() + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Types/User.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Types/User.g.cs new file mode 100644 index 00000000000..d9e5a3733aa --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/Types/User.g.cs @@ -0,0 +1,28 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class User + { + [DataMember(Name = "id")] + public uint Id; + + public User(uint Id) + { + this.Id = Id; + } + + public User() + { + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Namespace.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Namespace.g.cs new file mode 100644 index 00000000000..367b0c7cf3c --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Namespace.g.cs @@ -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. + +#nullable enable + +using System; +using System.Collections.Generic; + +namespace SpacetimeDB.Types.@class +{ + public sealed partial class RemoteReducers : RemoteBase + { + internal RemoteReducers(global::SpacetimeDB.Types.DbConnection conn) : base(conn) { } + internal event Action? InternalOnUnhandledReducerError; + } + + public sealed partial class RemoteProcedures : RemoteBase + { + internal RemoteProcedures(global::SpacetimeDB.Types.DbConnection conn) : base(conn) { } + } + + public sealed partial class RemoteTables + { + internal RemoteTables(global::SpacetimeDB.Types.DbConnection conn, Action register) + { + register(ScheduleResult = new(conn)); + register(User = new(conn)); + } + } + public sealed class From + { + public global::SpacetimeDB.Table ScheduleResult() => new(RemoteTables.ScheduleResultHandle.SqlName, new ScheduleResultCols(RemoteTables.ScheduleResultHandle.SqlName), new ScheduleResultIxCols(RemoteTables.ScheduleResultHandle.SqlName)); + public global::SpacetimeDB.Table User() => new(RemoteTables.UserHandle.SqlName, new UserCols(RemoteTables.UserHandle.SqlName), new UserIxCols(RemoteTables.UserHandle.SqlName)); + } + + public abstract partial class Reducer + { + private Reducer() { } + } + public abstract partial class Procedure + { + private Procedure() { } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Procedures/CountUsers.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Procedures/CountUsers.g.cs new file mode 100644 index 00000000000..ed009b4d43c --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Procedures/CountUsers.g.cs @@ -0,0 +1,64 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@class +{ + public sealed partial class RemoteProcedures : RemoteBase + { + public void CountUsers(ProcedureCallback callback) + { + // Convert the clean callback to the wrapper callback + InternalCountUsers((ctx, result) => + { + if (result.IsSuccess && result.Value != null) + { + callback(ctx, ProcedureCallbackResult.Success(result.Value.Value)); + } + else + { + callback(ctx, ProcedureCallbackResult.Failure(result.Error!)); + } + }); + } + + private void InternalCountUsers(ProcedureCallback callback) + { + conn.InternalCallProcedure(new Procedure.CountUsersArgs(), callback); + } + + } + + public abstract partial class Procedure + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class CountUsers + { + [DataMember(Name = "Value")] + public ulong Value; + + public CountUsers(ulong Value) + { + this.Value = Value; + } + + public CountUsers() + { + } + } + [SpacetimeDB.Type] + [DataContract] + public sealed partial class CountUsersArgs : Procedure, IProcedureArgs + { + string IProcedureArgs.ProcedureName => "class.count_users"; + } + + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Reducers/Add.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Reducers/Add.g.cs new file mode 100644 index 00000000000..7396fd1840a --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Reducers/Add.g.cs @@ -0,0 +1,66 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@class +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void AddHandler(global::SpacetimeDB.Types.ReducerEventContext ctx, uint id); + public event AddHandler? OnAdd; + + public void Add(uint id) + { + conn.InternalCallReducer(new Reducer.Add(id)); + } + + public bool InvokeAdd(global::SpacetimeDB.Types.ReducerEventContext ctx, Reducer.Add args) + { + if (OnAdd == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnAdd( + ctx, + args.Id + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Add : global::SpacetimeDB.Types.Reducer, IReducerArgs + { + [DataMember(Name = "id")] + public uint Id; + + public Add(uint Id) + { + this.Id = Id; + } + + public Add() + { + } + + string IReducerArgs.ReducerName => "class.add"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Reducers/CancelSchedules.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Reducers/CancelSchedules.g.cs new file mode 100644 index 00000000000..bf8783d6429 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Reducers/CancelSchedules.g.cs @@ -0,0 +1,53 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@class +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void CancelSchedulesHandler(global::SpacetimeDB.Types.ReducerEventContext ctx); + public event CancelSchedulesHandler? OnCancelSchedules; + + public void CancelSchedules() + { + conn.InternalCallReducer(new Reducer.CancelSchedules()); + } + + public bool InvokeCancelSchedules(global::SpacetimeDB.Types.ReducerEventContext ctx, Reducer.CancelSchedules args) + { + if (OnCancelSchedules == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnCancelSchedules( + ctx + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class CancelSchedules : global::SpacetimeDB.Types.Reducer, IReducerArgs + { + string IReducerArgs.ReducerName => "class.cancel_schedules"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Reducers/StartSchedules.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Reducers/StartSchedules.g.cs new file mode 100644 index 00000000000..cb9eeddaad2 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Reducers/StartSchedules.g.cs @@ -0,0 +1,53 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@class +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void StartSchedulesHandler(global::SpacetimeDB.Types.ReducerEventContext ctx); + public event StartSchedulesHandler? OnStartSchedules; + + public void StartSchedules() + { + conn.InternalCallReducer(new Reducer.StartSchedules()); + } + + public bool InvokeStartSchedules(global::SpacetimeDB.Types.ReducerEventContext ctx, Reducer.StartSchedules args) + { + if (OnStartSchedules == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnStartSchedules( + ctx + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class StartSchedules : global::SpacetimeDB.Types.Reducer, IReducerArgs + { + string IReducerArgs.ReducerName => "class.start_schedules"; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Tables/ScheduleResult.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Tables/ScheduleResult.g.cs new file mode 100644 index 00000000000..e844cce31fc --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Tables/ScheduleResult.g.cs @@ -0,0 +1,69 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@class +{ + public sealed partial class RemoteTables + { + public sealed class ScheduleResultHandle : RemoteTableHandle + { + public override string RemoteTableName => "class.schedule_result"; + internal static readonly global::SpacetimeDB.SqlTableName SqlName = new global::SpacetimeDB.SqlTableName("class", "schedule_result"); + protected override global::SpacetimeDB.SqlTableName RemoteSqlTableName => SqlName; + + public sealed class JobIdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(ScheduleResult row) => row.JobId; + + public JobIdUniqueIndex(ScheduleResultHandle table) : base(table) { } + } + + public readonly JobIdUniqueIndex JobId; + + internal ScheduleResultHandle(global::SpacetimeDB.Types.DbConnection conn) : base(conn) + { + JobId = new(this); + } + + protected override object GetPrimaryKey(ScheduleResult row) => row.JobId; + } + + public readonly ScheduleResultHandle ScheduleResult; + } + + public sealed class ScheduleResultCols + { + public global::SpacetimeDB.Col JobId { get; } + public global::SpacetimeDB.Col Payload { get; } + public global::SpacetimeDB.Col Kind { get; } + public global::SpacetimeDB.Col Executions { get; } + public global::SpacetimeDB.Col ScheduledId { get; } + + public ScheduleResultCols(global::SpacetimeDB.SqlTableName tableName) + { + JobId = new global::SpacetimeDB.Col(tableName, "job_id"); + Payload = new global::SpacetimeDB.Col(tableName, "payload"); + Kind = new global::SpacetimeDB.Col(tableName, "kind"); + Executions = new global::SpacetimeDB.Col(tableName, "executions"); + ScheduledId = new global::SpacetimeDB.Col(tableName, "scheduled_id"); + } + } + + public sealed class ScheduleResultIxCols + { + public global::SpacetimeDB.IxCol JobId { get; } + + public ScheduleResultIxCols(global::SpacetimeDB.SqlTableName tableName) + { + JobId = new global::SpacetimeDB.IxCol(tableName, "job_id"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Tables/User.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Tables/User.g.cs new file mode 100644 index 00000000000..b9e8f835939 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Tables/User.g.cs @@ -0,0 +1,63 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@class +{ + public sealed partial class RemoteTables + { + public sealed class UserHandle : RemoteTableHandle + { + public override string RemoteTableName => "class.user"; + internal static readonly global::SpacetimeDB.SqlTableName SqlName = new global::SpacetimeDB.SqlTableName("class", "user"); + protected override global::SpacetimeDB.SqlTableName RemoteSqlTableName => SqlName; + + public sealed class IdUniqueIndex : UniqueIndexBase + { + protected override uint GetKey(User row) => row.Id; + + public IdUniqueIndex(UserHandle table) : base(table) { } + } + + public readonly IdUniqueIndex Id; + + internal UserHandle(global::SpacetimeDB.Types.DbConnection conn) : base(conn) + { + Id = new(this); + } + + protected override object GetPrimaryKey(User row) => row.Id; + } + + public readonly UserHandle User; + } + + public sealed class UserCols + { + public global::SpacetimeDB.Col Id { get; } + public global::SpacetimeDB.Col Message { get; } + + public UserCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.Col(tableName, "id"); + Message = new global::SpacetimeDB.Col(tableName, "message"); + } + } + + public sealed class UserIxCols + { + public global::SpacetimeDB.IxCol Id { get; } + + public UserIxCols(global::SpacetimeDB.SqlTableName tableName) + { + Id = new global::SpacetimeDB.IxCol(tableName, "id"); + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/ProcedureJob.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/ProcedureJob.g.cs new file mode 100644 index 00000000000..d3fd05377ae --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/ProcedureJob.g.cs @@ -0,0 +1,43 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@class +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ProcedureJob + { + [DataMember(Name = "id")] + public ulong Id; + [DataMember(Name = "job_id")] + public uint JobId; + [DataMember(Name = "payload")] + public uint Payload; + [DataMember(Name = "due")] + public SpacetimeDB.ScheduleAt Due; + + public ProcedureJob( + ulong Id, + uint JobId, + uint Payload, + SpacetimeDB.ScheduleAt Due + ) + { + this.Id = Id; + this.JobId = JobId; + this.Payload = Payload; + this.Due = Due; + } + + public ProcedureJob() + { + this.Due = null!; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/ReducerJob.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/ReducerJob.g.cs new file mode 100644 index 00000000000..330424cf635 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/ReducerJob.g.cs @@ -0,0 +1,43 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@class +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ReducerJob + { + [DataMember(Name = "id")] + public ulong Id; + [DataMember(Name = "job_id")] + public uint JobId; + [DataMember(Name = "due")] + public SpacetimeDB.ScheduleAt Due; + [DataMember(Name = "payload")] + public uint Payload; + + public ReducerJob( + ulong Id, + uint JobId, + SpacetimeDB.ScheduleAt Due, + uint Payload + ) + { + this.Id = Id; + this.JobId = JobId; + this.Due = Due; + this.Payload = Payload; + } + + public ReducerJob() + { + this.Due = null!; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/ScheduleResult.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/ScheduleResult.g.cs new file mode 100644 index 00000000000..5994827df3c --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/ScheduleResult.g.cs @@ -0,0 +1,47 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@class +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class ScheduleResult + { + [DataMember(Name = "job_id")] + public uint JobId; + [DataMember(Name = "payload")] + public uint Payload; + [DataMember(Name = "kind")] + public string Kind; + [DataMember(Name = "executions")] + public uint Executions; + [DataMember(Name = "scheduled_id")] + public ulong ScheduledId; + + public ScheduleResult( + uint JobId, + uint Payload, + string Kind, + uint Executions, + ulong ScheduledId + ) + { + this.JobId = JobId; + this.Payload = Payload; + this.Kind = Kind; + this.Executions = Executions; + this.ScheduledId = ScheduledId; + } + + public ScheduleResult() + { + this.Kind = ""; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/User.g.cs b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/User.g.cs new file mode 100644 index 00000000000..7b1c4914ee6 --- /dev/null +++ b/sdks/csharp/examples~/regression-tests/namespaces/module_bindings/class/Types/User.g.cs @@ -0,0 +1,35 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types.@class +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class User + { + [DataMember(Name = "id")] + public uint Id; + [DataMember(Name = "message")] + public string Message; + + public User( + uint Id, + string Message + ) + { + this.Id = Id; + this.Message = Message; + } + + public User() + { + this.Message = ""; + } + } +} diff --git a/sdks/csharp/examples~/regression-tests/procedure-client/module_bindings/SpacetimeDBClient.g.cs b/sdks/csharp/examples~/regression-tests/procedure-client/module_bindings/SpacetimeDBClient.g.cs index 4bdf39df0a8..f769484f301 100644 --- a/sdks/csharp/examples~/regression-tests/procedure-client/module_bindings/SpacetimeDBClient.g.cs +++ b/sdks/csharp/examples~/regression-tests/procedure-client/module_bindings/SpacetimeDBClient.g.cs @@ -1,7 +1,7 @@ // 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.4 (commit dfc726be29516b8cdecc651f5c9705026a624a04). +// This was generated using spacetimedb cli version 2.10.1 (commit 7109fe86a665ba5404389ce72ffc63131bf576cc). #nullable enable diff --git a/sdks/csharp/examples~/regression-tests/republishing/client/module_bindings/SpacetimeDBClient.g.cs b/sdks/csharp/examples~/regression-tests/republishing/client/module_bindings/SpacetimeDBClient.g.cs index 446d0a75382..670d39676c5 100644 --- a/sdks/csharp/examples~/regression-tests/republishing/client/module_bindings/SpacetimeDBClient.g.cs +++ b/sdks/csharp/examples~/regression-tests/republishing/client/module_bindings/SpacetimeDBClient.g.cs @@ -1,7 +1,7 @@ // 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.0 (commit 4cce69765507c1815979d39572b4a52864f5c3d2). +// This was generated using spacetimedb cli version 2.10.1 (commit 7109fe86a665ba5404389ce72ffc63131bf576cc). #nullable enable diff --git a/sdks/csharp/src/Table.cs b/sdks/csharp/src/Table.cs index 680dfc11b52..3224b82d42a 100644 --- a/sdks/csharp/src/Table.cs +++ b/sdks/csharp/src/Table.cs @@ -176,6 +176,9 @@ internal class ParsedTableUpdate : IParsedTableUpdate public abstract string RemoteTableName { get; } string IRemoteTableHandle.RemoteTableName => RemoteTableName; + /// The SQL identifier, separate from the wire/cache key. + protected virtual SqlTableName RemoteSqlTableName => new(RemoteTableName); + /// /// Whether this table is an event table. /// Event tables don't persist rows in the client cache — they only fire insert callbacks. @@ -417,7 +420,7 @@ public event RowEventHandler OnInsert public IEnumerable Iter() => Entries.Values; public Task RemoteQuery(string query) => - conn.RemoteQuery($"SELECT {RemoteTableName}.* FROM {RemoteTableName} {query}"); + conn.RemoteQuery($"SELECT {RemoteSqlTableName}.* FROM {RemoteSqlTableName} {query}"); void InvokeInsert(IEventContext context, IStructuralReadWrite row) { @@ -451,7 +454,11 @@ void IRemoteTableHandle.PreApply(IEventContext context, IParsedTableUpdate parse { // Fully qualified to avoid clash with UnityEngine.Debug System.Diagnostics.Debug.Assert(wasInserted.Count == 0 && wasUpdated.Count == 0 && wasRemoved.Count == 0, "Call Apply and PostApply before calling PreApply again"); - if (IsEventTable) return; // Event tables have no deletes. + if (IsEventTable) + { + return; // Event tables have no deletes. + } + var delta = (ParsedTableUpdate)parsedTableUpdate; foreach (var (_, value) in Entries.WillRemove(delta.Delta)) { diff --git a/sdks/csharp/tests~/QueryBuilderTests.cs b/sdks/csharp/tests~/QueryBuilderTests.cs index 8b531c3cadd..e8df8c5f745 100644 --- a/sdks/csharp/tests~/QueryBuilderTests.cs +++ b/sdks/csharp/tests~/QueryBuilderTests.cs @@ -94,6 +94,42 @@ private static Table MakeRightTable(string tab new(tableName, new RightCols(tableName), new RightIxCols(tableName)); + [Fact] + public void QualifiedName_QuotesNamespaceAndLocalName() + { + var name = new SqlTableName("we\"ird.namespace", "users.with.dots"); + Assert.Equal("we\"ird.namespace", name.Namespace); + Assert.Equal("users.with.dots", name.LocalName); + Assert.Equal("\"we\"\"ird.namespace\".\"users.with.dots\"", name.ToString()); + Assert.Null(new SqlTableName("users").Namespace); + Assert.Equal("SELECT * FROM \"auth.users\"", MakeTable("auth.users").ToSql()); + Assert.Equal("\"auth.users\".\"id\"", new Col("auth.users", "id").ToString()); + Assert.Equal("\"auth.users\".\"id\"", new IxCol("auth.users", "id").ToString()); + } + + [Fact] + public void QualifiedName_FiltersAndBothSemijoinsKeepSameLeafNamesDistinct() + { + var leftName = new SqlTableName("auth", "users"); + var rightName = new SqlTableName("audit", "users"); + var left = new Table, IxCol>( + leftName, new(leftName, "id"), new(leftName, "id")); + var right = new Table, IxCol>( + rightName, new(rightName, "id"), new(rightName, "id")); + Assert.Equal("SELECT * FROM \"auth\".\"users\" WHERE (\"auth\".\"users\".\"id\" = 1)", + left.Where(c => c.Eq(1)).ToSql()); + Assert.Equal("SELECT * FROM \"auth\".\"users\" WHERE (\"auth\".\"users\".\"id\" = 1)", + left.Where((_, ix) => ix.Eq(SqlLit.Int(1))).ToSql()); + const string join = " FROM \"auth\".\"users\" JOIN \"audit\".\"users\" ON \"auth\".\"users\".\"id\" = \"audit\".\"users\".\"id\""; + Assert.Equal("SELECT \"auth\".\"users\".*" + join, + left.LeftSemijoin(right, (l, r) => l.Eq(r)).ToSql()); + Assert.Equal("SELECT \"audit\".\"users\".*" + join, + left.RightSemijoin(right, (l, r) => l.Eq(r)).ToSql()); + var escaped = new SqlTableName("auth\"data", "select"); + Assert.Equal("\"auth\"\"data\".\"select\".\"i\"\"d\"", new Col(escaped, "i\"d").ToString()); + Assert.Equal("\"auth\"\"data\".\"select\".\"i\"\"d\"", new IxCol(escaped, "i\"d").ToString()); + } + [Fact] public void All_QuotesTableName() { diff --git a/sdks/csharp/tests~/SnapshotTests.VerifySampleDump_dumpName=LegacySubscribeAll.verified.txt b/sdks/csharp/tests~/SnapshotTests.VerifySampleDump_dumpName=LegacySubscribeAll.verified.txt index 5ae3339cfaa..f961e0c49e4 100644 --- a/sdks/csharp/tests~/SnapshotTests.VerifySampleDump_dumpName=LegacySubscribeAll.verified.txt +++ b/sdks/csharp/tests~/SnapshotTests.VerifySampleDump_dumpName=LegacySubscribeAll.verified.txt @@ -106,10 +106,12 @@ }, Db: { Message: { + RemoteTableName: message, Count: 4 }, User: { Identity: {}, + RemoteTableName: user, Count: 3 } }, @@ -138,10 +140,12 @@ }, Db: { Message: { + RemoteTableName: message, Count: 4 }, User: { Identity: {}, + RemoteTableName: user, Count: 3 } }, @@ -170,10 +174,12 @@ }, Db: { Message: { + RemoteTableName: message, Count: 4 }, User: { Identity: {}, + RemoteTableName: user, Count: 3 } }, diff --git a/sdks/csharp/tests~/SnapshotTests.VerifySampleDump_dumpName=SubscribeApplied.verified.txt b/sdks/csharp/tests~/SnapshotTests.VerifySampleDump_dumpName=SubscribeApplied.verified.txt index 7dd87750886..1cefa360546 100644 --- a/sdks/csharp/tests~/SnapshotTests.VerifySampleDump_dumpName=SubscribeApplied.verified.txt +++ b/sdks/csharp/tests~/SnapshotTests.VerifySampleDump_dumpName=SubscribeApplied.verified.txt @@ -106,10 +106,12 @@ }, Db: { Message: { + RemoteTableName: message, Count: 4 }, User: { Identity: {}, + RemoteTableName: user, Count: 3 } }, @@ -138,10 +140,12 @@ }, Db: { Message: { + RemoteTableName: message, Count: 4 }, User: { Identity: {}, + RemoteTableName: user, Count: 3 } }, diff --git a/sdks/csharp/tools~/gen-regression-tests.sh b/sdks/csharp/tools~/gen-regression-tests.sh index d7bd005cf45..1bf296898b5 100755 --- a/sdks/csharp/tools~/gen-regression-tests.sh +++ b/sdks/csharp/tools~/gen-regression-tests.sh @@ -86,3 +86,7 @@ fi cargo spacetime generate -y -l csharp -o "$SDK_PATH/examples~/regression-tests/client/module_bindings" --module-path "$SDK_PATH/examples~/regression-tests/server" "${BUILD_OPTIONS[@]}" cargo spacetime generate -y -l csharp -o "$SDK_PATH/examples~/regression-tests/republishing/client/module_bindings" --module-path "$SDK_PATH/examples~/regression-tests/republishing/server-republish" "${BUILD_OPTIONS[@]}" cargo spacetime generate -y -l csharp -o "$SDK_PATH/examples~/regression-tests/procedure-client/module_bindings" --module-path "$STDB_PATH/modules/sdk-test-procedure" "${BUILD_OPTIONS[@]}" + +if [ -z "$DOTNET_VERSION" ] || [ "$DOTNET_VERSION" = "10" ]; then + cargo spacetime generate -y -l csharp -o "$SDK_PATH/examples~/regression-tests/namespaces/module_bindings" --module-path "$STDB_PATH/modules/namespace-test-cs" --build-options="--dotnet-version 10" +fi diff --git a/sdks/csharp/tools~/run-regression-tests.sh b/sdks/csharp/tools~/run-regression-tests.sh index 8415f319ee7..f801a9b39f6 100644 --- a/sdks/csharp/tools~/run-regression-tests.sh +++ b/sdks/csharp/tools~/run-regression-tests.sh @@ -92,10 +92,11 @@ configure_csharp_modules_sdk() { run_client() { local dir="$1" local dotnet_version="$2" + shift 2 if [ "$dotnet_version" = "10" ]; then - (cd "$dir" && EXPERIMENTAL_WASM_AOT=1 dotnet run -c Debug) + (cd "$dir" && EXPERIMENTAL_WASM_AOT=1 dotnet run -c Debug "$@") else - (cd "$dir" && env -u EXPERIMENTAL_WASM_AOT dotnet run -c Debug) + (cd "$dir" && env -u EXPERIMENTAL_WASM_AOT dotnet run -c Debug "$@") fi } @@ -130,4 +131,13 @@ for dotnet_version in "${DOTNET_VERSIONS[@]}"; do run_client "$SDK_PATH/examples~/regression-tests/client" "$dotnet_version" run_client "$SDK_PATH/examples~/regression-tests/republishing/client" "$dotnet_version" run_client "$SDK_PATH/examples~/regression-tests/procedure-client" "$dotnet_version" + + if [ "$dotnet_version" = "10" ]; then + # The module needs .NET 10; test its C# 9 bindings on both client runtimes. + for client_version in 8 10; do + echo "Running namespace client with .NET $client_version against the .NET 10 module" + cargo spacetime publish --dotnet-version 10 -c -y --server "$SPACETIMEDB_SERVER_URL" -p "$STDB_PATH/modules/namespace-test-cs" namespace-tests + run_client "$SDK_PATH/examples~/regression-tests/namespaces" "$client_version" --framework "net$client_version.0" + done + fi done