diff --git a/Directory.Packages.props b/Directory.Packages.props index bd55253198..027584ef8b 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -19,7 +19,6 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - diff --git a/docs/configuration/aot-publishing.md b/docs/configuration/aot-publishing.md index 6b57680d83..9d7cd390ba 100644 --- a/docs/configuration/aot-publishing.md +++ b/docs/configuration/aot-publishing.md @@ -42,7 +42,7 @@ Marten's storage / projection / compiled-query surfaces all build their dispatch - **No `dotnet run -- codegen write` step.** If you have an `Internal/Generated/` folder committed from a pre-9.0 Marten app, delete it and remove it from `.gitignore`. Nothing reads or writes those files. - **No `services.AddRuntimeCompilation()` call.** PR [#4461](https://github.com/JasperFx/marten/pull/4461) ripped out the runtime-codegen seam entirely. Don't add it back. -- **`StoreOptions.GeneratedCodeMode`, `AllowRuntimeCodeGeneration`, `SourceCodeWritingEnabled`, `GeneratedCodeOutputPath`** are kept on the API surface as `[Obsolete]` no-ops so existing bootstrapping compiles unchanged. Setting them has no effect in Marten 9 — they're documented for source-compatibility only. +- **`StoreOptions.GeneratedCodeMode`, `AllowRuntimeCodeGeneration`, `SourceCodeWritingEnabled`, `GeneratedCodeOutputPath`** have been deleted entirely — references to them will fail to compile against Marten 9.0. Remove any leftover assignments from your bootstrapping. `StoreOptions.ApplicationAssembly` survives because `AutoRegister` and `TryUseSourceGeneratedDiscovery` still use it as a scan hint. If you have a Wolverine app sitting next to your Marten app in the same composition root, the Wolverine side **does** still use the JasperFx two-phase model — Wolverine retains runtime codegen as an opt-in seam ([per the 2026 plan](https://github.com/JasperFx/jasperfx/issues/217)). The JasperFx guide is the authoritative reference for the Wolverine half of that story. diff --git a/docs/configuration/cli.md b/docs/configuration/cli.md index b2768f312a..d817b31cb4 100644 --- a/docs/configuration/cli.md +++ b/docs/configuration/cli.md @@ -130,16 +130,11 @@ dotnet run -- db-dump -d Marten ./marten.sql ### Codegen ::: warning Marten 9.0 -Marten 9.0 retired the Roslyn-driven runtime code-generation pipeline (`JasperFx.RuntimeCompiler`). -The `codegen` family of subcommands is still exposed by the shared JasperFx CLI for other -Critter-Stack tools, but it has no Marten artifacts to write or compare against — every -document-storage, event-storage, compiled-query, and secondary-store surface ships as -hand-written, closed-shape code or as `Marten.SourceGenerator`-emitted output under `obj/`. - -Existing applications that committed an `Internal/Generated/` folder pre-9.0 should delete it -and remove it from `.gitignore`; nothing reads or writes those files anymore. See -[Runtime code generation removed](/migration-guide#runtime-code-generation-removed) for the -full migration story. +Marten 9.0 completely removed its runtime code-generation pipeline (PR [#4461](https://github.com/JasperFx/marten/pull/4461)). **`dotnet run -- codegen write` is no longer necessary for Marten** — there are no Marten artifacts to write or pre-generate. If you committed an `Internal/Generated/` folder pre-9.0, delete it and remove it from `.gitignore`; nothing reads or writes those files anymore. + +The `codegen` family of subcommands is still surfaced by the shared JasperFx CLI for other Critter-Stack tools (Wolverine, for example), so the command itself may still run successfully against a host that registers those tools. It just won't do anything on Marten's behalf. + +See [Runtime code generation removed](/migration-guide#runtime-code-generation-removed) for the full migration story. ::: ## Outside the Dotnet CLI diff --git a/docs/configuration/hostbuilder.md b/docs/configuration/hostbuilder.md index 3f156707bc..c62b4f3a02 100644 --- a/docs/configuration/hostbuilder.md +++ b/docs/configuration/hostbuilder.md @@ -99,11 +99,10 @@ services.AddMarten(opts => // automatic database migrations and dynamic code generation services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); ``` -snippet source | anchor +snippet source | anchor Lastly, if you prefer, you can pass a Marten `StoreOptions` object to `AddMarten()` like this example: @@ -123,11 +122,10 @@ services.AddMarten(options); // automatic database migrations and dynamic code generation services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); ``` -snippet source | anchor +snippet source | anchor ## Using NpgsqlDataSource @@ -152,7 +150,7 @@ services.AddMarten() .UseLightweightSessions() .UseNpgsqlDataSource(); ``` -snippet source | anchor +snippet source | anchor If you're on .NET 8 (and above), you can also use a dedicated [keyed registration](https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-8#keyed-di-services). This can be useful for scenarios where you need more than one data source registered: @@ -168,7 +166,7 @@ services.AddMarten() .UseLightweightSessions() .UseNpgsqlDataSource(dataSourceKey); ``` -snippet source | anchor +snippet source | anchor ## Using a Multi-Host Data Source @@ -194,7 +192,7 @@ services.AddMarten(x => .UseLightweightSessions() .UseNpgsqlDataSource(); ``` -snippet source | anchor +snippet source | anchor ::: warning @@ -269,7 +267,7 @@ public interface IConfigureMarten void Configure(IServiceProvider services, StoreOptions options); } ``` -snippet source | anchor +snippet source | anchor You could alternatively implement a custom `IConfigureMarten` (or `IConfigureMarten where T : IDocumentStore` if you're working with multiple databases class like so: @@ -333,7 +331,7 @@ public interface IAsyncConfigureMarten ValueTask Configure(StoreOptions options, CancellationToken cancellationToken); } ``` -snippet source | anchor +snippet source | anchor As an example from the tests, here's a custom version that uses the Feature Management service: @@ -435,7 +433,7 @@ public class CustomSessionFactory: ISessionFactory } } ``` -snippet source | anchor +snippet source | anchor To register the custom session factory, use the `BuildSessionsWith()` method as shown in this example: @@ -458,11 +456,10 @@ services.AddMarten(opts => // automatic database migrations and dynamic code generation services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); ``` -snippet source | anchor +snippet source | anchor The session factories can also be used to build out and attach custom `IDocumentSessionListener` objects or replace the logging as we'll see in the next section. @@ -484,7 +481,7 @@ public interface ISession Guid CorrelationId { get; set; } } ``` -snippet source | anchor +snippet source | anchor And a custom Marten session logger to add the correlation identifier to the log output like this: @@ -544,7 +541,7 @@ public class CorrelatedMartenLogger: IMartenSessionLogger } } ``` -snippet source | anchor +snippet source | anchor Now, let's move on to building out a custom session factory that will attach our correlated marten logger to sessions being resolved from the IoC container: @@ -584,7 +581,7 @@ public class ScopedSessionFactory: ISessionFactory } } ``` -snippet source | anchor +snippet source | anchor Lastly, let's register our new session factory, but this time we need to take care to register the session factory as `Scoped` in the underlying container so we're using the correct `ISession` at runtime: @@ -606,11 +603,10 @@ services.AddMarten(opts => services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); ``` -snippet source | anchor +snippet source | anchor ::: tip @@ -645,7 +641,7 @@ public interface IInvoicingStore : IDocumentStore } ``` -snippet source | anchor +snippet source | anchor A couple notes on the interface: @@ -683,15 +679,14 @@ using var host = Host.CreateDefaultBuilder() .InitializeWith(new DefaultDataSet()); // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation + // automatic database migrations services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); }).StartAsync(); ``` -snippet source | anchor +snippet source | anchor At runtime we can inject an instance of our new `IInvoicingStore` and work with it like any other @@ -721,7 +716,7 @@ public class InvoicingService } } ``` -snippet source | anchor +snippet source | anchor ### Session Configuration for Ancillary Stores @@ -756,7 +751,7 @@ using var host = Host.CreateDefaultBuilder() // .BuildSessionsWith(); }).StartAsync(); ``` -snippet source | anchor +snippet source | anchor You can resolve the keyed `ISessionFactory` for an ancillary store directly from the DI container if needed: diff --git a/docs/configuration/optimized_artifact_workflow.md b/docs/configuration/optimized_artifact_workflow.md index c0e71123e5..2eb7f6ee1d 100644 --- a/docs/configuration/optimized_artifact_workflow.md +++ b/docs/configuration/optimized_artifact_workflow.md @@ -10,13 +10,9 @@ let developers just get things done without having to spend a lot of time fiddli scripts or ORM configuration. To that end, the default configuration for Marten is optimized for immediate developer productivity: - - ```cs var store = DocumentStore.For("connection string"); ``` -snippet source | anchor - In the configuration above, as needed, behind the scenes Marten is checking the underlying database to see whether the existing database schema matches the @@ -30,15 +26,7 @@ database migrations require a little bit of in-memory locking in the Marten code that has been problematic for folks using Marten from Blazor. ::: tip Marten 9.0 -The Roslyn runtime code-generation path and the `TypeLoadMode` switch that -controlled it were retired in Marten 9.0. The closed-shape document storage -hierarchy, the source generator for compiled queries (with a reflection-built -fallback), and a small `System.Reflection.Emit` shim for secondary stores -replace what `JasperFx.RuntimeCompiler` used to handle. `StoreOptions.GeneratedCodeMode`, -`StoreOptions.ApplicationAssembly`, `StoreOptions.SourceCodeWritingEnabled`, and -`StoreOptions.GeneratedCodeOutputPath` are still on the surface for source- -compatibility but are no-ops. `CritterStackDefaults` still controls the -`ResourceAutoCreate` half of the per-environment workflow. +The Roslyn runtime code-generation path was completely removed in Marten 9.0 (PR [#4461](https://github.com/JasperFx/marten/pull/4461)). The `StoreOptions.GeneratedCodeMode`, `StoreOptions.SourceCodeWritingEnabled`, `StoreOptions.GeneratedCodeOutputPath`, and `StoreOptions.AllowRuntimeCodeGeneration` properties have been **deleted** — remove any references to them from your bootstrapping. If you have an `Internal/Generated/` folder committed from a pre-9.0 Marten app, delete it and remove it from `.gitignore` — nothing reads or writes those files anymore. `CritterStackDefaults` still controls the `ResourceAutoCreate` half of the per-environment workflow, which is the remaining concern this page covers. ::: To allow for maximum developer productivity while using more efficient production @@ -51,8 +39,6 @@ options and how `ResourceAutoCreate` is resolved from `JasperFxOptions`, see the [JasperFx shared libraries documentation](https://shared-libs.jasperfx.net/). ::: - - ```cs using var host = await Host.CreateDefaultBuilder() .ConfigureServices(services => @@ -60,20 +46,15 @@ using var host = await Host.CreateDefaultBuilder() services.AddMarten("connection string"); // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation + // automatic database migrations. services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); }).StartAsync(); ``` -snippet source | anchor - -The `GeneratedCodeMode` line in that sample is a no-op in Marten 9.0 — it's -retained only so existing application bootstrapping compiles unchanged. The -effective behavior per environment is now driven entirely by `ResourceAutoCreate`: +The effective behavior per environment is driven entirely by `ResourceAutoCreate`: * In `Development`: `StoreOptions.AutoCreateSchemaObjects = AutoCreate.CreateOrUpdate` to detect and apply database schema migrations as needed. * In `Production`: `StoreOptions.AutoCreateSchemaObjects = AutoCreate.None` to short-circuit any kind of automatic database change detection and migration at runtime. This is also a minor performance optimization that sidesteps potential locking issues. diff --git a/docs/configuration/storeoptions.md b/docs/configuration/storeoptions.md index 60fb8636fb..2076d9692d 100644 --- a/docs/configuration/storeoptions.md +++ b/docs/configuration/storeoptions.md @@ -15,7 +15,7 @@ public static DocumentStore For(Action configure) return new DocumentStore(options); } ``` -snippet source | anchor +snippet source | anchor The major parts of `StoreOptions` are shown in the class diagram below: @@ -211,7 +211,7 @@ public class ConfiguresItself } } ``` -snippet source | anchor +snippet source | anchor The `DocumentMapping` type is the core configuration class representing how a document type is persisted or @@ -235,7 +235,7 @@ public class ConfiguresItselfSpecifically } } ``` -snippet source | anchor +snippet source | anchor ## Document Policies @@ -337,5 +337,5 @@ var store = DocumentStore.For(_ => _.NameDataLength = 100; }); ``` -snippet source | anchor +snippet source | anchor diff --git a/docs/devops/devops.md b/docs/devops/devops.md index b89085cfaf..755e3953b1 100644 --- a/docs/devops/devops.md +++ b/docs/devops/devops.md @@ -78,14 +78,16 @@ Of course, it is fully up to you how you want to configure grate or if you want ## Application project set-up -How you set-up your csproj is all up to you, but for this example you'll need to opt into the JasperFx command line execution that is bundled -with Marten so we can export migrations to the migration project in a later step and pre generate code. To that end, the latest line in your `program.cs` needs to be: +How you set-up your csproj is all up to you, but for this example you'll need to opt into the JasperFx command line execution that is bundled +with Marten so we can export migrations to the migration project in a later step. To that end, the latest line in your `program.cs` needs to be: ```cs return await app.RunJasperFxCommands(args); ``` -The dockerfile will include a step that writes the generated code by executing `dotnet run -- codegen write`. +::: tip Marten 9.0 +Pre-Marten-9.0 versions of this guide ran `dotnet run -- codegen write` inside the build stage to pre-generate runtime code. Marten 9.0 removed its Roslyn runtime code-generation pipeline entirely (PR [#4461](https://github.com/JasperFx/marten/pull/4461)), so the step is no longer needed for Marten. If you still use Wolverine or another JasperFx-family tool that ships its own codegen, see the equivalent guidance in those projects' DevOps docs. +::: ```dockerfile FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build @@ -99,7 +101,6 @@ COPY ["Application/Application.csproj", "Application/"] COPY . . WORKDIR "/src/Application" -RUN dotnet run -- codegen write RUN dotnet publish "Application.csproj" -c Release -o /app/publish /p:UseAppHost=false FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine AS runtime diff --git a/docs/diagnostics.md b/docs/diagnostics.md index 2a3d2bc7a7..ebb2297aa2 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -365,7 +365,7 @@ var store = DocumentStore.For(_ => _.Logger(new ConsoleMartenLogger()); }); ``` -snippet source | anchor +snippet source | anchor You can also directly apply a session logger to any `IQuerySession` or `IDocumentSession` like this: @@ -377,7 +377,7 @@ using var session = store.LightweightSession(); // Replace the logger for only this one session session.Logger = new RecordingLogger(); ``` -snippet source | anchor +snippet source | anchor The session logging is a different abstraction specifically so that you _could_ track database commands issued per session. In effect, my own shop is going to use this capability to understand what HTTP endpoints or service bus message handlers are being unnecessarily chatty in their database interactions. We also hope that the contextual logging of commands per document session makes it easier to understand how our systems behave. diff --git a/docs/documents/identity.md b/docs/documents/identity.md index 5ce1c6d233..68f105d1fa 100644 --- a/docs/documents/identity.md +++ b/docs/documents/identity.md @@ -260,16 +260,9 @@ A custom ID generator strategy should implement [IIdGeneration](https://github.c public class CustomIdGeneration : IIdGeneration { public bool IsNumeric { get; } = false; - public void GenerateCode(GeneratedMethod assign, DocumentMapping mapping) - { - var document = new Use(mapping.DocumentType); - assign.Frames.Code($"_setter({{0}}, \"newId\");", document); - assign.Frames.Code($"return {{0}}.{mapping.CodeGen.AccessId};", document); - } - } ``` -snippet source | anchor +snippet source | anchor The `Build()` method should return the actual `IdGenerator` for the document type, where `T` is the type of the Id field. @@ -295,7 +288,7 @@ It is also possible define a custom id generation algorithm for a specific docum ```cs options.Schema.For().IdStrategy(new CustomIdGeneration()); ``` -snippet source | anchor +snippet source | anchor ## Strong Typed Identifiers @@ -337,7 +330,7 @@ public readonly struct Task2Id public static Task2Id From(Guid value) => new Task2Id(value); } ``` -snippet source | anchor +snippet source | anchor In _all_ cases, the type name will have to be suffixed with "Id" (and it's case sensitive) to be considered by Marten to be @@ -367,7 +360,7 @@ public class Invoice public string Name { get; set; } } ``` -snippet source | anchor +snippet source | anchor The usage of our `Invoice` document is essentially the same as a document type with the primitive identifier types: @@ -394,7 +387,7 @@ public async Task update_a_document_smoke_test() loaded.Name.ShouldBeNull("updated"); } ``` -snippet source | anchor +snippet source | anchor ::: tip @@ -515,7 +508,7 @@ public async Task include_a_single_reference() list.Single().Id.ShouldBe(teacher.Id); } ``` -snippet source | anchor +snippet source | anchor * Within LINQ `Where()` clauses diff --git a/docs/documents/sessions.md b/docs/documents/sessions.md index 778c00bc71..801ee062dc 100644 --- a/docs/documents/sessions.md +++ b/docs/documents/sessions.md @@ -327,7 +327,7 @@ public void ConfigureCommandTimeout(IDocumentStore store) } } ``` -snippet source | anchor +snippet source | anchor ## Unit of Work Mechanics diff --git a/docs/documents/storage.md b/docs/documents/storage.md index d052d8e7a2..10096f749d 100644 --- a/docs/documents/storage.md +++ b/docs/documents/storage.md @@ -55,7 +55,7 @@ public class Customer [Identity] public string Name { get; set; } } ``` -snippet source | anchor +snippet source | anchor ## Type Aliases diff --git a/docs/events/appending.md b/docs/events/appending.md index b892ab3655..dafe2eb464 100644 --- a/docs/events/appending.md +++ b/docs/events/appending.md @@ -144,7 +144,7 @@ session.Events.Append(id, joined, departed); await session.SaveChangesAsync(); ``` -snippet source | anchor +snippet source | anchor ## Mandatory Stream Types diff --git a/docs/events/multitenancy.md b/docs/events/multitenancy.md index 5cc00562a9..509a1aa81f 100644 --- a/docs/events/multitenancy.md +++ b/docs/events/multitenancy.md @@ -31,7 +31,7 @@ Let's start with a possible implementation of a single stream projection: ```cs -public class SpecialCounterProjection: SingleStreamProjection +public partial class SpecialCounterProjection: SingleStreamProjection { public void Apply(SpecialCounter c, SpecialA _) => c.ACount++; public void Apply(SpecialCounter c, SpecialB _) => c.BCount++; @@ -48,7 +48,7 @@ Or this equivalent, but see how I'm explicitly registering event types, because ```cs -public class SpecialCounterProjection2: SingleStreamProjection +public partial class SpecialCounterProjection2: SingleStreamProjection { public SpecialCounterProjection2() { diff --git a/docs/events/optimizing.md b/docs/events/optimizing.md index 6aebc8796b..461f871c6a 100644 --- a/docs/events/optimizing.md +++ b/docs/events/optimizing.md @@ -62,7 +62,7 @@ like so: ```cs -public class DayProjection: MultiStreamProjection +public partial class DayProjection: MultiStreamProjection { public DayProjection() { diff --git a/docs/events/projections/composite.md b/docs/events/projections/composite.md index fa7c0213e8..84d2badb46 100644 --- a/docs/events/projections/composite.md +++ b/docs/events/projections/composite.md @@ -90,7 +90,7 @@ First, let's just look at the simple `ProviderShiftProjection`: ```cs -public class ProviderShiftProjection: SingleStreamProjection +public partial class ProviderShiftProjection: SingleStreamProjection { public ProviderShiftProjection() { @@ -169,7 +169,7 @@ ultimately need to use the build products of all three upstream projections: ```cs -public class AppointmentDetailsProjection: MultiStreamProjection +public partial class AppointmentDetailsProjection: MultiStreamProjection { public AppointmentDetailsProjection() { @@ -367,7 +367,7 @@ And also the definition for the downstream `BoardSummary` view: ```cs -public class BoardSummaryProjection: MultiStreamProjection +public partial class BoardSummaryProjection: MultiStreamProjection { public BoardSummaryProjection() { diff --git a/docs/events/projections/conventions.md b/docs/events/projections/conventions.md index 220cd569bd..5c38f84f5f 100644 --- a/docs/events/projections/conventions.md +++ b/docs/events/projections/conventions.md @@ -64,7 +64,7 @@ public class Trip internal bool ShouldDelete(VacationOver e) => Traveled > 1000; } ``` -snippet source | anchor +snippet source | anchor Or finally, you can use a method named `Create()` on a projection type as shown in this sample: @@ -96,14 +96,12 @@ public partial class TripProjection: SingleStreamProjection return new Trip { Id = started.StreamId, StartedOn = started.Data.Day, Active = true }; } - // ShouldDelete method-convention overloads — replace the pre-9.0 - // DeleteEvent() / DeleteEvent(predicate) constructor helpers. public bool ShouldDelete(TripAborted _) => true; public bool ShouldDelete(Breakdown e) => e.IsCritical; public bool ShouldDelete(VacationOver _, Trip trip) => trip.Traveled > 1000; } ``` -snippet source | anchor +snippet source | anchor The `Create()` method has to return either the aggregate document type or `Task` where `T` is the aggregate document type. There must be an argument for the specific event type or `IEvent` where `T` is the event type if you need access to event metadata. You can also take in an `IQuerySession` if you need to look up additional data as part of the transformation or `IEvent` in addition to the exact event type just to get at event metadata. @@ -144,14 +142,12 @@ public partial class TripProjection: SingleStreamProjection return new Trip { Id = started.StreamId, StartedOn = started.Data.Day, Active = true }; } - // ShouldDelete method-convention overloads — replace the pre-9.0 - // DeleteEvent() / DeleteEvent(predicate) constructor helpers. public bool ShouldDelete(TripAborted _) => true; public bool ShouldDelete(Breakdown e) => e.IsCritical; public bool ShouldDelete(VacationOver _, Trip trip) => trip.Traveled > 1000; } ``` -snippet source | anchor +snippet source | anchor The `Apply()` methods can accept any combination of these arguments: @@ -182,7 +178,7 @@ aggregate projection type: ```cs -public class TripProjection: SingleStreamProjection +public partial class TripProjection: SingleStreamProjection { public TripProjection() { @@ -201,7 +197,7 @@ and maybe even other document state in your Marten database, you can use the `Sh ```cs -public class TripProjection: SingleStreamProjection +public partial class TripProjection: SingleStreamProjection { // The current Trip aggregate would be deleted if // the Breakdown event is "critical" diff --git a/docs/events/projections/enrichment.md b/docs/events/projections/enrichment.md index 898c5a0801..98a2665c5d 100644 --- a/docs/events/projections/enrichment.md +++ b/docs/events/projections/enrichment.md @@ -103,7 +103,7 @@ as a way of wringing more performance and scalability out of your Marten usage! ```cs -public class UserTaskProjection: SingleStreamProjection +public partial class UserTaskProjection: SingleStreamProjection { // This is where you have a hook to "enrich" event data *after* slicing, // but before processing diff --git a/docs/events/projections/explicit.md b/docs/events/projections/explicit.md index 5a2b5f15ae..b25aa368f8 100644 --- a/docs/events/projections/explicit.md +++ b/docs/events/projections/explicit.md @@ -19,7 +19,7 @@ through only the event data: ```cs -public class AppointmentProjection: SingleStreamProjection +public partial class AppointmentProjection: SingleStreamProjection { public AppointmentProjection() { @@ -124,7 +124,7 @@ data (because users have absolutely wanted to do that over the years): ```cs -public class StartAndStopProjection: SingleStreamProjection +public partial class StartAndStopProjection: SingleStreamProjection { public StartAndStopProjection() { @@ -199,7 +199,7 @@ and another example: ```cs -public class HardDeletedStartAndStopProjection: SingleStreamProjection +public partial class HardDeletedStartAndStopProjection: SingleStreamProjection { public HardDeletedStartAndStopProjection() { diff --git a/docs/events/projections/multi-stream-projections.md b/docs/events/projections/multi-stream-projections.md index 298a1a69ab..057c7561c3 100644 --- a/docs/events/projections/multi-stream-projections.md +++ b/docs/events/projections/multi-stream-projections.md @@ -170,7 +170,7 @@ Here's a simple example of creating an aggregated view by user id: ```cs -public class UserGroupsAssignmentProjection: MultiStreamProjection +public partial class UserGroupsAssignmentProjection: MultiStreamProjection { public UserGroupsAssignmentProjection() { @@ -198,7 +198,7 @@ we care about and use this: ```cs -public class UserGroupsAssignmentProjection2: MultiStreamProjection +public partial class UserGroupsAssignmentProjection2: MultiStreamProjection { public UserGroupsAssignmentProjection2() { @@ -227,7 +227,7 @@ As of Marten V7, you can also use `IEvent` metadata as part of creating the iden ```cs -public class CustomerInsightsProjection : MultiStreamProjection +public partial class CustomerInsightsProjection : MultiStreamProjection { public CustomerInsightsProjection() @@ -258,7 +258,7 @@ shown below: ```cs -public class UserGroupsAssignmentProjection: MultiStreamProjection +public partial class UserGroupsAssignmentProjection: MultiStreamProjection { public UserGroupsAssignmentProjection() { @@ -329,7 +329,7 @@ public class LicenseFeatureToggledEventGrouper: IAggregateGrouper } // projection with documentsession -public class UserFeatureTogglesProjection: MultiStreamProjection +public partial class UserFeatureTogglesProjection: MultiStreamProjection { public UserFeatureTogglesProjection() { @@ -414,7 +414,7 @@ public class ExternalAccountLink public required Guid CustomerId { get; set; } } -public class ExternalAccountLinkProjection: SingleStreamProjection +public partial class ExternalAccountLinkProjection: SingleStreamProjection { public void Apply(CustomerLinkedToExternalAccount e, ExternalAccountLink link) { @@ -479,7 +479,7 @@ public class CustomerBillingMetrics public HashSet ModesSeen { get; set; } = []; } -public class CustomerBillingProjection: MultiStreamProjection +public partial class CustomerBillingProjection: MultiStreamProjection { public CustomerBillingProjection() { @@ -565,7 +565,7 @@ public class CustomerBillingMetrics public int ShippingLabels { get; set; } } -public class CustomerBillingProjection: MultiStreamProjection +public partial class CustomerBillingProjection: MultiStreamProjection { public CustomerBillingProjection() { @@ -659,7 +659,7 @@ public class ExternalAccountLink public required Guid CustomerId { get; set; } } -public class ExternalAccountLinkProjection: SingleStreamProjection +public partial class ExternalAccountLinkProjection: SingleStreamProjection { public void Apply(CustomerLinkedToExternalAccount e, ExternalAccountLink link) { @@ -722,7 +722,7 @@ public class BatchAwareExternalAccountGrouper: IAggregateGrouper } } -public class CustomerBillingProjection: MultiStreamProjection +public partial class CustomerBillingProjection: MultiStreamProjection { public CustomerBillingProjection() { @@ -841,7 +841,7 @@ public class CustomerBillingMetrics public required int Items { get; set; } } -public class CustomerBillingProjection: MultiStreamProjection +public partial class CustomerBillingProjection: MultiStreamProjection { public CustomerBillingProjection() { @@ -880,7 +880,7 @@ tenant id and make that the identity of the projected document. That usage is sh ```cs -public class RollupProjection: MultiStreamProjection +public partial class RollupProjection: MultiStreamProjection { public RollupProjection() { @@ -929,7 +929,7 @@ In a sample `ViewProjection`, we do a "fan out" of the `Travel.Movements` member ```cs -public class DayProjection: MultiStreamProjection +public partial class DayProjection: MultiStreamProjection { public DayProjection() { @@ -1015,7 +1015,7 @@ The `MonthlyAllocationProjection` class uses a custom grouper for this transform ```cs -public class MonthlyAllocationProjection: MultiStreamProjection +public partial class MonthlyAllocationProjection: MultiStreamProjection { public MonthlyAllocationProjection() { @@ -1173,7 +1173,7 @@ The key technique is `Identity>()` which gives you access to both the ```cs -public class MonthlyAccountActivityProjection : MultiStreamProjection +public partial class MonthlyAccountActivityProjection : MultiStreamProjection { public MonthlyAccountActivityProjection() { diff --git a/docs/events/projections/rebuilding.md b/docs/events/projections/rebuilding.md index 3b4baab803..7a5643644b 100644 --- a/docs/events/projections/rebuilding.md +++ b/docs/events/projections/rebuilding.md @@ -10,7 +10,7 @@ For example, if we have this projection: ```cs -public class ShopProjection: SingleStreamProjection +public partial class ShopProjection: SingleStreamProjection { public ShopProjection() { diff --git a/docs/events/projections/side-effects.md b/docs/events/projections/side-effects.md index bdfdb6ba8e..42740b51f5 100644 --- a/docs/events/projections/side-effects.md +++ b/docs/events/projections/side-effects.md @@ -26,7 +26,7 @@ Here's an example of that method overridden in a projection: ```cs -public class TripProjection: SingleStreamProjection +public partial class TripProjection: SingleStreamProjection { // Access event metadata through IEvent public Trip Create(IEvent @event) diff --git a/docs/events/projections/single-stream-projections.md b/docs/events/projections/single-stream-projections.md index de5c521181..f9398e8a7d 100644 --- a/docs/events/projections/single-stream-projections.md +++ b/docs/events/projections/single-stream-projections.md @@ -121,14 +121,12 @@ public partial class TripProjection: SingleStreamProjection return new Trip { Id = started.StreamId, StartedOn = started.Data.Day, Active = true }; } - // ShouldDelete method-convention overloads — replace the pre-9.0 - // DeleteEvent() / DeleteEvent(predicate) constructor helpers. public bool ShouldDelete(TripAborted _) => true; public bool ShouldDelete(Breakdown e) => e.IsCritical; public bool ShouldDelete(VacationOver _, Trip trip) => trip.Traveled > 1000; } ``` -snippet source | anchor +snippet source | anchor And register that projection like this: @@ -171,7 +169,7 @@ Here's a simple example of explicit code in projections: ```cs -public class AppointmentProjection: SingleStreamProjection +public partial class AppointmentProjection: SingleStreamProjection { public AppointmentProjection() { @@ -234,7 +232,7 @@ the possibility of soft deleting and later "un-deleting" the projected document ```cs -public class StartAndStopProjection: SingleStreamProjection +public partial class StartAndStopProjection: SingleStreamProjection { public StartAndStopProjection() { diff --git a/docs/events/projections/using-metadata.md b/docs/events/projections/using-metadata.md index 30af6b053d..1216426270 100644 --- a/docs/events/projections/using-metadata.md +++ b/docs/events/projections/using-metadata.md @@ -64,7 +64,7 @@ Below is a small example of accessing event metadata during aggregation: ```cs -public class TripProjection: SingleStreamProjection +public partial class TripProjection: SingleStreamProjection { // Access event metadata through IEvent public Trip Create(IEvent @event) @@ -169,7 +169,7 @@ public record ItemWorked; public record ItemFinished; -public class ItemProjection: SingleStreamProjection +public partial class ItemProjection: SingleStreamProjection { public void Apply(Item item, ItemStarted started) { diff --git a/docs/events/quickstart.md b/docs/events/quickstart.md index 7c665746f0..883df0a818 100644 --- a/docs/events/quickstart.md +++ b/docs/events/quickstart.md @@ -110,7 +110,7 @@ What about the quest itself? On top of seeing our in-progress quest, we also wan ```cs public sealed record Quest(Guid Id, List Members, List Slayed, string Name, bool isFinished); -public sealed class QuestProjection: SingleStreamProjection +public sealed partial class QuestProjection: SingleStreamProjection { public static Quest Create(QuestStarted started) => new(started.QuestId, [], [], started.Name, false); public static Quest Apply(MembersJoined joined, Quest party) => diff --git a/docs/migration-guide.md b/docs/migration-guide.md index 86fe0d479e..b6829cb6f1 100644 --- a/docs/migration-guide.md +++ b/docs/migration-guide.md @@ -243,8 +243,8 @@ What was replaced: What that means for application code: -* **No more `dotnet run -- codegen write` step.** Pre-built `Internal/Generated/` folders are obsolete — delete them from your project and `.gitignore`. The closed-shape paths build their descriptors at first use (cheap) and cache them; there is no compile-on-cold-start. -* **The `[Obsolete]` knobs stay on the surface as no-ops** so existing bootstrapping compiles unchanged: `StoreOptions.GeneratedCodeMode`, `StoreOptions.ApplicationAssembly`, `StoreOptions.SourceCodeWritingEnabled`, `StoreOptions.GeneratedCodeOutputPath`, `StoreOptions.AllowRuntimeCodeGeneration`, and `opts.Events.UseClosedShapeStorage` (which was an opt-in flag in 9.0-alpha; the closed-shape path is now the only path). None of them do anything at runtime — remove them at your convenience. +* **No more `dotnet run -- codegen write` step for Marten.** Pre-built `Internal/Generated/` folders are obsolete — delete them from your project and `.gitignore`. The closed-shape paths build their descriptors at first use (cheap) and cache them; there is no compile-on-cold-start. If your host also runs Wolverine or another JasperFx-family tool, those still ship their own codegen and may still require the `codegen write` step in your Dockerfile — only the Marten portion of the step is now redundant. +* **The codegen-config knobs have been deleted.** `StoreOptions.GeneratedCodeMode`, `StoreOptions.SourceCodeWritingEnabled`, `StoreOptions.GeneratedCodeOutputPath`, and `StoreOptions.AllowRuntimeCodeGeneration` are gone — references to them will fail to compile against Marten 9.0. Remove them from your bootstrapping. `StoreOptions.ApplicationAssembly` is kept (legitimately used by `AutoRegister` and `TryUseSourceGeneratedDiscovery` as a scan hint). * **The `Pre-Building Generated Types` documentation page has been retired.** Anything that linked to `/configuration/prebuilding` now 404s. The closest equivalent for "I want to ship without dynamic codegen" is reading the [compiled queries source-generator section](#source-gen-compiled-queries) below — the source generator covers the AOT-clean cases the pre-build flow used to. #### **Lazy document-mapping materialization** @@ -495,19 +495,16 @@ See [#4420](https://github.com/JasperFx/marten/issues/4420). Marten 9 retires obsolete types and members deprecated in Marten 8.x: -* **`StoreOptions.GeneratedCodeMode` is `[Obsolete]`.** Prefer the global `IServiceCollection.CritterStackDefaults()` API, which sets `GeneratedCodeMode` and `AutoCreate` per-environment (`Development` / `Production`) and applies the values across every Critter Stack tool in your application (Marten + [Wolverine](https://wolverinefx.net)) in one place: +* **`StoreOptions.GeneratedCodeMode` and the codegen-config family have been deleted** (see [Runtime code generation removed](#runtime-code-generation-removed)). The `x.Production.GeneratedCodeMode = TypeLoadMode.Static;` line that appeared in 8.x `CritterStackDefaults` samples is no longer relevant to Marten — drop it from your bootstrapping. The `ResourceAutoCreate` half of `CritterStackDefaults` is unchanged: ```csharp services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; // x.Development.* defaults are sensible; override only if needed. }); ``` - The old per-`StoreOptions` `GeneratedCodeMode` setter still works in Marten 9 (it carries an `[Obsolete]` warning) — it will be **removed in Marten 10**. Migrate now to avoid the build-break later. - * `[Obsolete]` types and members deprecated since Marten 8.x have been retired in Marten 9. If your code compiled in Marten 8.x with `[Obsolete]` warnings against any Marten type, those members are now gone in Marten 9 — fix the warnings on 8.x first, then upgrade. ### Renames coordinated with JasperFx 2.0 / JasperFx.Events 2.0 @@ -667,11 +664,10 @@ services.AddMarten(opts => // automatic database migrations and dynamic code generation services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); ``` -snippet source | anchor +snippet source | anchor Note the usage of `CritterStackDefaults()` above. This will allow you to specify separate behavior for `Development` time vs diff --git a/docs/scenarios/aggregates-events-repositories.md b/docs/scenarios/aggregates-events-repositories.md index 59180b654a..6f4f83a6ea 100644 --- a/docs/scenarios/aggregates-events-repositories.md +++ b/docs/scenarios/aggregates-events-repositories.md @@ -48,7 +48,7 @@ public abstract class AggregateBase } } ``` -snippet source | anchor +snippet source | anchor With the first piece of infrastructure implemented, two events to capture state changes of an invoice are introduced. Namely, creation of an invoice, accompanied by an invoice number, and addition of lines to an invoice: @@ -80,7 +80,7 @@ public sealed class LineItemAdded } } ``` -snippet source | anchor +snippet source | anchor With the events in place to present the deltas of an invoice, an aggregate is implemented, using the infrastructure presented above, to create and replay state from the described events. @@ -107,7 +107,11 @@ public sealed class Invoice: AggregateBase AddUncommittedEvent(@event); } - private Invoice() + // Public parameterless ctor for Marten's event-store replay. Pre-9.0 + // Marten could call a private parameterless ctor reflectively; the + // source-generated dispatch path in 9.0 emits direct calls instead, + // which require public visibility. See the 9.0 migration guide. + public Invoice() { } @@ -138,8 +142,11 @@ public sealed class Invoice: AggregateBase private readonly List> lines = new List>(); - // Apply the deltas to mutate our state - private void Apply(InvoiceCreated @event) + // Apply methods need to be `public` for the source-generated dispatcher + // to invoke them — pre-9.0 Marten reflected over private members; the + // SG-emitted dispatch path in 9.0 emits direct method calls. See the + // 9.0 migration guide. + public void Apply(InvoiceCreated @event) { Id = @event.InvoiceNumber.ToString(CultureInfo.InvariantCulture); @@ -147,8 +154,7 @@ public sealed class Invoice: AggregateBase Version++; } - // Apply the deltas to mutate our state - private void Apply(LineItemAdded @event) + public void Apply(LineItemAdded @event) { var price = @event.Price * (1 + @event.Vat / 100); Total += price; @@ -159,7 +165,7 @@ public sealed class Invoice: AggregateBase } } ``` -snippet source | anchor +snippet source | anchor The implemented invoice protects its state by not exposing mutable data, while enforcing its contracts through argument validation. Once an applicable state modification is introduced, either through the constructor (which numbers our invoice and captures that in an event) or the `Invoice.AddLine` method, a respective event capturing that data is recorded. @@ -201,7 +207,7 @@ public sealed class AggregateRepository } } ``` -snippet source | anchor +snippet source | anchor With the last infrastructure component in place, versioned invoices can now be created, persisted and hydrated through Marten. For this purpose, first an invoice is created: diff --git a/docs/schema/index.md b/docs/schema/index.md index 0096a3da08..85a9b6b98c 100644 --- a/docs/schema/index.md +++ b/docs/schema/index.md @@ -32,7 +32,7 @@ var store = DocumentStore.For(opts => opts.AutoCreateSchemaObjects = AutoCreate.None; }); ``` -snippet source | anchor +snippet source | anchor To prevent unnecessary loss of data, even in development, on the first usage of a document type, Marten will: @@ -53,7 +53,6 @@ All/None/CreateOnly/CreateOrUpdate rules as the table storage.** ## Overriding Schema Name By default marten will use the default `public` database scheme to create the document tables and function. You may, however, choose to set a different document store database schema name, like so: -::: warning If you run code before schema changes and using `opts.GeneratedCodeMode = TypeLoadMode.Auto;` (by yourself or by `OptimizeArtifactWorkflow()` in dev env) schema won't change. You need to delete `Internal` folder manually to force regenerating code and schema changes. ::: ```cs StoreOptions.DatabaseSchemaName = "other"; diff --git a/docs/schema/migrations.md b/docs/schema/migrations.md index e80f7668f0..04ae110332 100644 --- a/docs/schema/migrations.md +++ b/docs/schema/migrations.md @@ -51,7 +51,7 @@ var store = DocumentStore.For(opts => opts.AutoCreateSchemaObjects = AutoCreate.None; }); ``` -snippet source | anchor +snippet source | anchor As long as you're using a permissive auto creation mode (i.e., not _None_), you should be able to code in your application model @@ -170,7 +170,7 @@ services.AddMarten(opts => // database changes on application startup .ApplyAllDatabaseChangesOnStartup(); ``` -snippet source | anchor +snippet source | anchor In the option above, Marten is calling the same functionality within an `IHostedService` background task. diff --git a/package-lock.json b/package-lock.json index 872c9b7f8b..70be71d496 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "marten", + "name": "scrub-codegen", "lockfileVersion": 3, "requires": true, "packages": { diff --git a/src/AspNetCoreWithMarten/Samples/ByNestedClosure/Startup.cs b/src/AspNetCoreWithMarten/Samples/ByNestedClosure/Startup.cs index 20424c8295..85f0221590 100644 --- a/src/AspNetCoreWithMarten/Samples/ByNestedClosure/Startup.cs +++ b/src/AspNetCoreWithMarten/Samples/ByNestedClosure/Startup.cs @@ -1,5 +1,4 @@ using JasperFx; -using JasperFx.CodeGeneration; using Marten; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -35,7 +34,6 @@ public void ConfigureServices(IServiceCollection services) // automatic database migrations and dynamic code generation services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); #endregion diff --git a/src/AspNetCoreWithMarten/Samples/ByStoreOptions/Startup.cs b/src/AspNetCoreWithMarten/Samples/ByStoreOptions/Startup.cs index 819bf15b5f..6236210ae4 100644 --- a/src/AspNetCoreWithMarten/Samples/ByStoreOptions/Startup.cs +++ b/src/AspNetCoreWithMarten/Samples/ByStoreOptions/Startup.cs @@ -1,5 +1,4 @@ using JasperFx; -using JasperFx.CodeGeneration; using Marten; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -35,7 +34,6 @@ public void ConfigureServices(IServiceCollection services) // automatic database migrations and dynamic code generation services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); diff --git a/src/AspNetCoreWithMarten/Samples/ConfiguringSessionCreation/Startup.cs b/src/AspNetCoreWithMarten/Samples/ConfiguringSessionCreation/Startup.cs index f4769c7deb..84c0eb0888 100644 --- a/src/AspNetCoreWithMarten/Samples/ConfiguringSessionCreation/Startup.cs +++ b/src/AspNetCoreWithMarten/Samples/ConfiguringSessionCreation/Startup.cs @@ -1,6 +1,5 @@ using System.Data; using JasperFx; -using JasperFx.CodeGeneration; using Marten; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -69,7 +68,6 @@ public void ConfigureServices(IServiceCollection services) // automatic database migrations and dynamic code generation services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); #endregion diff --git a/src/AspNetCoreWithMarten/Samples/EagerInitialization/Startup.cs b/src/AspNetCoreWithMarten/Samples/EagerInitialization/Startup.cs index 06415946ed..4e510ca21d 100644 --- a/src/AspNetCoreWithMarten/Samples/EagerInitialization/Startup.cs +++ b/src/AspNetCoreWithMarten/Samples/EagerInitialization/Startup.cs @@ -1,5 +1,4 @@ using JasperFx; -using JasperFx.CodeGeneration; using Marten; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -30,7 +29,6 @@ public void ConfigureServices(IServiceCollection services) // automatic database migrations and dynamic code generation services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); diff --git a/src/AspNetCoreWithMarten/Samples/PerScopeSessionCreation/Startup.cs b/src/AspNetCoreWithMarten/Samples/PerScopeSessionCreation/Startup.cs index 7c912b7f4b..8ca103aee6 100644 --- a/src/AspNetCoreWithMarten/Samples/PerScopeSessionCreation/Startup.cs +++ b/src/AspNetCoreWithMarten/Samples/PerScopeSessionCreation/Startup.cs @@ -1,7 +1,6 @@ using System; using System.Data; using JasperFx; -using JasperFx.CodeGeneration; using Marten; using Marten.Services; using Microsoft.Extensions.Configuration; @@ -139,7 +138,6 @@ public void ConfigureServices(IServiceCollection services) services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); diff --git a/src/CommandLineRunner/Program.cs b/src/CommandLineRunner/Program.cs index ae3e417e1c..ff1576fc3b 100644 --- a/src/CommandLineRunner/Program.cs +++ b/src/CommandLineRunner/Program.cs @@ -4,7 +4,6 @@ using DaemonTests.EventProjections; using DaemonTests.TestingSupport; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Events; using JasperFx.Events.Daemon; using JasperFx.Events.Projections; @@ -46,13 +45,11 @@ public static IHostBuilder CreateHostBuilder(string[] args) opts.RegisterDocumentType(); opts.RegisterDocumentType(); opts.RegisterDocumentType(); - opts.GeneratedCodeMode = TypeLoadMode.Static; }); services.AddMartenStore(opts => { opts.Connection(ConnectionSource.ConnectionString); - opts.GeneratedCodeMode = TypeLoadMode.Static; opts.RegisterDocumentType(); @@ -68,7 +65,6 @@ public static IHostBuilder CreateHostBuilder(string[] args) services.AddMarten(opts => { opts.Events.AppendMode = EventAppendMode.Quick; - opts.GeneratedCodeMode = TypeLoadMode.Dynamic; opts.AutoCreateSchemaObjects = AutoCreate.All; opts.DatabaseSchemaName = "cli"; opts.DisableNpgsqlLogging = true; @@ -80,10 +76,6 @@ public static IHostBuilder CreateHostBuilder(string[] args) t => t.WithTenants("tenant1", "tenant2", "tenant3") ); - // This is important, setting this option tells Marten to - // *try* to use pre-generated code at runtime - //opts.GeneratedCodeMode = TypeLoadMode.Static; - //opts.Schema.For().AddSubClass(); // You have to register all persisted document types ahead of time diff --git a/src/CommandLineRunner/TestCommand.cs b/src/CommandLineRunner/TestCommand.cs index d4542631e2..89e6954498 100644 --- a/src/CommandLineRunner/TestCommand.cs +++ b/src/CommandLineRunner/TestCommand.cs @@ -3,7 +3,6 @@ using System.Threading.Tasks; using DaemonTests.TestingSupport; using EventSourcingTests.Aggregation; -using JasperFx.CodeGeneration; using JasperFx.CommandLine; using Marten; using Marten.Testing.Documents; @@ -19,23 +18,6 @@ public override async Task Execute(NetCoreInput input) { using var host = input.BuildHost(); - var collections = host.Services.GetServices().ToArray(); - foreach (var collection in collections) - { - Console.WriteLine(collection); - Console.WriteLine(" " + collection.Rules.GeneratedCodeOutputPath); - - var files = collection.BuildFiles(); - if (files.Any()) - { - foreach (var file in files) Console.WriteLine(" * " + file); - } - else - { - Console.WriteLine(" * NONE"); - } - } - using var store = host.Services.GetRequiredService(); await store.Advanced.Clean.DeleteAllDocumentsAsync(); diff --git a/src/CoreTests/Examples/CodeGenerationOptions.cs b/src/CoreTests/Examples/CodeGenerationOptions.cs deleted file mode 100644 index 2bad8109fb..0000000000 --- a/src/CoreTests/Examples/CodeGenerationOptions.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Threading.Tasks; -using JasperFx.Core; -using JasperFx.CodeGeneration; -using Marten; -using Marten.Testing.Documents; -using Marten.Testing.Harness; -using Microsoft.Extensions.Hosting; -using Xunit; - -namespace CoreTests.Examples; - -public class CodeGenerationOptions -{ - public void build_store() - { - #region sample_code_generation_modes - - using var store = DocumentStore.For(opts => - { - opts.Connection("some connection string"); - - // This is the default. Marten will always generate - // code dynamically at runtime - opts.GeneratedCodeMode = TypeLoadMode.Dynamic; - - // Marten will only use types that are compiled into - // the application assembly ahead of time. This is the - // "pre-built" model - opts.GeneratedCodeMode = TypeLoadMode.Static; - - // Explained Below :) - opts.GeneratedCodeMode = TypeLoadMode.Auto; - }); - - #endregion - } - - public async Task using_auto() - { - #region sample_document_store_for_user_document - - using var store = DocumentStore.For(opts => - { - // ConnectionSource is a little helper in the Marten - // test suite - opts.Connection(ConnectionSource.ConnectionString); - - opts.GeneratedCodeMode = TypeLoadMode.Auto; - }); - - #endregion - - #region sample_save_a_single_user - - await using var session = store.LightweightSession(); - var user = new User { UserName = "admin" }; - session.Store(user); - await session.SaveChangesAsync(); - - #endregion - } - - [Fact] - public void override_application_assembly() - { - #region sample_using_set_application_project - - using var host = Host.CreateDefaultBuilder() - .ConfigureServices(services => - { - services.AddMarten(opts => - { - opts.Connection("some connection string"); - opts.SetApplicationProject(typeof(User).Assembly); - }); - }) - .StartAsync(); - - #endregion - } -} diff --git a/src/CoreTests/Examples/MultipleDocumentStores.cs b/src/CoreTests/Examples/MultipleDocumentStores.cs index dc2e39483a..718cf1bfe8 100644 --- a/src/CoreTests/Examples/MultipleDocumentStores.cs +++ b/src/CoreTests/Examples/MultipleDocumentStores.cs @@ -1,7 +1,6 @@ using System.Threading; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Events.Daemon; using Marten; using Marten.Schema; @@ -40,10 +39,9 @@ public static async Task bootstrap() .InitializeWith(new DefaultDataSet()); // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation + // automatic database migrations services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); }).StartAsync(); diff --git a/src/CoreTests/Internal/CodeGeneration/MartenSnapshotInputsTests.cs b/src/CoreTests/Internal/CodeGeneration/MartenSnapshotInputsTests.cs deleted file mode 100644 index 8606b3d73a..0000000000 --- a/src/CoreTests/Internal/CodeGeneration/MartenSnapshotInputsTests.cs +++ /dev/null @@ -1,226 +0,0 @@ -using System; -using JasperFx.CodeGeneration.Snapshots; -using Marten; -using Marten.Internal.CodeGeneration; -using Marten.Testing.Harness; -using Shouldly; -using Xunit; - -namespace CoreTests.Internal.CodeGeneration; - -/// -/// Trust-gate tests for the codegen snapshot canonical-input shape (marten#4370 -/// Phase 2). These pin determinism + mutation-sensitivity. They run without -/// Postgres (canonical-input is a pure function of -/// and doesn't touch the database). -/// -public class MartenSnapshotInputsTests -{ - /// - /// Build a minimal StoreOptions that's still composed enough to walk. - /// We never call ApplyConfiguration / Validate / DocumentStore.For — - /// those open a database connection. We work directly against a - /// constructed StoreOptions and exercise the canonical-input shape. - /// - private static StoreOptions FreshOptions() - { - var opts = new StoreOptions(); - opts.Connection(ConnectionSource.ConnectionString); - return opts; - } - - // ─── Determinism ───────────────────────────────────────────────────── - - [Fact] - public void compose_is_deterministic_for_unchanged_options() - { - var a = MartenSnapshotInputs.Compose(FreshOptions()); - var b = MartenSnapshotInputs.Compose(FreshOptions()); - - a.ShouldBe(b); - } - - [Fact] - public void fingerprint_is_deterministic_for_unchanged_options() - { - var a = MartenSnapshot.BuildFingerprint(FreshOptions()); - var b = MartenSnapshot.BuildFingerprint(FreshOptions()); - - a.ConfigHash.ShouldBe(b.ConfigHash); - a.ShouldBe(b); - } - - [Fact] - public void config_hash_is_a_lowercase_64_char_hex_digest() - { - var fp = MartenSnapshot.BuildFingerprint(FreshOptions()); - - fp.ConfigHash.Length.ShouldBe(64); - fp.ConfigHash.ShouldAllBe(c => (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')); - } - - [Fact] - public void fingerprint_records_marten_product_name() - { - MartenSnapshot.BuildFingerprint(FreshOptions()).ProductName.ShouldBe("marten"); - } - - // ─── Mutation matrix ──────────────────────────────────────────────── - // Each mutation tests one dimension of MartenSnapshotInputs.Compose and - // verifies the resulting fingerprint differs. If any of these stop - // failing, you've broken invalidation for that input — bad. - - [Fact] - public void mutation_adding_a_document_type_changes_the_hash() - { - var baseline = MartenSnapshot.BuildFingerprint(FreshOptions()); - - var mutated = FreshOptions(); - mutated.Schema.For(); - var withDoc = MartenSnapshot.BuildFingerprint(mutated); - - withDoc.ConfigHash.ShouldNotBe(baseline.ConfigHash); - } - - [Fact] - public void mutation_different_document_type_yields_different_hash() - { - var a = FreshOptions(); - a.Schema.For(); - var hashA = MartenSnapshot.BuildFingerprint(a).ConfigHash; - - var b = FreshOptions(); - b.Schema.For(); - var hashB = MartenSnapshot.BuildFingerprint(b).ConfigHash; - - hashA.ShouldNotBe(hashB); - } - - [Fact] - public void mutation_changing_database_schema_name_changes_the_hash() - { - var baseline = MartenSnapshot.BuildFingerprint(FreshOptions()); - - var mutated = FreshOptions(); - mutated.DatabaseSchemaName = "different_schema"; - var withCustomSchema = MartenSnapshot.BuildFingerprint(mutated); - - withCustomSchema.ConfigHash.ShouldNotBe(baseline.ConfigHash); - } - - [Fact] - public void mutation_changing_store_name_changes_the_hash() - { - var baseline = MartenSnapshot.BuildFingerprint(FreshOptions()); - - var mutated = FreshOptions(); - mutated.StoreName = "AnotherStore"; - var withCustomName = MartenSnapshot.BuildFingerprint(mutated); - - withCustomName.ConfigHash.ShouldNotBe(baseline.ConfigHash); - } - - [Fact] - public void mutation_changing_stream_identity_changes_the_hash() - { - var baseline = MartenSnapshot.BuildFingerprint(FreshOptions()); - - var mutated = FreshOptions(); - mutated.Events.StreamIdentity = JasperFx.Events.StreamIdentity.AsString; - var withStringStream = MartenSnapshot.BuildFingerprint(mutated); - - withStringStream.ConfigHash.ShouldNotBe(baseline.ConfigHash); - } - - [Fact] - public void mutation_enabling_strict_stream_identity_changes_the_hash() - { - var baseline = MartenSnapshot.BuildFingerprint(FreshOptions()); - - var mutated = FreshOptions(); - mutated.Events.EnableStrictStreamIdentityEnforcement = true; - var withStrict = MartenSnapshot.BuildFingerprint(mutated); - - withStrict.ConfigHash.ShouldNotBe(baseline.ConfigHash); - } - - [Fact] - public void mutation_enabling_extended_progression_tracking_changes_the_hash() - { - // EventGraph is internal so we access the flag via the internal property - // rather than the IEventStoreOptions public surface. CoreTests sees Marten - // internals via InternalsVisibleTo. - var baseline = MartenSnapshot.BuildFingerprint(FreshOptions()); - - var mutated = FreshOptions(); - mutated.EventGraph.EnableExtendedProgressionTracking = true; - var withExt = MartenSnapshot.BuildFingerprint(mutated); - - withExt.ConfigHash.ShouldNotBe(baseline.ConfigHash); - } - - // ─── Composition / order-stability ────────────────────────────────── - - [Fact] - public void doc_type_registration_order_does_not_affect_hash() - { - // Sorting in MartenSnapshotInputs means two stores that register the same - // types in different orders should produce identical fingerprints. If - // this test fails the sort isn't doing its job and downstream snapshots - // would spuriously invalidate on cosmetic option-build reorderings. - var a = FreshOptions(); - a.Schema.For(); - a.Schema.For(); - var hashA = MartenSnapshot.BuildFingerprint(a).ConfigHash; - - var b = FreshOptions(); - b.Schema.For(); - b.Schema.For(); - var hashB = MartenSnapshot.BuildFingerprint(b).ConfigHash; - - hashA.ShouldBe(hashB); - } - - // ─── Verdict via SnapshotGate ─────────────────────────────────────── - - [Fact] - public void verify_returns_Accept_when_persisted_matches_live() - { - var live = MartenSnapshot.BuildFingerprint(FreshOptions()); - SnapshotGate.Verify(live, persisted: live).ShouldBe(SnapshotVerdict.Accept); - } - - [Fact] - public void verify_returns_FirstBoot_when_no_persisted_fingerprint() - { - var live = MartenSnapshot.BuildFingerprint(FreshOptions()); - SnapshotGate.Verify(live, persisted: null).ShouldBe(SnapshotVerdict.FirstBoot); - } - - [Fact] - public void verify_returns_RejectAndRegenerate_when_options_mutated() - { - var persisted = MartenSnapshot.BuildFingerprint(FreshOptions()); - - var live = FreshOptions(); - live.Schema.For(); - var liveFingerprint = MartenSnapshot.BuildFingerprint(live); - - SnapshotGate.Verify(liveFingerprint, persisted) - .ShouldBe(SnapshotVerdict.RejectAndRegenerate); - } - - // ─── Test fixtures ────────────────────────────────────────────────── - - public class DocTypeA - { - public Guid Id { get; set; } - public string Name { get; set; } = ""; - } - - public class DocTypeB - { - public Guid Id { get; set; } - public int Count { get; set; } - } -} diff --git a/src/CoreTests/Internal/CodeGeneration/MartenSnapshotPersistenceTests.cs b/src/CoreTests/Internal/CodeGeneration/MartenSnapshotPersistenceTests.cs deleted file mode 100644 index 557d66220a..0000000000 --- a/src/CoreTests/Internal/CodeGeneration/MartenSnapshotPersistenceTests.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System; -using System.IO; -using JasperFx.CodeGeneration.Snapshots; -using Marten; -using Marten.Internal.CodeGeneration; -using Marten.Testing.Harness; -using Shouldly; -using Xunit; - -namespace CoreTests.Internal.CodeGeneration; - -/// -/// Filesystem round-trip + verify tests for the codegen snapshot -/// (marten#4370 Phase 2). Covers -/// and end-to-end via a real -/// temp directory. No Postgres connection required. -/// -public class MartenSnapshotPersistenceTests : IDisposable -{ - private readonly string _tempFolder; - - public MartenSnapshotPersistenceTests() - { - _tempFolder = Path.Combine( - Path.GetTempPath(), - "marten-snapshot-tests-" + Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(_tempFolder); - } - - public void Dispose() - { - if (Directory.Exists(_tempFolder)) Directory.Delete(_tempFolder, recursive: true); - } - - private StoreOptions OptionsAtTempFolder() - { - var opts = new StoreOptions(); - opts.Connection(ConnectionSource.ConnectionString); - opts.GeneratedCodeOutputPath = _tempFolder; - return opts; - } - - // ─── First-boot path ───────────────────────────────────────────────── - - [Fact] - public void verify_at_boot_returns_FirstBoot_when_folder_is_empty() - { - // No fingerprint persisted yet → FirstBoot. This is the steady-state - // result on a fresh deployment, not an error. - MartenSnapshot.VerifyAtBoot(OptionsAtTempFolder()) - .ShouldBe(SnapshotVerdict.FirstBoot); - } - - [Fact] - public void persist_then_verify_round_trips_to_Accept() - { - // The plumbing's primary contract: PersistFingerprint() followed by - // VerifyAtBoot() with the same options accepts the snapshot. If this - // ever stops holding, the boot-time verify path is broken. - var opts = OptionsAtTempFolder(); - - MartenSnapshot.PersistFingerprint(opts); - - MartenSnapshot.VerifyAtBoot(opts).ShouldBe(SnapshotVerdict.Accept); - } - - [Fact] - public void persist_writes_fingerprint_json_to_the_generated_folder() - { - MartenSnapshot.PersistFingerprint(OptionsAtTempFolder()); - - var path = Path.Combine(_tempFolder, SnapshotGate.FingerprintFileName); - File.Exists(path).ShouldBeTrue(); - } - - // ─── Mutation invalidates ─────────────────────────────────────────── - - [Fact] - public void mutation_after_persist_yields_RejectAndRegenerate() - { - // Establish a baseline snapshot on disk. - var baseline = OptionsAtTempFolder(); - MartenSnapshot.PersistFingerprint(baseline); - - // Live boot with a mutated config — same temp folder, different inputs. - var mutated = OptionsAtTempFolder(); - mutated.Schema.For(); - - MartenSnapshot.VerifyAtBoot(mutated) - .ShouldBe(SnapshotVerdict.RejectAndRegenerate); - } - - [Fact] - public void rewriting_with_mutated_options_overwrites_the_baseline() - { - var baseline = OptionsAtTempFolder(); - MartenSnapshot.PersistFingerprint(baseline); - - var mutated = OptionsAtTempFolder(); - mutated.Schema.For(); - MartenSnapshot.PersistFingerprint(mutated); - - // After overwrite the mutated options should now Accept (the persisted - // fingerprint is the mutated one). This is the steady-state of the - // "fall back to live, then re-persist" flow on the next boot. - MartenSnapshot.VerifyAtBoot(mutated).ShouldBe(SnapshotVerdict.Accept); - - // And the original baseline should now be rejected because the - // persisted fingerprint reflects the mutation. - MartenSnapshot.VerifyAtBoot(baseline) - .ShouldBe(SnapshotVerdict.RejectAndRegenerate); - } - - // ─── Defensive behaviour ──────────────────────────────────────────── - - [Fact] - public void verify_at_boot_with_malformed_fingerprint_treats_as_FirstBoot() - { - // SnapshotGate.Read returns null on malformed JSON (soft-fallback policy). - // From MartenSnapshot's perspective that's indistinguishable from no - // fingerprint — both return FirstBoot. Pin this so a corrupt file in - // the generated folder doesn't crash boot. - File.WriteAllText( - Path.Combine(_tempFolder, SnapshotGate.FingerprintFileName), - "{ corrupted"); - - MartenSnapshot.VerifyAtBoot(OptionsAtTempFolder()) - .ShouldBe(SnapshotVerdict.FirstBoot); - } - - public class TestDoc - { - public Guid Id { get; set; } - } -} diff --git a/src/CoreTests/SessionOptionsTests.cs b/src/CoreTests/SessionOptionsTests.cs index a86c92f10e..d524cf6c3a 100644 --- a/src/CoreTests/SessionOptionsTests.cs +++ b/src/CoreTests/SessionOptionsTests.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten; using Marten.Internal.OpenTelemetry; @@ -157,7 +156,6 @@ public async Task default_timeout_should_be_npgsql_default_ie_30() { var connectionString = ConnectionSource.ConnectionString.Replace(";Command Timeout=5", ""); opts.Connection(connectionString); - opts.GeneratedCodeMode = TypeLoadMode.Auto; }); var options = new SessionOptions(); diff --git a/src/CoreTests/StoreOptionsTests.cs b/src/CoreTests/StoreOptionsTests.cs index 0ef14c26fd..c1193924ae 100644 --- a/src/CoreTests/StoreOptionsTests.cs +++ b/src/CoreTests/StoreOptionsTests.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Text.Json; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Descriptors; using JasperFx.MultiTenancy; using Marten; @@ -314,13 +313,6 @@ public void storeOptions.Advanced.DuplicatedFieldEnumStorage.ShouldBe(EnumStorage.AsInteger); } - [Fact] - public void default_code_generation_is_dynamic() - { - var storeOptions = new StoreOptions(); - storeOptions.GeneratedCodeMode.ShouldBe(TypeLoadMode.Dynamic); - } - public void set_the_maximum_name_length() { #region sample_setting-name-data-length diff --git a/src/CoreTests/all_exceptions_should_derive_from_MartenException.cs b/src/CoreTests/all_exceptions_should_derive_from_MartenException.cs index 29bf9783fa..b0704cd9dd 100644 --- a/src/CoreTests/all_exceptions_should_derive_from_MartenException.cs +++ b/src/CoreTests/all_exceptions_should_derive_from_MartenException.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using JasperFx.Core; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using Marten.Events.TestSupport; using Marten.Exceptions; diff --git a/src/CoreTests/bootstrapping_with_service_collection_extensions.cs b/src/CoreTests/bootstrapping_with_service_collection_extensions.cs index 48f3a11d7b..e2fe233478 100644 --- a/src/CoreTests/bootstrapping_with_service_collection_extensions.cs +++ b/src/CoreTests/bootstrapping_with_service_collection_extensions.cs @@ -4,7 +4,6 @@ using System.Reflection; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Core; using JasperFx.Core.Reflection; using Lamar; @@ -51,7 +50,7 @@ public void add_marten_with_just_connection_string() } [Fact] - public async Task use_jasper_fx_defaults_for_type_load_and_auto_create() + public async Task use_jasper_fx_defaults_for_auto_create() { using var host = await Host.CreateDefaultBuilder() .ConfigureServices(services => @@ -61,19 +60,12 @@ public async Task use_jasper_fx_defaults_for_type_load_and_auto_create() services.AddJasperFx(opts => { opts.Development.ResourceAutoCreate = AutoCreate.None; - opts.GeneratedCodeOutputPath = "/"; - opts.Development.GeneratedCodeMode = TypeLoadMode.Static; - - // Default is true - opts.Development.SourceCodeWritingEnabled = false; }); }) .UseEnvironment("Development").StartAsync(); var store = (DocumentStore)host.DocumentStore(); store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.None); - store.Options.SourceCodeWritingEnabled.ShouldBeFalse(); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Static); } [Fact] @@ -118,49 +110,6 @@ public void add_marten_by_configure_lambda() ShouldHaveAllTheExpectedRegistrations(container); } - [Fact] - public void picks_up_application_assembly_and_content_directory_from_IHostEnvironment() - { - var environment = new MartenHostEnvironment(); - - using var host = Host.CreateDefaultBuilder(Array.Empty()) - .ConfigureServices(services => - { - services.AddMarten(ConnectionSource.ConnectionString); - - services.AddSingleton(environment); - }).Build(); - - var store = host.Services.GetRequiredService().As(); - store.Options.ApplicationAssembly.ShouldBe(GetType().Assembly); - var projectPath = AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory(); - var expectedGeneratedCodeOutputPath = projectPath.ToFullPath().AppendPath("Internal", "Generated"); - store.Options.GeneratedCodeOutputPath.ShouldBe(expectedGeneratedCodeOutputPath); - - var rules = store.Options.CreateGenerationRules(); - rules.ApplicationAssembly.ShouldBe(store.Options.ApplicationAssembly); - rules.GeneratedCodeOutputPath.ShouldBe(store.Options.GeneratedCodeOutputPath); - } - - [Fact] - public void application_assembly_and_content_directory_from_StoreOptions() - { - using var host = Host.CreateDefaultBuilder(Array.Empty()) - .ConfigureServices(services => - { - services.AddMarten(opts => - { - opts.Connection(ConnectionSource.ConnectionString); - opts.SetApplicationProject(GetType().Assembly); - }); - }).Build(); - - var store = host.Services.GetRequiredService().As(); - store.Options.ApplicationAssembly.ShouldBe(GetType().Assembly); - var projectPath = AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory(); - var expectedGeneratedCodeOutputPath = projectPath.ToFullPath().AppendPath("Internal", "Generated"); - store.Options.GeneratedCodeOutputPath.ShouldBe(expectedGeneratedCodeOutputPath); - } [Fact] public void no_error_if_IHostEnvironment_does_not_exist() @@ -171,13 +120,7 @@ public void no_error_if_IHostEnvironment_does_not_exist() services.AddMarten(ConnectionSource.ConnectionString); }).Build(); - var store = host.Services.GetRequiredService().As(); - store.Options.ApplicationAssembly.ShouldBe(GetType().Assembly); - store.Options.GeneratedCodeOutputPath.TrimEnd(Path.DirectorySeparatorChar).ShouldBe(AppContext.BaseDirectory - .AppendPath("Internal", "Generated").TrimEnd(Path.DirectorySeparatorChar)); - - var rules = store.Options.CreateGenerationRules(); - rules.ApplicationAssembly.ShouldBe(store.Options.ApplicationAssembly); + host.Services.GetRequiredService().As().ShouldNotBeNull(); } [Fact] @@ -630,8 +573,6 @@ private static void ShouldHaveAllTheExpectedRegistrations(Container container, container.GetInstance().ShouldBeSameAs(store.As().Tenancy); - container.GetAllInstances().OfType().Count().ShouldBe(1); - container.Model.For>().Default.ShouldNotBeNull(); container.GetInstance() diff --git a/src/CoreTests/document_store_usage_tests.cs b/src/CoreTests/document_store_usage_tests.cs index 4157bc0894..716e9c25ba 100644 --- a/src/CoreTests/document_store_usage_tests.cs +++ b/src/CoreTests/document_store_usage_tests.cs @@ -146,22 +146,6 @@ public async Task usage_carries_flat_option_values_for_secondary_settings() usage.PropertyFor("WriteSessionPreference").ShouldNotBeNull(); } - [Fact] - public async Task usage_includes_code_generation_child_descriptor() - { - using var host = await BuildHost(opts => - { - opts.Connection(ConnectionSource.ConnectionString); - opts.DatabaseSchemaName = "doc_usage_codegen"; - opts.Schema.For(); - }); - - var usage = await GetUsageAsync(host); - - usage.CodeGeneration.ShouldNotBeNull(); - usage.CodeGeneration.GeneratedCodeMode.ShouldNotBeNullOrEmpty(); - } - [Fact] public async Task event_store_usage_includes_global_aggregates_when_present() { diff --git a/src/CoreTests/jasper_fx_mechanics.cs b/src/CoreTests/jasper_fx_mechanics.cs index 17c64898c2..ecee3a6f39 100644 --- a/src/CoreTests/jasper_fx_mechanics.cs +++ b/src/CoreTests/jasper_fx_mechanics.cs @@ -3,7 +3,6 @@ using System.Threading; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.CommandLine.Descriptions; using JasperFx.Core.Reflection; using JasperFx.Events; @@ -140,39 +139,6 @@ public async Task build_system_parts_for_ancillary_document_stores_and_single_te usage2.SubjectUri.ShouldBe(new Uri("marten://isecondstore")); } - [Fact] - public async Task add_marten_store_for_ancillary_stores_respects_JasperFxOptions() - { - using var host = await Host.CreateDefaultBuilder() - .ConfigureServices(services => - { - services.AddMartenStore(opts => - { - opts.Connection(ConnectionSource.ConnectionString); - opts.DatabaseSchemaName = "first_store"; - }); - - services.AddMartenStore(services => - { - var opts = new StoreOptions(); - opts.Connection(ConnectionSource.ConnectionString); - opts.DatabaseSchemaName = "second_store"; - - return opts; - }); - - services.CritterStackDefaults(opts => - { - opts.Development.GeneratedCodeMode = TypeLoadMode.Auto; - opts.Production.GeneratedCodeMode = TypeLoadMode.Auto; - - }); - }).StartAsync(); - - host.Services.GetRequiredService().Options.As().GeneratedCodeMode.ShouldBe(TypeLoadMode.Auto); - host.Services.GetRequiredService().Options.As().GeneratedCodeMode.ShouldBe(TypeLoadMode.Auto); - } - [Fact] public async Task integration_with_describe_command_line() { diff --git a/src/CoreTests/reading_configuration_from_jasperfxoptions.cs b/src/CoreTests/reading_configuration_from_jasperfxoptions.cs index b3b1d43309..23c0a1f2ca 100644 --- a/src/CoreTests/reading_configuration_from_jasperfxoptions.cs +++ b/src/CoreTests/reading_configuration_from_jasperfxoptions.cs @@ -1,14 +1,10 @@ -using System.Threading.Tasks; using JasperFx; -using JasperFx.Core; -using Lamar; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using JasperFx.MultiTenancy; +using Lamar; using Marten; using Marten.Testing.Harness; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; using Shouldly; using Weasel.Core; using Xunit; @@ -28,14 +24,7 @@ public void all_the_defaults() var store = container.GetInstance().As(); - var rules = store.Options.CreateGenerationRules(); - store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.CreateOrUpdate); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Dynamic); - - rules.GeneratedNamespace.ShouldBe("Marten.Generated"); - rules.SourceCodeWritingEnabled.ShouldBeTrue(); - } [Fact] @@ -63,7 +52,6 @@ public void use_default_tenancy_id_style() services.AddMarten(opts => { opts.Connection(ConnectionSource.ConnectionString); - // opts.TenantIdStyle = TenantIdStyle.ForceLowerCase; }); services.CritterStackDefaults(x => x.TenantIdStyle = TenantIdStyle.ForceUpperCase); @@ -71,233 +59,4 @@ public void use_default_tenancy_id_style() container.GetInstance().As().Options.TenantIdStyle.ShouldBe(TenantIdStyle.ForceUpperCase); } - - public static async Task bootstrapping_example() - { - #region sample_using_optimized_artifact_workflow - - using var host = await Host.CreateDefaultBuilder() - .ConfigureServices(services => - { - services.AddMarten("connection string"); - - // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation - services.CritterStackDefaults(x => - { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; - x.Production.ResourceAutoCreate = AutoCreate.None; - }); - }).StartAsync(); - - #endregion - } - - public static async Task bootstrapping_example_with_static() - { - #region sample_using_optimized_artifact_workflow_static - - using var host = await Host.CreateDefaultBuilder() - .ConfigureServices(services => - { - services.AddMarten("connection string"); - - // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation - services.CritterStackDefaults(x => - { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; - x.Production.ResourceAutoCreate = AutoCreate.None; - }); - }).StartAsync(); - #endregion - } - - [Fact] - public void using_optimized_mode_in_development() - { - using var host = new HostBuilder() - .ConfigureServices(services => - { - services.AddMarten(ConnectionSource.ConnectionString); - - // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation - services.CritterStackDefaults(x => - { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; - x.Production.ResourceAutoCreate = AutoCreate.None; - - x.Development.GeneratedCodeMode = TypeLoadMode.Auto; - x.Development.ResourceAutoCreate = AutoCreate.CreateOrUpdate; - - x.TenantIdStyle = TenantIdStyle.ForceLowerCase; - }); - }) - .UseEnvironment("Development") - .Start(); - - - var store = host.Services.GetRequiredService().As(); - - var rules = store.Options.CreateGenerationRules(); - - store.Options.TenantIdStyle.ShouldBe(TenantIdStyle.ForceLowerCase); - - store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.CreateOrUpdate); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Auto); - - rules.GeneratedNamespace.ShouldBe("Marten.Generated"); - rules.SourceCodeWritingEnabled.ShouldBeTrue(); - } - - [Fact] - public void using_optimized_mode_in_production() - { - using var host = new HostBuilder() - .ConfigureServices(services => - { - services.AddMarten(ConnectionSource.ConnectionString); - - // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation - services.CritterStackDefaults(x => - { - x.Production.GeneratedCodeMode = TypeLoadMode.Auto; - x.Production.ResourceAutoCreate = AutoCreate.None; - x.Production.SourceCodeWritingEnabled = false; - }); - }) - .UseEnvironment("Production") - .Start(); - - - var store = host.Services.GetRequiredService().As(); - - var rules = store.Options.CreateGenerationRules(); - - store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.None); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Auto); - - rules.GeneratedNamespace.ShouldBe("Marten.Generated"); - rules.SourceCodeWritingEnabled.ShouldBeFalse(); - } - - [Fact] - public void application_assembly_from_critter_stack_defaults_flows_to_store_options() - { - var expectedAssembly = typeof(JasperFxOptions).Assembly; - - using var container = Container.For(services => - { - services.AddMarten(ConnectionSource.ConnectionString); - services.CritterStackDefaults(x => x.ApplicationAssembly = expectedAssembly); - }); - - var store = container.GetInstance().As(); - - #pragma warning disable CS0618 - store.Options.ApplicationAssembly.ShouldBe(expectedAssembly); - #pragma warning restore CS0618 - } - - [Fact] - public void explicit_store_options_application_assembly_takes_precedence_over_critter_stack_defaults() - { - var critterStackAssembly = typeof(JasperFxOptions).Assembly; - var explicitAssembly = typeof(StoreOptions).Assembly; - - using var container = Container.For(services => - { - services.AddMarten(opts => - { - opts.Connection(ConnectionSource.ConnectionString); - #pragma warning disable CS0618 - opts.ApplicationAssembly = explicitAssembly; - #pragma warning restore CS0618 - }); - services.CritterStackDefaults(x => x.ApplicationAssembly = critterStackAssembly); - }); - - var store = container.GetInstance().As(); - - #pragma warning disable CS0618 - store.Options.ApplicationAssembly.ShouldBe(explicitAssembly); - #pragma warning restore CS0618 - } - - public static void default_setup() - { - #region sample_simplest_possible_setup - - var store = DocumentStore.For("connection string"); - - #endregion - } - - [Fact] - public void using_optimized_mode_in_production_override_type_load_mode() - { - using var host = new HostBuilder() - .ConfigureServices(services => - { - services.AddMarten(ConnectionSource.ConnectionString); - - // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation - services.CritterStackDefaults(x => - { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; - x.Production.ResourceAutoCreate = AutoCreate.None; - x.Production.SourceCodeWritingEnabled = false; - }); - }) - .UseEnvironment("Production") - .Start(); - - - var store = host.Services.GetRequiredService().As(); - - var rules = store.Options.CreateGenerationRules(); - - store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.None); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Static); - - rules.GeneratedNamespace.ShouldBe("Marten.Generated"); - rules.SourceCodeWritingEnabled.ShouldBeFalse(); - } - - [Fact] - public void using_optimized_mode_in_production_override_environment_name() - { - using var host = new HostBuilder() - .ConfigureServices(services => - { - services.AddMarten(ConnectionSource.ConnectionString); - - // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation - services.CritterStackDefaults(x => - { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; - x.Production.ResourceAutoCreate = AutoCreate.CreateOrUpdate; - - x.Development.GeneratedCodeMode = TypeLoadMode.Auto; - - x.DevelopmentEnvironmentName = "Local"; - }); - }) - .UseEnvironment("Local") - .Start(); - - var store = host.Services.GetRequiredService().As(); - - var rules = store.Options.CreateGenerationRules(); - - store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.CreateOrUpdate); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Auto); - - rules.GeneratedNamespace.ShouldBe("Marten.Generated"); - rules.SourceCodeWritingEnabled.ShouldBeTrue(); - } } diff --git a/src/DaemonTests/Bugs/Bug_2177_query_session_tenancy_in_daemon.cs b/src/DaemonTests/Bugs/Bug_2177_query_session_tenancy_in_daemon.cs index 80de61dbb9..b583b30a59 100644 --- a/src/DaemonTests/Bugs/Bug_2177_query_session_tenancy_in_daemon.cs +++ b/src/DaemonTests/Bugs/Bug_2177_query_session_tenancy_in_daemon.cs @@ -7,7 +7,6 @@ using Marten.Testing.Harness; using Xunit; using Bug2177; -using JasperFx.CodeGeneration; using JasperFx.Core; using JasperFx.Events; using JasperFx.Events.Projections; @@ -29,7 +28,6 @@ public async Task should_have_tenancy_set_correctly() options.Events.MetadataConfig.EnableAll(); options.Projections.Add(ProjectionLifecycle.Async); - options.GeneratedCodeMode = TypeLoadMode.Auto; options.Schema.For().MultiTenanted(); }); diff --git a/src/DaemonTests/TestingSupport/TestLogger.cs b/src/DaemonTests/TestingSupport/TestLogger.cs index 2dd7597335..cbf3ed2889 100644 --- a/src/DaemonTests/TestingSupport/TestLogger.cs +++ b/src/DaemonTests/TestingSupport/TestLogger.cs @@ -1,6 +1,5 @@ using System; using System.Diagnostics; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using Microsoft.Extensions.Logging; using Xunit.Abstractions; diff --git a/src/DocumentDbTests/Concurrency/numeric_revisioning.cs b/src/DocumentDbTests/Concurrency/numeric_revisioning.cs index 9eb1fb0d9f..cd64c0df3a 100644 --- a/src/DocumentDbTests/Concurrency/numeric_revisioning.cs +++ b/src/DocumentDbTests/Concurrency/numeric_revisioning.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using Castle.Components.DictionaryAdapter; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten; using Marten.Exceptions; @@ -387,13 +386,6 @@ public async Task load_and_update_revisioned_document_by_revision_from_dirty_ses [Fact] public async Task optimistic_concurrency_failure_with_update_revision_when_revision_number_equal_in_new_doc_and_db() { - StoreOptions(opts => - { - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = AppContext.BaseDirectory.ParentDirectory().ParentDirectory() - .ParentDirectory().AppendPath("Internal", "Generated"); - }); - var doc1 = new RevisionedDoc { Name = "Tim" }; theSession.Store(doc1); await theSession.SaveChangesAsync(); diff --git a/src/DocumentDbTests/Configuration/DocumentMappingTests.cs b/src/DocumentDbTests/Configuration/DocumentMappingTests.cs index cbffd44984..314091704c 100644 --- a/src/DocumentDbTests/Configuration/DocumentMappingTests.cs +++ b/src/DocumentDbTests/Configuration/DocumentMappingTests.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using JasperFx.Events; using JasperFx.Events.Projections; @@ -758,11 +757,6 @@ public class Organization public class CustomIdGeneration: IIdGeneration { public bool IsNumeric { get; } = false; - - public void GenerateCode(GeneratedMethod assign, DocumentMapping mapping) - { - throw new NotSupportedException(); - } } diff --git a/src/DocumentDbTests/Writing/Identity/Sequences/CustomKeyGenerationTests.cs b/src/DocumentDbTests/Writing/Identity/Sequences/CustomKeyGenerationTests.cs index 40d79aaaf9..f16e786339 100644 --- a/src/DocumentDbTests/Writing/Identity/Sequences/CustomKeyGenerationTests.cs +++ b/src/DocumentDbTests/Writing/Identity/Sequences/CustomKeyGenerationTests.cs @@ -1,10 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using JasperFx.Core; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; using JasperFx.Core.Reflection; using Marten; using Marten.Schema; @@ -19,13 +12,6 @@ namespace DocumentDbTests.Writing.Identity.Sequences; public class CustomIdGeneration : IIdGeneration { public bool IsNumeric { get; } = false; - public void GenerateCode(GeneratedMethod assign, DocumentMapping mapping) - { - var document = new Use(mapping.DocumentType); - assign.Frames.Code($"_setter({{0}}, \"newId\");", document); - assign.Frames.Code($"return {{0}}.{mapping.CodeGen.AccessId};", document); - } - } #endregion diff --git a/src/EventSourcingTests/Aggregation/AggregationContext.cs b/src/EventSourcingTests/Aggregation/AggregationContext.cs index 5d357c6347..2f3996c84e 100644 --- a/src/EventSourcingTests/Aggregation/AggregationContext.cs +++ b/src/EventSourcingTests/Aggregation/AggregationContext.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using JasperFx.Events; using JasperFx.Events.Aggregation; @@ -32,19 +31,12 @@ protected override Task fixtureSetup() public void UsingDefinition() where T : SingleStreamProjection, new() { _projection = new T(); - - var rules = theStore.Options.CreateGenerationRules(); - rules.TypeLoadMode = TypeLoadMode.Dynamic; } public void UsingDefinition(Action> configure) { _projection = new SingleStreamProjection(); configure(_projection); - - - var rules = theStore.Options.CreateGenerationRules(); - rules.TypeLoadMode = TypeLoadMode.Dynamic; } diff --git a/src/EventSourcingTests/Aggregation/aggregation_projection_validation_rules.cs b/src/EventSourcingTests/Aggregation/aggregation_projection_validation_rules.cs index 88cd119248..447f0a89a4 100644 --- a/src/EventSourcingTests/Aggregation/aggregation_projection_validation_rules.cs +++ b/src/EventSourcingTests/Aggregation/aggregation_projection_validation_rules.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using JasperFx.Events; using JasperFx.Events.Grouping; diff --git a/src/EventSourcingTests/Bugs/Bug_2865_configuration_assertion_with_flat_table_projections.cs b/src/EventSourcingTests/Bugs/Bug_2865_configuration_assertion_with_flat_table_projections.cs index d937c8933a..e92d56fee3 100644 --- a/src/EventSourcingTests/Bugs/Bug_2865_configuration_assertion_with_flat_table_projections.cs +++ b/src/EventSourcingTests/Bugs/Bug_2865_configuration_assertion_with_flat_table_projections.cs @@ -1,7 +1,6 @@ using System; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Events.Daemon; using JasperFx.Events.Projections; using Marten; @@ -39,9 +38,7 @@ public async Task should_be_able_to_assert_on_existence_of_flat_table_functions( appBuilder.Services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; - x.Production.SourceCodeWritingEnabled = false; }); var app = appBuilder.Build(); diff --git a/src/EventSourcingTests/Bugs/Bug_3791_migrating_from_no_partitioning_to_having_partitioning.cs b/src/EventSourcingTests/Bugs/Bug_3791_migrating_from_no_partitioning_to_having_partitioning.cs index 192f89c2c7..eb7986c73f 100644 --- a/src/EventSourcingTests/Bugs/Bug_3791_migrating_from_no_partitioning_to_having_partitioning.cs +++ b/src/EventSourcingTests/Bugs/Bug_3791_migrating_from_no_partitioning_to_having_partitioning.cs @@ -1,5 +1,4 @@ using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Events; using Marten; using Marten.Testing.Harness; @@ -18,7 +17,6 @@ public async Task try_it_out() //o.Events.UseArchivedStreamPartitioning = true; o.DisableNpgsqlLogging = true; o.Events.UseOptimizedProjectionRebuilds = true; - o.GeneratedCodeMode = TypeLoadMode.Auto; o.Events.AppendMode = EventAppendMode.Quick; o.Events.UseIdentityMapForAggregates = true; o.DatabaseSchemaName = "some_custom_schema"; @@ -35,7 +33,6 @@ public async Task try_it_out() o.Events.UseArchivedStreamPartitioning = true; o.DisableNpgsqlLogging = true; o.Events.UseOptimizedProjectionRebuilds = true; - o.GeneratedCodeMode = TypeLoadMode.Auto; o.Events.AppendMode = EventAppendMode.Quick; o.Events.UseIdentityMapForAggregates = true; o.DatabaseSchemaName = "some_custom_schema"; diff --git a/src/EventSourcingTests/Projections/CodeGeneration/aggregation_with_event_type_hierarchy.cs b/src/EventSourcingTests/Projections/CodeGeneration/aggregation_with_event_type_hierarchy.cs index 2009095895..8328ab3ad2 100644 --- a/src/EventSourcingTests/Projections/CodeGeneration/aggregation_with_event_type_hierarchy.cs +++ b/src/EventSourcingTests/Projections/CodeGeneration/aggregation_with_event_type_hierarchy.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; using Marten.Events.Projections; using Marten.Testing.Harness; using Shouldly; @@ -17,7 +16,6 @@ public aggregation_with_event_type_hierarchy() { StoreOptions(x => { - x.GeneratedCodeMode = TypeLoadMode.Auto; x.AutoCreateSchemaObjects = AutoCreate.All; x.Schema.For().Identity(something => something.Id); diff --git a/src/EventSourcingTests/SchemaChange/MultipleVersions/MultipleSchemaVersions.cs b/src/EventSourcingTests/SchemaChange/MultipleVersions/MultipleSchemaVersions.cs index 78393ebc8e..c7140389dd 100644 --- a/src/EventSourcingTests/SchemaChange/MultipleVersions/MultipleSchemaVersions.cs +++ b/src/EventSourcingTests/SchemaChange/MultipleVersions/MultipleSchemaVersions.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Events; using Marten; using Marten.Events; @@ -32,7 +31,6 @@ Action configureV3Upcasters StoreOptions(options => { - options.GeneratedCodeMode = TypeLoadMode.Auto; options.Projections.Snapshot(SnapshotLifecycle.Inline); }); await theStore.EnsureStorageExistsAsync(typeof(StreamAction)); @@ -79,7 +77,6 @@ Action configureV3Upcasters StoreOptions(options => { - options.GeneratedCodeMode = TypeLoadMode.Auto; options.Projections.Snapshot(SnapshotLifecycle.Inline); }); await theStore.EnsureStorageExistsAsync(typeof(StreamAction)); @@ -131,7 +128,6 @@ private async Task CheckV2WithTheSameNameUpcasting( { using var storeV2 = SeparateStore(options => { - options.GeneratedCodeMode = TypeLoadMode.Auto; options.Projections.Snapshot(SnapshotLifecycle.Inline); //////////////////////////////////////////////////////// // 2.1. Define Upcast methods from V1 to V2 @@ -210,7 +206,6 @@ decimal price { using var storeV3 = SeparateStore(options => { - options.GeneratedCodeMode = TypeLoadMode.Auto; options.Projections.Snapshot(SnapshotLifecycle.Inline); //////////////////////////////////////////////////////// // 3.1. Define Upcast methods from V1 to V3, and from V2 to V3 @@ -291,7 +286,6 @@ private async Task CheckV2WithDifferentNameUpcasting( { using var storeV2 = SeparateStore(options => { - options.GeneratedCodeMode = TypeLoadMode.Auto; options.Projections.Snapshot(SnapshotLifecycle.Inline); //////////////////////////////////////////////////////// // 2.1. Define Upcast methods from V1 to V2 @@ -369,7 +363,6 @@ private async Task CheckV3WithDifferentNameUpcasting( { using var storeV3 = SeparateStore(options => { - options.GeneratedCodeMode = TypeLoadMode.Auto; options.Projections.Snapshot(SnapshotLifecycle.Inline); //////////////////////////////////////////////////////// // 3.1. Define Upcast methods from V1 to V3, and from V2 to V3 diff --git a/src/EventSourcingTests/end_to_end_event_capture_and_fetching_the_stream.cs b/src/EventSourcingTests/end_to_end_event_capture_and_fetching_the_stream.cs index c0af123513..0ec58e3624 100644 --- a/src/EventSourcingTests/end_to_end_event_capture_and_fetching_the_stream.cs +++ b/src/EventSourcingTests/end_to_end_event_capture_and_fetching_the_stream.cs @@ -5,7 +5,6 @@ using EventSourcingTests.Projections; using EventSourcingTests.Utils; using JasperFx; -using JasperFx.CodeGeneration; using Marten; using Marten.Events.Projections; using Marten.Storage; diff --git a/src/EventStoreMigrations/Program.cs b/src/EventStoreMigrations/Program.cs index 4a10afc1df..4ae3148cbc 100644 --- a/src/EventStoreMigrations/Program.cs +++ b/src/EventStoreMigrations/Program.cs @@ -1,5 +1,4 @@ using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Events; using Marten; using Marten.Events; @@ -26,8 +25,6 @@ public static IHostBuilder CreateHostBuilder(string[] args) opts.DatabaseSchemaName = "cli"; opts.Connection(ConnectionSource.ConnectionString); - opts.GeneratedCodeMode = TypeLoadMode.Dynamic; - opts.Events.StreamIdentity = StreamIdentity.AsString; opts.Events.MetadataConfig.HeadersEnabled = true; opts.Events.AddEventType(typeof(Started)); diff --git a/src/Marten.AotSmoke/Program.cs b/src/Marten.AotSmoke/Program.cs index db7071ff76..e22d550834 100644 --- a/src/Marten.AotSmoke/Program.cs +++ b/src/Marten.AotSmoke/Program.cs @@ -37,8 +37,6 @@ // (The build itself doesn't catch a missing emission — the SG silently // skips when its preconditions don't hold; the runtime check is the // sentinel.) -// - StoreOptions.GeneratedCodeMode = TypeLoadMode.Static — pins the -// consumer profile that AOT-publishing apps would set. // - Host.CreateApplicationBuilder + Build + DI resolution of // IDocumentStore — the boot path consumers actually hit. // @@ -55,7 +53,6 @@ // libraries — the static inventory at audit/projections-inventory.md // covers that. This program is the regression sentinel. -using JasperFx.CodeGeneration; using JasperFx.Events; using JasperFx.Events.Projections; using Marten; @@ -72,11 +69,8 @@ { opts.Connection(placeholderConnectionString); - // Pin the consumer profile an AOT-publishing app would set. Marten 9 - // retired the runtime-codegen path entirely, so this setting is a - // documented no-op kept for source-compatibility — exercising it here - // pins that compile-time contract. - opts.GeneratedCodeMode = TypeLoadMode.Static; + // Marten 9 retired the runtime-codegen path entirely — there's nothing + // to pin here for AOT consumers, the closed-shape adapter is always used. // Exercise the document-mapping surface — registers the closed-shape // IDocumentStorage path (#4404). DocumentMapping infers the Id member diff --git a/src/Marten.Testing.OtherAssembly/ShortGuid.cs b/src/Marten.Testing.OtherAssembly/ShortGuid.cs index b37a38d574..ad80012190 100644 --- a/src/Marten.Testing.OtherAssembly/ShortGuid.cs +++ b/src/Marten.Testing.OtherAssembly/ShortGuid.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.Core.Reflection; -using Marten.Schema; using Marten.Schema.Identity; namespace Marten.Testing.OtherAssembly; @@ -18,14 +13,5 @@ public static string NewGuid() public class String2IdGeneration: IIdGeneration { - public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) - { - var use = new Use(mapping.DocumentType); - method.Frames.Code( - "if ({0}." + mapping.IdMember.Name + " == null) _setter({0}, global::" + - typeof(ShortGuid).FullNameInCode() + ".NewGuid());", use); - method.Frames.Code("return {0}." + mapping.IdMember.Name + ";", use); - } - public bool IsNumeric => false; } diff --git a/src/Marten.Testing/Harness/DefaultStoreFixture.cs b/src/Marten.Testing/Harness/DefaultStoreFixture.cs index a9001d1e23..627a69464f 100644 --- a/src/Marten.Testing/Harness/DefaultStoreFixture.cs +++ b/src/Marten.Testing/Harness/DefaultStoreFixture.cs @@ -1,8 +1,6 @@ using System; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Util; using JasperFx.Events; using Marten.Events; using Npgsql; @@ -36,9 +34,6 @@ public Task InitializeAsync() { opts.Connection(ConnectionSource.ConnectionString); opts.AutoCreateSchemaObjects = AutoCreate.All; - - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.ApplicationAssembly = GetType().Assembly; }); // Do this exactly once and no more. diff --git a/src/Marten.Testing/Harness/IntegrationContext.cs b/src/Marten.Testing/Harness/IntegrationContext.cs index cfaff2362f..a8bd5a356e 100644 --- a/src/Marten.Testing/Harness/IntegrationContext.cs +++ b/src/Marten.Testing/Harness/IntegrationContext.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using JasperFx.Events; using Marten.Events; @@ -70,9 +69,6 @@ protected IDocumentStore SeparateStore() { opts.Connection(ConnectionSource.ConnectionString); opts.AutoCreateSchemaObjects = AutoCreate.All; - - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.ApplicationAssembly = GetType().Assembly; }); } diff --git a/src/Marten/DocumentStore.CompiledQueryCollection.cs b/src/Marten/DocumentStore.CompiledQueryCollection.cs index fc8b42d449..88b69e4de2 100644 --- a/src/Marten/DocumentStore.CompiledQueryCollection.cs +++ b/src/Marten/DocumentStore.CompiledQueryCollection.cs @@ -4,7 +4,6 @@ using System.Threading.Tasks; using ImTools; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Core; using JasperFx.Core.Reflection; using Marten.Exceptions; @@ -67,9 +66,8 @@ internal ICompiledQuerySource GetCompiledQuerySourceFor(ICompiledQue // registered a descriptor for this query type (consumer assembly missing // the [JasperFxAssembly] marker, or a query type registered at runtime via // reflection) we build the descriptor reflectively from the freshly-walked - // CompiledQueryPlan and cache it in the registry. Subsequent calls hit the - // fast registry path. Replaces the previous fallthrough to - // CompiledQuerySourceBuilder / JasperFx.RuntimeCompiler. + // CompiledQueryPlan and cache it in the registry. Subsequent calls hit + // the fast registry path. descriptor = RuntimeCompiledQueryDescriptorFactory.Build(plan); CompiledQueryHandlerRegistry.Register(query.GetType(), descriptor); } @@ -84,29 +82,13 @@ internal ICompiledQuerySource GetCompiledQuerySourceFor(ICompiledQue } } -public partial class DocumentStore: ICodeFileCollection +public partial class DocumentStore { private readonly CompiledQueryCollection _dirtyTrackedCompiledQueries; private readonly CompiledQueryCollection _identityMapCompiledQueries; private readonly CompiledQueryCollection _lightweightCompiledQueries; private readonly CompiledQueryCollection _queryOnlyCompiledQueries; - public GenerationRules Rules => Options.CreateGenerationRules(); - - IReadOnlyList ICodeFileCollection.BuildFiles() - { - // #4454 Phase 1E: compiled queries no longer emit ICodeFile entries — - // dispatch runs through CompiledQueryHandlerRegistry / source-gen + - // RuntimeCompiledQueryDescriptorFactory. The codegen path (and the - // `dotnet marten codegen` CLI surface that consumed it) is retired - // entirely in Phase 5. Returning an empty list keeps DocumentStore's - // ICodeFileCollection contract intact for non-compiled-query consumers - // until then. - return Array.Empty(); - } - - string ICodeFileCollection.ChildNamespace { get; } = "CompiledQueries"; - internal ICompiledQuerySource GetCompiledQuerySourceFor(ICompiledQuery query, QuerySession session) where TDoc : notnull { diff --git a/src/Marten/DocumentStore.DocumentStoreUsage.cs b/src/Marten/DocumentStore.DocumentStoreUsage.cs index 45b74b503d..90d2e03315 100644 --- a/src/Marten/DocumentStore.DocumentStoreUsage.cs +++ b/src/Marten/DocumentStore.DocumentStoreUsage.cs @@ -33,19 +33,6 @@ public partial class DocumentStore : IDocumentStoreUsageSource EnumStorage = Options.EnumStorage.ToString(), }; - // Code-generation snapshot — wrapped as a child descriptor (rather than - // flattened) so the four obsolete-on-StoreOptions properties stay - // cohesive even after they ride out the deprecation window. -#pragma warning disable CS0618 // intentional: building a diagnostic snapshot of obsolete settings - usage.CodeGeneration = new CodeGenerationDescriptor - { - ApplicationAssembly = Options.ApplicationAssembly?.GetName().FullName, - SourceCodeWritingEnabled = Options.SourceCodeWritingEnabled, - GeneratedCodeOutputPath = Options.GeneratedCodeOutputPath, - GeneratedCodeMode = Options.GeneratedCodeMode.ToString(), - }; -#pragma warning restore CS0618 - // Per-document-type mappings — Documents collection. Skip mappings that // don't emit schema (structural-typed, internal-only) so the snapshot // matches what an operator would see in the database. diff --git a/src/Marten/DocumentStore.cs b/src/Marten/DocumentStore.cs index bdbff84d6e..6a7a0159bc 100644 --- a/src/Marten/DocumentStore.cs +++ b/src/Marten/DocumentStore.cs @@ -8,7 +8,6 @@ using System.Threading.Tasks; using System.Transactions; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Core; using JasperFx.Core.Reflection; using JasperFx.Descriptors; @@ -87,32 +86,13 @@ public DocumentStore(StoreOptions options) // is called with a type that has [NaturalKey]. Assembly-level scanning was // removed because it caused spurious InvalidProjectionException failures // when test projects share compile references with incompatible stream identity types. - // - // 9.0: Skip AssertValidity when running in TypeLoadMode.Static (#4305). - // Static mode means the runtime is loading pre-generated artifacts that - // would not have been emitted if validation had failed at codegen time — - // re-running the validation walk on every host start is pure cold-start - // overhead. Dynamic and Auto modes still validate, so any hot-reload or - // first-run codegen path keeps the existing fail-fast behavior. - if (Options.GeneratedCodeMode != TypeLoadMode.Static) - { - Options.Projections.AssertValidity(Options); - } + Options.Projections.AssertValidity(Options); if (Options.LogFactory != null) { Options.Projections.AttachLogging(Options.LogFactory); } - // marten#4370 Phase 2: compute the codegen snapshot verdict and log - // any rejection. The verdict is observed but not yet acted on — - // Phase 2 ships the plumbing so subsequent PRs can add concrete - // snapshot artifacts (event-name map, document-storage map, - // projection apply factories) each gated by this verdict. - MartenSnapshot.VerifyAtBoot( - Options, - Options.LogFactory?.CreateLogger("Marten.Snapshot")); - Advanced = new AdvancedOperations(this); Diagnostics = new Diagnostics(this); @@ -136,12 +116,6 @@ public DocumentStore(StoreOptions options) } Identity = new(Options.StoreName.ToLowerInvariant(), "marten"); - - // marten#4370 Phase 2: persist the fingerprint at the end of - // construction so the next boot's VerifyAtBoot has a baseline - // to compare against. Best-effort — persistence failure must not - // break construction. - MartenSnapshot.PersistFingerprint(Options); } public ITenancy Tenancy => Options.Tenancy; diff --git a/src/Marten/Events/EventGraph.GeneratesCode.cs b/src/Marten/Events/EventGraph.GeneratesCode.cs deleted file mode 100644 index 06b5ccb3eb..0000000000 --- a/src/Marten/Events/EventGraph.GeneratesCode.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Reflection; -using System.Threading.Tasks; -using JasperFx.CodeGeneration; -using JasperFx.Events; -using Marten.Internal.Storage; -using System.Diagnostics.CodeAnalysis; - -namespace Marten.Events; - -#nullable enable -public partial class EventGraph: ICodeFile -{ - internal DocumentProvider? Provider { get; private set; } - - void ICodeFile.AssembleTypes(GeneratedAssembly assembly) - { - // #4454 Phase 2: event storage is fully closed-shape — no Roslyn emit - // for the event-store write path. The ICodeFile contract is preserved - // for now so DocumentStore's ICodeFileCollection.BuildFiles aggregation - // still walks EventGraph; Phase 5 retires the contract entirely. - } - - public bool AttachTypesSynchronously(GenerationRules rules, Assembly assembly, IServiceProvider? services, - string containingNamespace) - { - // Closed-shape adapter is constructed directly — no codegen lookup, - // no JasperFx.RuntimeCompiler fallback. ProviderGraph triggers this - // path on first IEvent storage request. - var closedShape = new Marten.EventStorage.ClosedShapeEventDocumentStorage(Options); - Provider = new DocumentProvider(null, closedShape, closedShape, closedShape, closedShape); - return true; - } - - Task ICodeFile.AttachTypes(GenerationRules rules, Assembly assembly, IServiceProvider? services, - string containingNamespace) - { - var found = AttachTypesSynchronously(rules, assembly, services, containingNamespace); - return Task.FromResult(found); - } - - string ICodeFile.FileName => "EventStorage"; - -} diff --git a/src/Marten/Events/EventGraph.cs b/src/Marten/Events/EventGraph.cs index 0059eba24c..a33ed65984 100644 --- a/src/Marten/Events/EventGraph.cs +++ b/src/Marten/Events/EventGraph.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using ImTools; using JasperFx.Blocks; -using JasperFx.CodeGeneration; using JasperFx.Core; using JasperFx.Core.Reflection; using JasperFx.Descriptors; @@ -42,7 +41,7 @@ namespace Marten.Events; Justification = "Class-level: uses Type.MakeGenericType / MethodInfo.MakeGenericMethod / Activator.CreateInstance / FastExpressionCompiler — runtime code generation. AOT consumers pre-generate codegen artifacts (codegen write) and supply source-generator-backed serializer impls per the AOT publishing guide.")] public partial class EventGraph: EventRegistry, IEventStoreOptions, IReadOnlyEventStoreOptions, IDisposable, IAsyncDisposable, - IAggregationSourceFactory, IDescribeMyself, ICodeFileCollection + IAggregationSourceFactory, IDescribeMyself { private readonly Cache _aggregateNameByType = new(type => type.IsGenericType ? type.ShortNameInCode() : type.Name.ToTableAlias()); @@ -777,13 +776,19 @@ private void autoDiscoverTagTypesFromProjections() } } - IReadOnlyList ICodeFileCollection.BuildFiles() - { - return [this]; - } + public List GlobalAggregates { get; } = new(); - string ICodeFileCollection.ChildNamespace => "EventStore"; + internal Marten.Internal.Storage.DocumentProvider? Provider { get; private set; } - GenerationRules ICodeFileCollection.Rules => Options.CreateGenerationRules(); - public List GlobalAggregates { get; } = new(); + /// + /// Constructs the closed-shape event document storage adapter for this + /// EventGraph and caches it as . The closed-shape + /// adapter is built reflectively at runtime — no codegen is involved. + /// ProviderGraph invokes this on the first IEvent storage request. + /// + internal void AttachTypesSynchronously() + { + var closedShape = new Marten.EventStorage.ClosedShapeEventDocumentStorage(Options); + Provider = new Marten.Internal.Storage.DocumentProvider(null!, closedShape, closedShape, closedShape, closedShape); + } } diff --git a/src/Marten/Events/Projections/Flattened/DecrementMap.cs b/src/Marten/Events/Projections/Flattened/DecrementMap.cs index 4351288d40..df671d7ef4 100644 --- a/src/Marten/Events/Projections/Flattened/DecrementMap.cs +++ b/src/Marten/Events/Projections/Flattened/DecrementMap.cs @@ -1,5 +1,4 @@ using System; -using JasperFx.CodeGeneration.Model; using Weasel.Postgresql.Tables; namespace Marten.Events.Projections.Flattened; diff --git a/src/Marten/Events/Projections/Flattened/IColumnMap.cs b/src/Marten/Events/Projections/Flattened/IColumnMap.cs index 6145e13732..420ef095c9 100644 --- a/src/Marten/Events/Projections/Flattened/IColumnMap.cs +++ b/src/Marten/Events/Projections/Flattened/IColumnMap.cs @@ -1,4 +1,3 @@ -using JasperFx.CodeGeneration.Model; using Weasel.Postgresql.Tables; namespace Marten.Events.Projections.Flattened; diff --git a/src/Marten/Events/Projections/Flattened/IncrementMap.cs b/src/Marten/Events/Projections/Flattened/IncrementMap.cs index 78c4547a63..ac755dabdf 100644 --- a/src/Marten/Events/Projections/Flattened/IncrementMap.cs +++ b/src/Marten/Events/Projections/Flattened/IncrementMap.cs @@ -1,5 +1,4 @@ using System; -using JasperFx.CodeGeneration.Model; using Weasel.Postgresql.Tables; namespace Marten.Events.Projections.Flattened; diff --git a/src/Marten/Events/Projections/Flattened/MemberMap.cs b/src/Marten/Events/Projections/Flattened/MemberMap.cs index 74f90e57d2..d08183342e 100644 --- a/src/Marten/Events/Projections/Flattened/MemberMap.cs +++ b/src/Marten/Events/Projections/Flattened/MemberMap.cs @@ -3,7 +3,6 @@ using System.Linq.Expressions; using System.Reflection; using System.Text; -using JasperFx.CodeGeneration.Model; using JasperFx.Core; using Marten.Linq.Parsing; using Marten.Util; diff --git a/src/Marten/Events/Projections/Flattened/SetValueMap.cs b/src/Marten/Events/Projections/Flattened/SetValueMap.cs index 6d08ac0f51..e83fc7ffaa 100644 --- a/src/Marten/Events/Projections/Flattened/SetValueMap.cs +++ b/src/Marten/Events/Projections/Flattened/SetValueMap.cs @@ -1,5 +1,4 @@ using System; -using JasperFx.CodeGeneration.Model; using Weasel.Postgresql.Tables; namespace Marten.Events.Projections.Flattened; diff --git a/src/Marten/Events/Schema/VersionColumn.cs b/src/Marten/Events/Schema/VersionColumn.cs index b11264cd1f..0242840be0 100644 --- a/src/Marten/Events/Schema/VersionColumn.cs +++ b/src/Marten/Events/Schema/VersionColumn.cs @@ -1,8 +1,3 @@ -using System.Diagnostics.CodeAnalysis; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using Npgsql; - namespace Marten.Events.Schema; internal class VersionColumn: EventTableColumn diff --git a/src/Marten/Events/TestSupport/ProjectionScenario.EventOperations.cs b/src/Marten/Events/TestSupport/ProjectionScenario.EventOperations.cs index 1c40cd54f7..dbb274478f 100644 --- a/src/Marten/Events/TestSupport/ProjectionScenario.EventOperations.cs +++ b/src/Marten/Events/TestSupport/ProjectionScenario.EventOperations.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core; using JasperFx.Core.Reflection; using JasperFx.Events; diff --git a/src/Marten/Exceptions/EventDeserializationFailureException.cs b/src/Marten/Exceptions/EventDeserializationFailureException.cs index 961c81e24e..244cc20ce6 100644 --- a/src/Marten/Exceptions/EventDeserializationFailureException.cs +++ b/src/Marten/Exceptions/EventDeserializationFailureException.cs @@ -1,5 +1,4 @@ using System; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using JasperFx.Events; using JasperFx.Events.Daemon; diff --git a/src/Marten/Exceptions/InvalidCompiledQueryException.cs b/src/Marten/Exceptions/InvalidCompiledQueryException.cs index e2abf8bb2e..9b9a406e3a 100644 --- a/src/Marten/Exceptions/InvalidCompiledQueryException.cs +++ b/src/Marten/Exceptions/InvalidCompiledQueryException.cs @@ -1,6 +1,5 @@ using System; using System.Runtime.Serialization; -using JasperFx.CodeGeneration; using JasperFx.Core; using JasperFx.Core.Reflection; diff --git a/src/Marten/Internal/CodeGeneration/FrameCollectionExtensions.cs b/src/Marten/Internal/CodeGeneration/FrameCollectionExtensions.cs deleted file mode 100644 index 30758c74cb..0000000000 --- a/src/Marten/Internal/CodeGeneration/FrameCollectionExtensions.cs +++ /dev/null @@ -1,314 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Threading; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; -using JasperFx.Core; -using JasperFx.Core.Reflection; -using Marten.Events.CodeGeneration; -using Marten.Linq.Parsing; -using Marten.Schema; -using Marten.Util; -using Weasel.Postgresql; -using System.Diagnostics.CodeAnalysis; - -namespace Marten.Internal.CodeGeneration; - -[UnconditionalSuppressMessage("Trimming", "IL2026", - Justification = "Class-level: consumes RUC-annotated members (ISerializer, JasperFx.Events aggregator graph, CloseAndBuildAs / GenericFactoryCache fallbacks, FastExpressionCompiler). Document/event/projection types flow in from StoreOptions / Schema.For() / projection registration and are preserved per the AOT publishing guide; AOT consumers supply a source-generator-backed serializer + pre-generated codegen artifacts.")] -[UnconditionalSuppressMessage("Trimming", "IL2070", - Justification = "Class-level: reflects PublicMethods/PublicProperties on a Type whose runtime instance is preserved at the StoreOptions / projection-registration boundary.")] -[UnconditionalSuppressMessage("AOT", "IL3050", - Justification = "Class-level: uses Type.MakeGenericType / MethodInfo.MakeGenericMethod / Activator.CreateInstance / FastExpressionCompiler — runtime code generation. AOT consumers pre-generate codegen artifacts (codegen write) and supply source-generator-backed serializer impls per the AOT publishing guide.")] -internal static class FrameCollectionExtensions -{ - public const string DocumentVariableName = "document"; - - public static void StoreInIdentityMap(this FramesCollection frames, DocumentMapping mapping) - { - frames.Code("_identityMap[id] = document;"); - } - - public static void StoreTracker(this FramesCollection frames) - { - frames.Code("StoreTracker({0}, document);", Use.Type()); - } - - public static void DeserializeDocument(this FramesCollection frames, DocumentMapping mapping, int index) - { - var documentType = mapping.DocumentType; - var document = new Variable(documentType, DocumentVariableName); - if (mapping is DocumentMapping d) - { - if (!d.IsHierarchy()) - { - frames.Code($@" -{documentType.FullNameInCode()} document; -document = _serializer.FromJson<{documentType.FullNameInCode()}>(reader, {index}); -").Creates(document); - } - else - { - // Hierarchy path is different - frames.Code($@" -{documentType.FullNameInCode()} document; -var typeAlias = reader.GetFieldValue({index + 1}); -document = ({documentType.FullNameInCode()}) _serializer.FromJson(_mapping.TypeFor(typeAlias), reader, {index}); -").Creates(document); - } - } - } - - public static void MarkAsLoaded(this FramesCollection frames) - { - frames.Code($"{{0}}.{nameof(IMartenSession.MarkAsDocumentLoaded)}(id, document);", - Use.Type()); - } - - public static void DeserializeDocumentAsync(this FramesCollection frames, DocumentMapping mapping, int index) - { - var documentType = mapping.DocumentType; - var document = new Variable(documentType, DocumentVariableName); - - if (!mapping.IsHierarchy()) - { - frames.CodeAsync($@" -{documentType.FullNameInCode()} document; -document = await _serializer.FromJsonAsync<{documentType.FullNameInCode()}>(reader, {index}, {{0}}).ConfigureAwait(false); -", Use.Type()).Creates(document); - } - else - { - frames.CodeAsync($@" -{documentType.FullNameInCode()} document; -var typeAlias = await reader.GetFieldValueAsync({index + 1}, {{0}}).ConfigureAwait(false); -document = ({documentType.FullNameInCode()}) (await _serializer.FromJsonAsync(_mapping.TypeFor(typeAlias), reader, {index}, {{0}}).ConfigureAwait(false)); -", Use.Type()).Creates(document); - } - } - - /// - /// Generates the necessary setter code to set a value of a document. - /// Handles internal/private setters - /// - /// - /// - /// - /// - /// - public static void SetMemberValue(this FramesCollection frames, MemberInfo member, string variableName, - Type documentType, GeneratedType generatedType) - { - if (member is PropertyInfo property) - { - if (property.CanWrite) - { - if (property.SetMethod.IsPublic) - { - frames.SetPublicMemberValue(member, variableName, documentType); - } - else - { - var setterFieldName = generatedType.InitializeLambdaSetterProperty(member, documentType); - frames.Code($"{setterFieldName}({{0}}, {variableName});", new Use(documentType)); - } - - return; - } - } - else if (member is FieldInfo field) - { - if (field.IsPublic) - { - frames.SetPublicMemberValue(member, variableName, documentType); - } - else - { - var setterFieldName = generatedType.InitializeLambdaSetterProperty(member, documentType); - frames.Code($"{setterFieldName}({{0}}, {variableName});", new Use(documentType)); - } - - return; - } - - throw new ArgumentOutOfRangeException(nameof(member), $"MemberInfo {member} is not valid in this usage. "); - } - - public static string InitializeLambdaSetterProperty(this GeneratedType generatedType, MemberInfo member, - Type documentType) - { - var setterFieldName = $"{member.Name}Writer"; - - if (generatedType.Setters.All(x => x.PropName != setterFieldName)) - { - var memberType = member.GetRawMemberType()!; - var actionType = typeof(Action<,>).MakeGenericType(documentType, memberType); - var expression = - $"{typeof(LambdaBuilder).FullNameInCode()}.{nameof(LambdaBuilder.Setter)}<{documentType.FullNameInCode()},{memberType.FullNameInCode()}>(typeof({documentType.FullNameInCode()}).GetProperty(\"{member.Name}\"))"; - - var constant = new Variable(actionType, expression); - - var setter = Setter.StaticReadOnly(setterFieldName, constant); - - generatedType.Setters.Add(setter); - } - - return setterFieldName; - } - - private static void SetPublicMemberValue(this FramesCollection frames, MemberInfo member, string variableName, - Type documentType) - { - frames.Code($"{{0}}.{member.Name} = {variableName};", new Use(documentType)); - } - - public static void AssignMemberFromReader(this GeneratedMethod method, GeneratedType generatedType, - int index, - Expression> memberExpression) - { - var member = MemberFinder.Determine(memberExpression).Single(); - var variableName = member.Name.ToCamelCase(); - method.Frames.Code( - $"var {variableName} = reader.GetFieldValue<{member.GetMemberType()!.FullNameInCode()}>({index});"); - - method.Frames.SetMemberValue(member, variableName, typeof(T), generatedType); - } - - public static void AssignMemberFromReader(this GeneratedMethod method, GeneratedType generatedType, int index, - Type documentType, string memberName) - { - var member = documentType.GetMember(memberName).Single(); - var variableName = member.Name.ToCamelCase(); - method.Frames.Code( - $"var {variableName} = reader.GetFieldValue<{member.GetMemberType()!.FullNameInCode()}>({index});"); - - method.Frames.SetMemberValue(member, variableName, documentType, generatedType); - } - - public static void AssignMemberFromReader(this GeneratedMethod method, GeneratedType generatedType, - int index, - Expression>> memberExpression) - { - var member = FindMembers.Determine(memberExpression).Single(); - var variableName = member.Name.ToCamelCase(); - - method.Frames.Code( - $"var {variableName} = _options.Serializer().FromJson<{member.GetMemberType()!.FullNameInCode()}>(reader, {index});"); - - method.Frames.SetMemberValue(member, variableName, typeof(T), generatedType); - } - - public static void AssignMemberFromReaderAsync(this GeneratedMethod method, GeneratedType generatedType, - int index, - Expression> memberExpression) - { - var member = MemberFinder.Determine(memberExpression).Single(); - var variableName = member.Name.ToCamelCase(); - method.Frames.Code( - $"var {variableName} = await reader.GetFieldValueAsync<{member.GetMemberType()!.FullNameInCode()}>({index}, {{0}}).ConfigureAwait(false);", - Use.Type()); - - method.Frames.SetMemberValue(member, variableName, typeof(T), generatedType); - } - - public static void AssignMemberFromReaderAsync(this GeneratedMethod method, GeneratedType generatedType, - int index, - Expression>> memberExpression) - { - var member = FindMembers.Determine(memberExpression).Single(); - var variableName = member.Name.ToCamelCase(); - - method.Frames.Code( - $"var {variableName} = await _options.Serializer().FromJsonAsync<{member.GetMemberType()!.FullNameInCode()}>(reader, {index}, {{0}}).ConfigureAwait(false);", - Use.Type()); - - method.Frames.SetMemberValue(member, variableName, typeof(T), generatedType); - } - - public static void AssignMemberFromReaderAsync(this GeneratedMethod method, GeneratedType generatedType, - int index, - Type documentType, string memberName) - { - var member = documentType.GetMember(memberName).Single(); - var variableName = member.Name.ToCamelCase(); - method.Frames.Code( - $"var {variableName} = await reader.GetFieldValueAsync<{member.GetMemberType()!.FullNameInCode()}>({index}, {{0}}).ConfigureAwait(false);", - Use.Type()); - - method.Frames.SetMemberValue(member, variableName, documentType, generatedType); - } - - public static void IfDbReaderValueIsNotNull(this GeneratedMethod method, int index, Action action) - { - method.Frames.Code($"if (!reader.IsDBNull({index}))"); - method.Frames.Code("{{"); - - action(); - - method.Frames.Code("}}"); - } - - public static void IfDbReaderValueIsNotNullAsync(this GeneratedMethod method, int index, Action action) - { - method.Frames.CodeAsync($"if (!(await reader.IsDBNullAsync({index}, token).ConfigureAwait(false)))"); - method.Frames.Code("{{"); - - action(); - - method.Frames.Code("}}"); - } - - public static void SetParameterFromMemberNonNullableString(this GeneratedMethod method, int index, - Expression> memberExpression) - { - var member = MemberFinder.Determine(memberExpression).Single(); - method.Frames.Code($"var parameter{index} = parameterBuilder.{nameof(IGroupedParameterBuilder.AppendParameter)}({{1}}.{member.Name});", Use.Type()); - method.Frames.Code($"parameter{index}.NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Text;"); - } - - public static void SetParameterFromMember(this GeneratedMethod method, int index, - Expression> memberExpression) - { - var member = MemberFinder.Determine(memberExpression).Single(); - var memberType = member.GetMemberType(); - var pgType = PostgresqlProvider.Instance.ToParameterType(memberType!); - - if (memberType == typeof(string)) - { - method.Frames.Code( - $"var parameter{index} = {{0}}.{member.Name} != null ? parameterBuilder.{nameof(IGroupedParameterBuilder.AppendParameter)}({{0}}.{member.Name}) : parameterBuilder.{nameof(IGroupedParameterBuilder.AppendParameter)}({typeof(DBNull).FullNameInCode()}.Value);", - Use.Type()); - method.Frames.Code($"parameter{index}.NpgsqlDbType = {{0}};", pgType); - } - else - { - method.Frames.Code($"var parameter{index} = parameterBuilder.{nameof(IGroupedParameterBuilder.AppendParameter)}({{0}}.{member.Name});", Use.Type()); - method.Frames.Code($"parameter{index}.NpgsqlDbType = {{0}};", pgType); - - } - } - - private interface ISetterBuilder - { - void Add(GeneratedType generatedType, MemberInfo member, string setterFieldName); - } - - private class SetterBuilder: ISetterBuilder - { - public void Add(GeneratedType generatedType, MemberInfo member, string setterFieldName) - { - var writer = LambdaBuilder.Setter(member); - var setter = - new Setter(typeof(Action), setterFieldName) - { - InitialValue = writer, Type = SetterType.ReadWrite - }; - - generatedType.Setters.Add(setter); - } - } -} diff --git a/src/Marten/Internal/CodeGeneration/MartenSnapshot.cs b/src/Marten/Internal/CodeGeneration/MartenSnapshot.cs deleted file mode 100644 index 146f8c3775..0000000000 --- a/src/Marten/Internal/CodeGeneration/MartenSnapshot.cs +++ /dev/null @@ -1,182 +0,0 @@ -#nullable enable -using System; -using System.IO; -using System.Reflection; -using JasperFx.CodeGeneration.Snapshots; -using Microsoft.Extensions.Logging; -using System.Diagnostics.CodeAnalysis; - -namespace Marten.Internal.CodeGeneration; - -/// -/// Phase 2 of marten#4370. -/// Marten-side consumer of the codegen snapshot invalidation contract that JasperFx 2.0 -/// ships (). Wires into the shared -/// fingerprint persistence + verdict flow. -/// -/// -/// -/// What Phase 2 ships (this class). Plumbing: compute Marten's canonical input -/// hash via , persist the fingerprint to disk via -/// , verify at boot via , -/// log the verdict via . The verdict -/// is computed but does not yet gate any expensive boot work — Phase 2 deliberately -/// stops at the plumbing so subsequent PRs can add concrete artifacts (event-name map, -/// document-storage map, projection apply factories) incrementally, each gated by the -/// verdict that's already being computed. -/// -/// -/// Fingerprint scope. One fingerprint per instance, -/// persisted as fingerprint.json in the store's generated-code output path. -/// Multi-store hosts get one fingerprint per store; the -/// contributes to so two stores at the same -/// output path don't collide. -/// -/// -/// Soft-fallback policy. Per the contract, a rejected -/// snapshot logs via at -/// and the consumer continues with the live discovery -/// path. Operators grep for JasperFx.Codegen: snapshot rejected when diagnosing -/// slow first-boot-after-deploy. -/// -/// -[UnconditionalSuppressMessage("Trimming", "IL2026", - Justification = "Class-level: consumes RUC-annotated members (ISerializer, JasperFx.Events aggregator graph, CloseAndBuildAs / GenericFactoryCache fallbacks, FastExpressionCompiler). Document/event/projection types flow in from StoreOptions / Schema.For() / projection registration and are preserved per the AOT publishing guide; AOT consumers supply a source-generator-backed serializer + pre-generated codegen artifacts.")] -[UnconditionalSuppressMessage("AOT", "IL3050", - Justification = "Class-level: uses Type.MakeGenericType / MethodInfo.MakeGenericMethod / Activator.CreateInstance / FastExpressionCompiler — runtime code generation. AOT consumers pre-generate codegen artifacts (codegen write) and supply source-generator-backed serializer impls per the AOT publishing guide.")] -internal static class MartenSnapshot -{ - private const string ProductName = "marten"; - - /// - /// Read + verify any persisted snapshot, log the verdict, and return it. Caller - /// can use the verdict to drive Phase 3+ artifact-loading decisions; Phase 2 - /// just logs and returns. - /// - /// Fully-composed store options. - /// - /// Optional logger; when , log calls are skipped. The - /// log signature on rejection is - /// and is part of the public stability contract. - /// - internal static SnapshotVerdict VerifyAtBoot(StoreOptions options, ILogger? logger = null) - { - ArgumentNullException.ThrowIfNull(options); - - var folder = ResolveSnapshotFolder(options); - if (folder is null) - { - // No generated-code output path is configured (and the default - // resolution couldn't produce one either) — there's nowhere to - // read a snapshot from, so treat as first boot. - return SnapshotVerdict.FirstBoot; - } - - var live = BuildFingerprint(options); - var persisted = SnapshotGate.Read(folder); - var verdict = SnapshotGate.Verify(live, persisted); - - if (verdict == SnapshotVerdict.RejectAndRegenerate && logger is not null) - { - // Public log signature — see SnapshotGate.SnapshotRejectedLogTemplate - // remarks. Operators key off this exact prefix when diagnosing. -#pragma warning disable CA2254 // Template not constant — the template IS the constant; placeholders bind at the structured-log level - logger.LogInformation( - SnapshotGate.SnapshotRejectedLogTemplate, - ProductName, - live.ProductVersion + "/" + (options.StoreName ?? ""), - DescribeReason(live, persisted!)); -#pragma warning restore CA2254 - } - - return verdict; - } - - /// - /// Persist the current fingerprint to the store's generated-code folder. Called - /// at the end of construction so the next boot's - /// can compare against a freshly-written value. Idempotent: - /// re-running with the same options produces the same fingerprint file content. - /// - /// - /// Why persist on every boot, not just at codegen write time? - /// Phase 2 plumbing keeps the snapshot path live in every mode so the contract - /// is exercised whether or not the user runs the CLI. Future phases can gate - /// persistence on the consumer actually writing artifacts (no point persisting - /// a fingerprint with nothing to invalidate), but at Phase 2 the persistence - /// itself is what's being validated. - /// - internal static void PersistFingerprint(StoreOptions options) - { - ArgumentNullException.ThrowIfNull(options); - - var folder = ResolveSnapshotFolder(options); - if (folder is null) return; - - try - { - SnapshotGate.Write(folder, BuildFingerprint(options)); - } - catch (Exception) - { - // Persistence is a cold-start optimisation, not a correctness - // requirement. Failure to write the fingerprint must not break - // DocumentStore construction. Swallow silently — the next boot - // will be FirstBoot, which is also a no-op. - } - } - - /// - /// Build a for the given options. Public-internal - /// so tests can call it directly without going through the file-system round-trip. - /// - internal static SnapshotFingerprint BuildFingerprint(StoreOptions options) - { - var canonical = MartenSnapshotInputs.Compose(options); - return new SnapshotFingerprint( - ProductName: ProductName, - ProductVersion: MartenVersion, - JasperFxVersion: JasperFxVersion, - ConfigHash: SnapshotGate.ComputeHash(canonical)); - } - - private static string? ResolveSnapshotFolder(StoreOptions options) - { - // The snapshot lives alongside Marten's generated code. CreateGenerationRules - // resolves the path with the same fallback logic that codegen-write uses - // (explicit GeneratedCodeOutputPath → AppContext.BaseDirectory/Internal/Generated, - // with StoreName appended for non-Main stores). - try - { - var rules = options.CreateGenerationRules(); - return string.IsNullOrWhiteSpace(rules.GeneratedCodeOutputPath) - ? null - : rules.GeneratedCodeOutputPath; - } - catch - { - // Best-effort: if the rules can't be built (e.g. test scenarios with - // half-configured options) we treat that as "no folder" and skip both - // verify and persist. - return null; - } - } - - private static string DescribeReason(SnapshotFingerprint live, SnapshotFingerprint persisted) - { - // Identify the field(s) that changed so the rejection log is actionable. - // Order matches typical change probability: config first (most common - // dev-time churn), then versions (which point at upgrades). - if (live.ConfigHash != persisted.ConfigHash) return "config-hash changed"; - if (live.ProductVersion != persisted.ProductVersion) return $"marten version {persisted.ProductVersion} → {live.ProductVersion}"; - if (live.JasperFxVersion != persisted.JasperFxVersion) return $"jasperfx version {persisted.JasperFxVersion} → {live.JasperFxVersion}"; - if (live.SchemaVersion != persisted.SchemaVersion) return $"snapshot schema {persisted.SchemaVersion} → {live.SchemaVersion}"; - return "fingerprint mismatch"; - } - - private static readonly string MartenVersion = - typeof(StoreOptions).Assembly.GetName().Version?.ToString() ?? "0.0.0"; - - private static readonly string JasperFxVersion = - typeof(SnapshotGate).Assembly.GetName().Version?.ToString() ?? "0.0.0"; -} diff --git a/src/Marten/Internal/CodeGeneration/MartenSnapshotInputs.cs b/src/Marten/Internal/CodeGeneration/MartenSnapshotInputs.cs deleted file mode 100644 index 164973a424..0000000000 --- a/src/Marten/Internal/CodeGeneration/MartenSnapshotInputs.cs +++ /dev/null @@ -1,159 +0,0 @@ -#nullable enable -using System; -using System.Linq; -using System.Reflection; -using System.Text; -using JasperFx.CodeGeneration; -using Marten.Events; - -namespace Marten.Internal.CodeGeneration; - -/// -/// Phase 2 of marten#4370. -/// Builds the canonical-input string that -/// hashes into . -/// The fingerprint invalidates whenever any input that would change the generated codegen -/// output (or the dispatch tables a future snapshot artifact would persist) changes. -/// -/// -/// -/// Determinism requirements. The canonical string must be stable across runs given -/// the same . That means: collections are sorted, value -/// representations are normalised (e.g. rather -/// than instance hashes), and there are no environment-dependent inputs (no -/// , no , etc.). -/// -/// -/// Laziness invariant. Per marten#4303 -/// document mappings are materialised + validated lazily on first session use, not at -/// DocumentStore.For construction. The canonical input therefore reads the -/// registration map (StorageFeatures.RegisteredDocumentTypes) rather than -/// materialised AllDocumentMappings — touching the latter at boot would force -/// CompileAndValidate on every registered type and resurrect the eager-validation -/// behaviour the 9.0 lazy refactor explicitly retired. -/// -/// -/// Input scope. The inputs are everything that can plausibly affect the boot-time -/// state a snapshot artifact would persist: -/// -/// -/// Marten version -/// -/// The registered document-type list (AssemblyQualifiedName, sorted) -/// The registered event-type alias list (alias + AssemblyQualifiedName pairs, sorted by alias) -/// The registered projection-type list (AssemblyQualifiedName, sorted) -/// Serializer type -/// Boot-relevant flags -/// (, -/// , -/// , -/// , -/// ) -/// -/// -/// The JasperFx version is supplied via the -/// itself (separate field), not folded into the canonical input — invalidation on a JasperFx -/// upgrade comes for free from the fingerprint comparison. -/// -/// -internal static class MartenSnapshotInputs -{ - /// - /// Sentinel inserted between input groups in the canonical string. Picked to be - /// unambiguous against the AssemblyQualifiedName / alias / flag-value content, - /// none of which contain U+241E (record separator). - /// - private const char GroupSeparator = '␞'; - - /// - /// Inter-record separator within a group (e.g. between two doc-type AQNs). - /// Same rationale — U+241F is record-unit separator and won't appear in CLR - /// names or string flag values. - /// - private const char RecordSeparator = '␟'; - - /// - /// Build the canonical-input string from a fully-composed . - /// Caller is responsible for ensuring all registrations (doc types, projections, - /// event mappings) have completed before invoking this — typically after - /// + the event-graph init pass. - /// - internal static string Compose(StoreOptions options) - { - ArgumentNullException.ThrowIfNull(options); - - var sb = new StringBuilder(capacity: 1024); - - AppendGroup(sb, "marten-version", typeof(StoreOptions).Assembly.GetName().Version?.ToString() ?? ""); - AppendGroup(sb, "store-name", options.StoreName ?? ""); - - // Document types — read from the registration map (RegisteredDocumentTypes), - // not AllDocumentMappings. Per marten#4303 mapping materialisation + - // validation is deferred to first session use; calling BuildAllMappings - // here would surface configuration errors (e.g. missing Id property) at - // DocumentStore.For() time and break the documented lazy contract — see - // DocumentMappingTests.cannot_use_a_doc_type_with_no_id_with_store. - // RegisteredDocumentTypes returns every type that was queued via - // Schema.For() (plus internal registrations like DeadLetterEvent) - // without triggering CompileAndValidate. Sort by AQN for run stability. - var docTypes = options.Storage - .RegisteredDocumentTypes - .Select(t => t.AssemblyQualifiedName ?? t.FullName ?? "") - .Where(s => s.Length > 0) - .OrderBy(s => s, StringComparer.Ordinal) - .ToArray(); - AppendList(sb, "doc-types", docTypes); - - // Event-type aliases — sort by alias. Pair = alias + AQN so an aliased - // rename of the same underlying type invalidates the snapshot. - var eventAliases = options.EventGraph.AllEvents() - .Select(m => m.EventTypeName + "=" + (m.DocumentType.AssemblyQualifiedName ?? "")) - .OrderBy(s => s, StringComparer.Ordinal) - .ToArray(); - AppendList(sb, "event-aliases", eventAliases); - - // Projection types — sort by AQN. PublishedTypes is part of the - // IProjectionSource contract and provides a stable identifier. - var projectionTypes = options.Projections.All - .Select(p => p.GetType().AssemblyQualifiedName ?? p.GetType().FullName ?? "") - .Where(s => s.Length > 0) - .OrderBy(s => s, StringComparer.Ordinal) - .ToArray(); - AppendList(sb, "projection-types", projectionTypes); - - // Serializer — affects JSON shape, which affects generated code. - AppendGroup(sb, "serializer-type", - options.Serializer().GetType().AssemblyQualifiedName ?? ""); - - // Boot-relevant flags. Each new entry here is a deliberate design call — - // only flags that would change the generated output or the dispatch tables - // belong. Adding a flag here will invalidate every existing snapshot the - // first time it's read, by design. - AppendGroup(sb, "schema-name", options.DatabaseSchemaName ?? ""); - AppendGroup(sb, "code-mode", options.GeneratedCodeMode.ToString()); - AppendGroup(sb, "stream-identity", options.EventGraph.StreamIdentity.ToString()); - AppendGroup(sb, "ext-progression-tracking", - options.EventGraph.EnableExtendedProgressionTracking.ToString()); - AppendGroup(sb, "strict-stream-identity", - options.EventGraph.EnableStrictStreamIdentityEnforcement.ToString()); - - return sb.ToString(); - } - - private static void AppendGroup(StringBuilder sb, string key, string value) - { - if (sb.Length > 0) sb.Append(GroupSeparator); - sb.Append(key).Append('=').Append(value); - } - - private static void AppendList(StringBuilder sb, string key, string[] items) - { - if (sb.Length > 0) sb.Append(GroupSeparator); - sb.Append(key).Append('='); - for (var i = 0; i < items.Length; i++) - { - if (i > 0) sb.Append(RecordSeparator); - sb.Append(items[i]); - } - } -} diff --git a/src/Marten/Internal/CompiledQueries/CompiledQueryHandlerRegistry.cs b/src/Marten/Internal/CompiledQueries/CompiledQueryHandlerRegistry.cs index 38b2bea3a1..61501d015a 100644 --- a/src/Marten/Internal/CompiledQueries/CompiledQueryHandlerRegistry.cs +++ b/src/Marten/Internal/CompiledQueries/CompiledQueryHandlerRegistry.cs @@ -15,13 +15,12 @@ namespace Marten.Internal.CompiledQueries; /// /// /// This is the implicit-opt-in surface for #4405's compiled-query source-gen -/// PoC. The consumer never calls directly — the +/// path. The consumer never calls directly — the /// generator does it from per-query [ModuleInitializer] shims. The /// runtime side (CompiledQueryCollection.GetCompiledQuerySourceFor) -/// consults the registry on first use of each query type. If a descriptor is -/// present, the source-gen path is taken; if not, the PoC bridge currently -/// falls through to JasperFx.RuntimeCompiler. The bridge is removed -/// when iteration 4 lands green — at that point a miss throws. +/// consults the registry on first use of each query type. A miss falls back +/// to , which builds a +/// descriptor reflectively from the walked query plan and caches it. /// /// /// The registry is intentionally a process-wide static. Compiled query diff --git a/src/Marten/Internal/ProviderGraph.cs b/src/Marten/Internal/ProviderGraph.cs index e16f5fc2e0..d9217f9dda 100644 --- a/src/Marten/Internal/ProviderGraph.cs +++ b/src/Marten/Internal/ProviderGraph.cs @@ -69,11 +69,9 @@ internal DocumentProvider CreateDocumentProvider() where T : notnull if (documentType == typeof(IEvent)) { // Phase 4 (#4454): closed-shape event storage is the only path — - // no codegen, no AllowRuntimeCodeGeneration gate to honor here. - // EventGraph.AttachTypesSynchronously builds + // no codegen. EventGraph.AttachTypesSynchronously builds // ClosedShapeEventDocumentStorage directly. - _options.EventGraph.AttachTypesSynchronously( - rules: null!, assembly: null!, services: null, containingNamespace: string.Empty); + _options.EventGraph.AttachTypesSynchronously(); _storage = _storage.AddOrUpdate(documentType, _options.EventGraph.Provider!); diff --git a/src/Marten/Internal/SecondaryStoreProxyFactory.cs b/src/Marten/Internal/SecondaryStoreProxyFactory.cs index 754da58e77..4ae3409aaf 100644 --- a/src/Marten/Internal/SecondaryStoreProxyFactory.cs +++ b/src/Marten/Internal/SecondaryStoreProxyFactory.cs @@ -9,12 +9,10 @@ namespace Marten.Internal; /// /// Builds a thin runtime subclass class <T>Implementation : DocumentStore, T -/// per user-supplied secondary-store interface — what the Roslyn-emit path -/// in used to produce. Uses -/// instead of JasperFx.RuntimeCompiler: -/// T here is a marker interface (T : IDocumentStore) with no -/// extra abstract members, so the emitted type only needs a forwarding -/// constructor. +/// per user-supplied secondary-store interface via +/// . T here is a marker interface +/// (T : IDocumentStore) with no extra abstract members, so the emitted +/// type only needs a forwarding constructor. /// [RequiresDynamicCode("Generates a runtime subclass per secondary-store interface via System.Reflection.Emit.")] internal static class SecondaryStoreProxyFactory diff --git a/src/Marten/Internal/Sessions/QuerySession.Load.cs b/src/Marten/Internal/Sessions/QuerySession.Load.cs index e2e15236b0..090a30b82f 100644 --- a/src/Marten/Internal/Sessions/QuerySession.Load.cs +++ b/src/Marten/Internal/Sessions/QuerySession.Load.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using Marten.Exceptions; using Marten.Internal.Storage; diff --git a/src/Marten/Internal/Storage/IDocumentStorage.cs b/src/Marten/Internal/Storage/IDocumentStorage.cs index b2916e8028..c00112be01 100644 --- a/src/Marten/Internal/Storage/IDocumentStorage.cs +++ b/src/Marten/Internal/Storage/IDocumentStorage.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Model; using JasperFx.Events.Aggregation; using Marten.Internal.Operations; using Marten.Internal.Sessions; @@ -61,18 +59,6 @@ public interface IDocumentStorage: ISelectClause object RawIdentityValue(object id); } -[UnconditionalSuppressMessage("AOT", "IL2055", - Justification = "Class-level: Type.MakeGenericType with a runtime-determined type argument — AOT consumers must pre-register the closed shape they need (see the AOT publishing guide).")] -[UnconditionalSuppressMessage("AOT", "IL3050", - Justification = "Class-level: uses Type.MakeGenericType / MethodInfo.MakeGenericMethod / Activator.CreateInstance / FastExpressionCompiler — runtime code generation. AOT consumers pre-generate codegen artifacts (codegen write) and supply source-generator-backed serializer impls per the AOT publishing guide.")] -internal class CreateFromDocumentMapping: Variable -{ - public CreateFromDocumentMapping(DocumentMapping mapping, Type openType, GeneratedType type): base( - openType.MakeGenericType(mapping.DocumentType), $"new {type.TypeName}(mapping)") - { - } -} - public class DocumentProvider where T : notnull { public DocumentProvider(IBulkLoader bulkLoader, IDocumentStorage queryOnly, IDocumentStorage lightweight, diff --git a/src/Marten/Internal/Storage/IdentityMapDocumentStorage.cs b/src/Marten/Internal/Storage/IdentityMapDocumentStorage.cs index 0f4a042023..cd3fee4827 100644 --- a/src/Marten/Internal/Storage/IdentityMapDocumentStorage.cs +++ b/src/Marten/Internal/Storage/IdentityMapDocumentStorage.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using Marten.Exceptions; using Marten.Internal.CodeGeneration; diff --git a/src/Marten/MartenServiceCollectionExtensions.cs b/src/Marten/MartenServiceCollectionExtensions.cs index c3dc0e6611..fbbed2d382 100644 --- a/src/Marten/MartenServiceCollectionExtensions.cs +++ b/src/Marten/MartenServiceCollectionExtensions.cs @@ -5,7 +5,6 @@ using System.Threading; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.CommandLine; using JasperFx.CommandLine.Descriptions; using JasperFx.Core.Reflection; @@ -191,8 +190,6 @@ Func optionSource return options; }); - services.AddSingleton(s => s.GetRequiredService().EventGraph); - services.AddSingleton(s => { var options = s.GetRequiredService(); @@ -229,9 +226,6 @@ Func optionSource services.AddScoped(s => s.GetRequiredService().QuerySession()); services.AddScoped(s => s.GetRequiredService().OpenSession()); - services.AddSingleton(s => (ICodeFileCollection)s.GetRequiredService()); - services.AddSingleton(s => s.GetRequiredService()); - services.AddSingleton(s => s.GetRequiredService().As().Tenancy); diff --git a/src/Marten/Schema/Arguments/CurrentVersionArgument.cs b/src/Marten/Schema/Arguments/CurrentVersionArgument.cs index eda858d887..cfad9e9be4 100644 --- a/src/Marten/Schema/Arguments/CurrentVersionArgument.cs +++ b/src/Marten/Schema/Arguments/CurrentVersionArgument.cs @@ -1,8 +1,4 @@ -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; using NpgsqlTypes; -using Weasel.Postgresql; namespace Marten.Schema.Arguments; @@ -15,11 +11,4 @@ public CurrentVersionArgument() DbType = NpgsqlDbType.Uuid; Column = null; } - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code("setCurrentVersionParameter({0});", Use.Type()); - } } diff --git a/src/Marten/Schema/Arguments/DocJsonBodyArgument.cs b/src/Marten/Schema/Arguments/DocJsonBodyArgument.cs index a83ae2e022..500a185fca 100644 --- a/src/Marten/Schema/Arguments/DocJsonBodyArgument.cs +++ b/src/Marten/Schema/Arguments/DocJsonBodyArgument.cs @@ -1,12 +1,4 @@ -using System; -using System.Threading; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; -using Marten.Internal; -using Marten.Services; using NpgsqlTypes; -using Weasel.Postgresql; namespace Marten.Schema.Arguments; @@ -19,24 +11,4 @@ public DocJsonBodyArgument() DbType = NpgsqlDbType.Jsonb; Column = "data"; } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - // Direct UTF-8 serialization via SerializerExtensions.SerializeToUtf8 — internally - // a pooled buffer writer + sized byte[] snapshot. Skips the string materialization - // that serializer.ToJson(document) would emit on the bulk-loader hot path. - load.Frames.CodeAsync( - $"await writer.WriteAsync({typeof(SerializerExtensions).FullName}.{nameof(SerializerExtensions.SerializeToUtf8)}(serializer, document), {{0}}, {{1}});", - NpgsqlDbType.Jsonb, Use.Type()); - } - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - // Use Serializer.WriteToParameter for direct UTF-8 serialization into the - // parameter; skips the intermediate string round-trip. - method.Frames.Code($"var parameter{i} = {{0}}.{nameof(IGroupedParameterBuilder.AppendParameter)}({typeof(DBNull).FullName}.Value);", Use.Type()); - method.Frames.Code($"{{0}}.Serializer.{nameof(ISerializer.WriteToParameter)}(parameter{i}, _document);", Use.Type()); - } } diff --git a/src/Marten/Schema/Arguments/DocTypeArgument.cs b/src/Marten/Schema/Arguments/DocTypeArgument.cs index 20684d1d4a..4880c66748 100644 --- a/src/Marten/Schema/Arguments/DocTypeArgument.cs +++ b/src/Marten/Schema/Arguments/DocTypeArgument.cs @@ -1,14 +1,6 @@ using System.Reflection; -using System.Threading; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; using JasperFx.Core.Reflection; -using Marten.Events.CodeGeneration; -using Marten.Internal.CodeGeneration; -using Npgsql; using NpgsqlTypes; -using Weasel.Postgresql; namespace Marten.Schema.Arguments; @@ -24,35 +16,4 @@ public DocTypeArgument() DbType = NpgsqlDbType.Varchar; PostgresType = "varchar"; } - - public override void GenerateCodeToModifyDocument(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code($"var docType = _mapping.{nameof(DocumentMapping.AliasFor)}(document.GetType());"); - - if (mapping.Metadata.DocumentType.Member != null) - { - method.Frames.SetMemberValue(mapping.Metadata.DocumentType.Member, "docType", mapping.DocumentType, type); - } - } - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code($"var parameter{i} = {{0}}.{nameof(IGroupedParameterBuilder.AppendParameter)}(docType);", Use.Type()); - method.Frames.Code($"parameter{i}.{nameof(NpgsqlParameter.NpgsqlDbType)} = {{0}};", DbType); - } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - load.Frames.Code($"var docType = _mapping.{nameof(DocumentMapping.AliasFor)}(document.GetType());"); - - load.Frames.CodeAsync("await writer.WriteAsync(docType, {0}, {1});", DbType, Use.Type()); - if (mapping.Metadata.DocumentType.Member != null) - { - load.Frames.SetMemberValue(mapping.Metadata.DocumentType.Member, "docType", mapping.DocumentType, type); - } - } } diff --git a/src/Marten/Schema/Arguments/DotNetTypeArgument.cs b/src/Marten/Schema/Arguments/DotNetTypeArgument.cs index 9f212b94d2..d0acb3fe1b 100644 --- a/src/Marten/Schema/Arguments/DotNetTypeArgument.cs +++ b/src/Marten/Schema/Arguments/DotNetTypeArgument.cs @@ -1,12 +1,7 @@ using System; using System.Reflection; -using System.Threading; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; using JasperFx.Core.Reflection; using NpgsqlTypes; -using Weasel.Postgresql; namespace Marten.Schema.Arguments; @@ -24,22 +19,4 @@ public DotNetTypeArgument() DbType = NpgsqlDbType.Varchar; PostgresType = "varchar"; } - - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - var version = type.AllInjectedFields[0]; - - method.Frames.Code("// .Net Class Type"); - method.Frames.Code($"var parameter{{0}} = {{1}}.{nameof(IGroupedParameterBuilder.AppendParameter)}({{2}}.GetType().FullName);", i, Use.Type(), version); - method.Frames.Code("parameter{0}.NpgsqlDbType = {1};", i, DbType); - } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - load.Frames.Code("await writer.WriteAsync(document.GetType().FullName, {0}, {1});", DbType, - Use.Type()); - } } diff --git a/src/Marten/Schema/Arguments/ExpectedVersionArgument.cs b/src/Marten/Schema/Arguments/ExpectedVersionArgument.cs index 9b83735573..0edff9201f 100644 --- a/src/Marten/Schema/Arguments/ExpectedVersionArgument.cs +++ b/src/Marten/Schema/Arguments/ExpectedVersionArgument.cs @@ -1,8 +1,3 @@ -using System; -using System.Reflection; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Model; -using JasperFx.Core.Reflection; using NpgsqlTypes; namespace Marten.Schema.Arguments; @@ -16,36 +11,4 @@ public ExpectedVersionArgument(NpgsqlDbType dbType) DbType = dbType; PostgresType = dbType == NpgsqlDbType.Bigint ? "bigint" : "uuid"; } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - if (mapping.Metadata.Version.Member != null) - { - writeGuidExpectedVersion(load, mapping.Metadata.Version.Member); - } - else if (mapping.Metadata.Revision.Member != null) - { - writeLongExpectedVersion(load, mapping.Metadata.Revision.Member); - } - else - { - load.Frames.Code($"writer.Write({typeof(DBNull).FullNameInCode()}.Value, {0});", NpgsqlDbType.Uuid); - } - } - - private void writeGuidExpectedVersion(GeneratedMethod load, MemberInfo member) - { - var memberName = member.Name; - var dbTypeUsage = Constant.ForEnum(NpgsqlDbType.Uuid).Usage; - load.Frames.Code( - $"writer.Write(document.{memberName} == Guid.Empty ? (object){typeof(DBNull).FullNameInCode()}.Value : (object)document.{memberName}, {dbTypeUsage});"); - } - - private void writeLongExpectedVersion(GeneratedMethod load, MemberInfo member) - { - var memberName = member.Name; - var dbTypeUsage = Constant.ForEnum(NpgsqlDbType.Bigint).Usage; - load.Frames.Code( - $"writer.Write(document.{memberName} <= 0 ? (object){typeof(DBNull).FullNameInCode()}.Value : (object)(long)document.{memberName}, {dbTypeUsage});"); - } } diff --git a/src/Marten/Schema/Arguments/RevisionArgument.cs b/src/Marten/Schema/Arguments/RevisionArgument.cs index 88bbbe2c41..740ba253ee 100644 --- a/src/Marten/Schema/Arguments/RevisionArgument.cs +++ b/src/Marten/Schema/Arguments/RevisionArgument.cs @@ -1,7 +1,3 @@ -using System.Threading; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; using NpgsqlTypes; namespace Marten.Schema.Arguments; @@ -15,18 +11,4 @@ public RevisionArgument() DbType = NpgsqlDbType.Bigint; Column = SchemaConstants.VersionColumn; } - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code("setCurrentRevisionParameter(parameterBuilder);"); - } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - load.Frames.CodeAsync( - "await writer.WriteAsync((long)1, {0}, {1});", - NpgsqlDbType.Bigint, Use.Type()); - } } diff --git a/src/Marten/Schema/Arguments/TenantIdArgument.cs b/src/Marten/Schema/Arguments/TenantIdArgument.cs index 5fe7293ad2..dd260cf20e 100644 --- a/src/Marten/Schema/Arguments/TenantIdArgument.cs +++ b/src/Marten/Schema/Arguments/TenantIdArgument.cs @@ -1,11 +1,5 @@ -using System.Threading; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; -using Marten.Internal.CodeGeneration; using Marten.Storage.Metadata; using NpgsqlTypes; -using Weasel.Postgresql; namespace Marten.Schema.Arguments; @@ -21,34 +15,4 @@ public TenantIdArgument() DbType = NpgsqlDbType.Varchar; Column = TenantIdColumn.Name; } - - public override void GenerateCodeToModifyDocument(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - if (mapping.Metadata.TenantId.Member != null) - { - method.Frames.SetMemberValue(mapping.Metadata.TenantId.Member, TenantIdFieldName, mapping.DocumentType, - type); - } - } - - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code($"var parameter{{0}} = parameterBuilder.{nameof(IGroupedParameterBuilder.AppendParameter)}(_tenantId);", i); - method.Frames.Code("parameter{0}.NpgsqlDbType = {1};", i, DbType); - } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - load.Frames.CodeAsync("await writer.WriteAsync(tenant.TenantId, {0}, {1});", DbType, - Use.Type()); - if (mapping.Metadata.TenantId.Member != null) - { - load.Frames.SetMemberValue(mapping.Metadata.TenantId.Member, "tenant.TenantId", mapping.DocumentType, type); - } - } } diff --git a/src/Marten/Schema/Arguments/UpsertArgument.cs b/src/Marten/Schema/Arguments/UpsertArgument.cs index a7e210811b..67e9308ece 100644 --- a/src/Marten/Schema/Arguments/UpsertArgument.cs +++ b/src/Marten/Schema/Arguments/UpsertArgument.cs @@ -1,18 +1,11 @@ using System; using System.Linq; using System.Reflection; -using System.Threading; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; using JasperFx.Core; using JasperFx.Core.Reflection; -using Marten.Internal.CodeGeneration; -using Marten.Schema.Identity; using Marten.Util; using Npgsql; using NpgsqlTypes; -using Weasel.Core; using Weasel.Postgresql; using System.Diagnostics.CodeAnalysis; @@ -96,175 +89,4 @@ public string ArgumentDeclaration() { return $"{Arg} {PostgresType}"; } - - public virtual void GenerateCodeToModifyDocument(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - // Nothing - } - - public virtual void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, DocumentMapping mapping, StoreOptions options) - { - var memberPath = _members.Select(x => x.Name).Join("?."); - - if (DotNetType.IsEnum || (DotNetType.IsNullable() && DotNetType.GetGenericArguments()[0].IsEnum)) - { - writeEnumerationValues(method, i, parameters, options, memberPath); - } - else - { - var rawMemberType = _members.Last().GetRawMemberType(); - - var dbTypeString = rawMemberType!.IsArray - ? $"{Constant.ForEnum(NpgsqlDbType.Array).Usage} | {Constant.ForEnum(PostgresqlProvider.Instance.ToParameterType(rawMemberType.GetElementType()!)).Usage}" - : Constant.ForEnum(DbType).Usage; - - var accessorString = AccessorString(type); - var requiresCast = DeclaringType is { } dt && dt != type.BaseType; - - if (rawMemberType.IsClass || rawMemberType.IsNullable() || _members.Length > 1) - { - var hasValueGuard = requiresCast - ? $"(document is {DeclaringType!.FullNameInCode()} && {accessorString} != null)" - : $"{accessorString} != null"; - - method.Frames.Code($@" -BLOCK:if ({hasValueGuard}) -var parameter{i} = {{0}}.{nameof(IGroupedParameterBuilder.AppendParameter)}({accessorString}); -parameter{i}.{nameof(NpgsqlParameter.NpgsqlDbType)} = {dbTypeString}; -END -BLOCK:else -var parameter{i} = {{0}}.{nameof(IGroupedParameterBuilder.AppendParameter)}({typeof(DBNull).FullNameInCode()}.Value); -END -", Use.Type()); - } - else - { - var underlying = rawMemberType; - var valueProp = rawMemberType.GetProperty("Value"); - if (valueProp != null) - underlying = valueProp.PropertyType; - - var guarded = requiresCast - ? $"(document is {DeclaringType!.FullNameInCode()} ? {accessorString} : default({underlying.FullNameInCode()}))" - : accessorString; - - method.Frames.Code( - $"var parameter{i} = {{0}}.{nameof(IGroupedParameterBuilder.AppendParameter)}<{underlying.FullNameInCode()}>({guarded});", - Use.Type()); - } - } - } - - private void writeEnumerationValues(GeneratedMethod method, int i, Argument parameters, StoreOptions options, - string memberPath) - { - if (options.Advanced.DuplicatedFieldEnumStorage == EnumStorage.AsInteger) - { - if (DotNetType.IsNullable()) - { - method.Frames.Code( - $"var parameter{i} = document.{memberPath} == null ? {{0}}.{nameof(IGroupedParameterBuilder.AppendParameter)}({typeof(DBNull).FullNameInCode()}.Value) : {{0}}.{nameof(CommandBuilder.AppendParameter)}((int)document.{memberPath});", - Use.Type()); - - method.Frames.Code($"parameter{i}.{nameof(NpgsqlParameter.NpgsqlDbType)} = {{0}};", NpgsqlDbType.Integer); - } - else - { - method.Frames.Code( - $"var parameter{i} = {{0}}.{nameof(IGroupedParameterBuilder.AppendParameter)}((int)document.{memberPath});", Use.Type()); - method.Frames.Code($"parameter{i}.{nameof(NpgsqlParameter.NpgsqlDbType)} = {{0}};", - NpgsqlDbType.Integer); - } - } - else if (DotNetType.IsNullable()) - { - method.Frames.Code( - $"var parameter{i} = {{0}}.{nameof(IGroupedParameterBuilder.AppendParameter)}((document.{memberPath}).ToString());", Use.Type()); - method.Frames.Code($"parameter{i}.{nameof(NpgsqlParameter.NpgsqlDbType)} = {{0}};", - NpgsqlDbType.Varchar); - } - else - { - method.Frames.Code( - $"var parameter{i} = {{0}}.{nameof(IGroupedParameterBuilder.AppendParameter)}(document.{memberPath}.ToString());", Use.Type()); - method.Frames.Code($"parameter{i}.{nameof(NpgsqlParameter.NpgsqlDbType)} = {{0}};", - NpgsqlDbType.Varchar); - } - } - public virtual void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - var rawMemberType = _members.Last().GetRawMemberType()!; - - - var dbTypeString = rawMemberType.IsArray - ? $"{Constant.ForEnum(NpgsqlDbType.Array).Usage} | {Constant.ForEnum(PostgresqlProvider.Instance.ToParameterType(rawMemberType.GetElementType()!)).Usage}" - : Constant.ForEnum(DbType).Usage; - - - var memberPath = _members.Select(x => x.Name).Join("?."); - - if (mapping.IdStrategy is ValueTypeIdGeneration st) - { - st.WriteBulkWriterCodeAsync(load, mapping); - } - else if (DotNetType.IsEnum || (DotNetType.IsNullable() && DotNetType.GetGenericArguments()[0].IsEnum)) - { - var isDeep = _members.Length > 0; - var memberType = _members.Last().GetMemberType(); - var isNullable = memberType!.IsNullable(); - - var enumType = isNullable ? memberType!.GetGenericArguments()[0] : memberType; - var accessor = memberPath; - - if (DbType == NpgsqlDbType.Integer) - { - if (isNullable || isDeep) - { - accessor = - $"{nameof(BulkLoader.GetEnumIntValue)}<{enumType.FullNameInCode()}>(document.{memberPath})"; - } - - load.Frames.CodeAsync($"await writer.WriteAsync({accessor}, {{0}}, {{1}});", NpgsqlDbType.Integer, - Use.Type()); - } - else - { - if (isNullable || isDeep) - { - accessor = - $"GetEnumStringValue<{enumType!.FullNameInCode()}>(document.{memberPath})"; - } - else - { - accessor = $"document.{memberPath}.ToString()"; - } - - load.Frames.CodeAsync($"await writer.WriteAsync({accessor}, {{0}}, {{1}});", NpgsqlDbType.Varchar, - Use.Type()); - } - } - else if (DotNetType.IsNullable() && DotNetType.GetGenericArguments()[0].IsValueType) - { - var valueType = DotNetType.GetGenericArguments()[0]; - var accessor = $"GetNullable<{valueType}>(document.{memberPath})"; - var npgsqlType = DbType; - load.Frames.CodeAsync($"await writer.WriteAsync({accessor}, {{0}}, {{1}});", npgsqlType, - Use.Type()); - } - else - { - var accessor = AccessorString(type); - - load.Frames.CodeAsync($"await writer.WriteAsync({accessor}, {dbTypeString}, {{0}});", - Use.Type()); - } - } - - private string AccessorString(GeneratedType type) => - DeclaringType is { } dt2 && dt2 != type.BaseType - ? $"(({DeclaringType.FullNameInCode()})document).{ParameterValue}" - : $"document.{ParameterValue}"; } diff --git a/src/Marten/Schema/Arguments/VersionArgument.cs b/src/Marten/Schema/Arguments/VersionArgument.cs index 5076f08192..b269cbd511 100644 --- a/src/Marten/Schema/Arguments/VersionArgument.cs +++ b/src/Marten/Schema/Arguments/VersionArgument.cs @@ -1,13 +1,5 @@ using System; using System.Reflection; -using System.Threading; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; -using JasperFx.Core; -using JasperFx.Core.Reflection; -using Marten.Internal.CodeGeneration; -using Marten.Schema.Identity; using NpgsqlTypes; namespace Marten.Schema.Arguments; @@ -27,42 +19,4 @@ public VersionArgument() DbType = NpgsqlDbType.Uuid; PostgresType = "uuid"; } - - public override void GenerateCodeToModifyDocument(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - if (mapping.Metadata.Version.Member != null) - { - // "_version" would be a field in the StorageOperation base class - method.Frames.SetMemberValue(mapping.Metadata.Version.Member, "_version", mapping.DocumentType, type); - } - } - - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code("setVersionParameter(parameterBuilder);"); - } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - if (mapping.Metadata.Version.Member == null) - { - load.Frames.CodeAsync( - $"await writer.WriteAsync({typeof(CombGuidIdGeneration).FullNameInCode()}.NewGuid(), {{0}}, {{1}});", - NpgsqlDbType.Uuid, Use.Type()); - } - else - { - load.Frames.Code($@" -var version = {typeof(CombGuidIdGeneration).FullNameInCode()}.NewGuid(); -writer.Write(version, {{0}}); -", NpgsqlDbType.Uuid); - - load.Frames.SetMemberValue(mapping.Metadata.Version.Member, "version", mapping.DocumentType, type); - } - } } diff --git a/src/Marten/Schema/Identity/CombGuidIdGeneration.cs b/src/Marten/Schema/Identity/CombGuidIdGeneration.cs index fa4387486f..d4a4dabc73 100644 --- a/src/Marten/Schema/Identity/CombGuidIdGeneration.cs +++ b/src/Marten/Schema/Identity/CombGuidIdGeneration.cs @@ -1,12 +1,4 @@ #nullable enable -using System; -using System.Buffers.Binary; -using System.Collections.Generic; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.Core; -using JasperFx.Core.Reflection; - namespace Marten.Schema.Identity; /// @@ -15,13 +7,4 @@ namespace Marten.Schema.Identity; public class SequentialGuidIdGeneration: IIdGeneration { public bool IsNumeric { get; } = false; - - public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) - { - var document = new Use(mapping.DocumentType); - method.Frames.Code( - $"if ({{0}}.{mapping.IdMember.Name} == Guid.Empty) _setter({{0}}, {typeof(CombGuidIdGeneration).FullNameInCode()}.NewGuid());", - document); - method.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); - } } diff --git a/src/Marten/Schema/Identity/FSharpDiscriminatedUnionIdGeneration.cs b/src/Marten/Schema/Identity/FSharpDiscriminatedUnionIdGeneration.cs index 0fdc644be8..e5473d4091 100644 --- a/src/Marten/Schema/Identity/FSharpDiscriminatedUnionIdGeneration.cs +++ b/src/Marten/Schema/Identity/FSharpDiscriminatedUnionIdGeneration.cs @@ -6,8 +6,6 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; using JasperFx.Core; using JasperFx.Core.Reflection; using Marten.Internal; @@ -52,13 +50,6 @@ private FSharpDiscriminatedUnionIdGeneration(Type outerType, PropertyInfo valueP public bool IsNumeric => false; - public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) - { - var document = new Use(mapping.DocumentType); - - method.Frames.Code($"return {{0}}.{mapping.CodeGen.AccessId};", document); - } - public ISelectClause BuildSelectClause(string tableName) { return _selector.CloneToOtherTable(tableName); @@ -144,40 +135,6 @@ public string ParameterValue(DocumentMapping mapping) return $"{mapping.IdMember.Name}.{ValueProperty.Name}"; } - - - public void GenerateCodeForFetchingId(int index, GeneratedMethod sync, GeneratedMethod async, - DocumentMapping mapping) - { - if (Builder != null) - { - sync.Frames.Code( - $"var id = {OuterType.FullNameInCode()}.{Builder.Name}(reader.GetFieldValue<{SimpleType.FullNameInCode()}>({index}));"); - async.Frames.CodeAsync( - $"var id = {OuterType.FullNameInCode()}.{Builder.Name}(await reader.GetFieldValueAsync<{SimpleType.FullNameInCode()}>({index}, token));"); - } - else - { - sync.Frames.Code( - $"var id = new {OuterType.FullNameInCode()}(reader.GetFieldValue<{SimpleType.FullNameInCode()}>({index}));"); - async.Frames.CodeAsync( - $"var id = new {OuterType.FullNameInCode()}(await reader.GetFieldValueAsync<{SimpleType.FullNameInCode()}>({index}, token));"); - } - } - - public void WriteBulkWriterCode(GeneratedMethod load, DocumentMapping mapping) - { - var dbType = PostgresqlProvider.Instance.ToParameterType(SimpleType); - load.Frames.Code($"writer.Write(document.{mapping.IdMember.Name}.{ValueProperty.Name}, {{0}});", dbType); - } - - public void WriteBulkWriterCodeAsync(GeneratedMethod load, DocumentMapping mapping) - { - var dbType = PostgresqlProvider.Instance.ToParameterType(SimpleType); - load.Frames.Code( - $"await writer.WriteAsync(document.{mapping.IdMember.Name}.{ValueProperty.Name}, {{0}}, {{1}});", - dbType, Use.Type()); - } } [UnconditionalSuppressMessage("Trimming", "IL2026", diff --git a/src/Marten/Schema/Identity/GuidIdGeneration.cs b/src/Marten/Schema/Identity/GuidIdGeneration.cs index 21da3a812c..4d79a992a5 100644 --- a/src/Marten/Schema/Identity/GuidIdGeneration.cs +++ b/src/Marten/Schema/Identity/GuidIdGeneration.cs @@ -1,10 +1,4 @@ #nullable enable -using System; -using System.Collections.Generic; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.Core.Reflection; - namespace Marten.Schema.Identity; /// @@ -13,13 +7,4 @@ namespace Marten.Schema.Identity; public class GuidIdGeneration: IIdGeneration { public bool IsNumeric { get; } = false; - - public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) - { - var document = new Use(mapping.DocumentType); - method.Frames.Code( - $"if ({{0}}.{mapping.IdMember.Name} == Guid.Empty) _setter({{0}}, {typeof(Guid).FullNameInCode()}.NewGuid());", - document); - method.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); - } } diff --git a/src/Marten/Schema/Identity/IIdGeneration.cs b/src/Marten/Schema/Identity/IIdGeneration.cs index 768ea94e6c..332d1dcbf6 100644 --- a/src/Marten/Schema/Identity/IIdGeneration.cs +++ b/src/Marten/Schema/Identity/IIdGeneration.cs @@ -1,10 +1,4 @@ #nullable enable -using System; -using System.Collections.Generic; -using System.Reflection; -using JasperFx.CodeGeneration; -using JasperFx.Core.Reflection; - namespace Marten.Schema.Identity; /// @@ -16,12 +10,4 @@ public interface IIdGeneration /// Does this strategy require number sequences /// bool IsNumeric { get; } - - /// - /// This method must be implemented to build and set the identity on - /// a document - /// - /// - /// - void GenerateCode(GeneratedMethod method, DocumentMapping mapping); } diff --git a/src/Marten/Schema/Identity/NoOpIdGeneration.cs b/src/Marten/Schema/Identity/NoOpIdGeneration.cs index f3a5df1a4a..8ea417b34b 100644 --- a/src/Marten/Schema/Identity/NoOpIdGeneration.cs +++ b/src/Marten/Schema/Identity/NoOpIdGeneration.cs @@ -1,9 +1,4 @@ #nullable enable -using System; -using System.Collections.Generic; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; - namespace Marten.Schema.Identity; /// @@ -12,10 +7,4 @@ namespace Marten.Schema.Identity; public class NoOpIdGeneration: IIdGeneration { public bool IsNumeric => false; - - public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) - { - var document = new Use(mapping.DocumentType); - method.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); - } } diff --git a/src/Marten/Schema/Identity/Sequences/HiloIdGeneration.cs b/src/Marten/Schema/Identity/Sequences/HiloIdGeneration.cs index ce59ca572c..f5fff74a53 100644 --- a/src/Marten/Schema/Identity/Sequences/HiloIdGeneration.cs +++ b/src/Marten/Schema/Identity/Sequences/HiloIdGeneration.cs @@ -1,9 +1,5 @@ #nullable enable using System; -using System.Collections.Generic; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using Marten.Storage; namespace Marten.Schema.Identity.Sequences; @@ -22,25 +18,4 @@ public HiloIdGeneration(Type documentType, HiloSettings hiloSettings) public int MaxLo => _hiloSettings.MaxLo; public bool IsNumeric { get; } = true; - - public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) - { - var document = new Use(mapping.DocumentType); - - - if (mapping.IdType == typeof(int)) - { - method.Frames.Code( - $"if ({{0}}.{mapping.IdMember.Name} <= 0) _setter({{0}}, {{1}}.Sequences.SequenceFor({{2}}).NextInt());", - document, Use.Type(), mapping.DocumentType); - } - else - { - method.Frames.Code( - $"if ({{0}}.{mapping.IdMember.Name} <= 0) _setter({{0}}, {{1}}.Sequences.SequenceFor({{2}}).NextLong());", - document, Use.Type(), mapping.DocumentType); - } - - method.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); - } } diff --git a/src/Marten/Schema/Identity/Sequences/IdentityKeyGeneration.cs b/src/Marten/Schema/Identity/Sequences/IdentityKeyGeneration.cs index 57ba2f77eb..618b38d9cc 100644 --- a/src/Marten/Schema/Identity/Sequences/IdentityKeyGeneration.cs +++ b/src/Marten/Schema/Identity/Sequences/IdentityKeyGeneration.cs @@ -1,9 +1,5 @@ #nullable enable using System; -using System.Collections.Generic; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using Marten.Storage; namespace Marten.Schema.Identity.Sequences; @@ -22,16 +18,6 @@ public IdentityKeyGeneration(DocumentMapping mapping, HiloSettings hiloSettings) public bool IsNumeric { get; } = true; - public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) - { - var document = new Use(mapping.DocumentType); - - method.Frames.Code( - $"if (string.{nameof(string.IsNullOrEmpty)}({{0}}.{mapping.IdMember.Name})) _setter({{0}}, \"{_mapping.Alias}\" + \"/\" + {{1}}.Sequences.SequenceFor({{2}}).NextLong());", - document, Use.Type(), mapping.DocumentType); - method.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); - } - public Type[] DependentFeatures() { return new[] { typeof(SequenceFactory) }; diff --git a/src/Marten/Schema/Identity/StringIdGeneration.cs b/src/Marten/Schema/Identity/StringIdGeneration.cs index 247b6a269b..dbffa1f022 100644 --- a/src/Marten/Schema/Identity/StringIdGeneration.cs +++ b/src/Marten/Schema/Identity/StringIdGeneration.cs @@ -1,9 +1,4 @@ #nullable enable -using System; -using System.Collections.Generic; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; - namespace Marten.Schema.Identity; /// @@ -12,13 +7,4 @@ namespace Marten.Schema.Identity; public class StringIdGeneration: IIdGeneration { public bool IsNumeric { get; } = false; - - public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) - { - var document = new Use(mapping.DocumentType); - method.Frames.Code( - $"if (string.IsNullOrEmpty({{0}}.{mapping.IdMember.Name})) throw new InvalidOperationException(\"Id/id values cannot be null or empty\");", - document); - method.Frames.Code($"return {{0}}.{mapping.IdMember.Name};", document); - } } diff --git a/src/Marten/Schema/Identity/ValueTypeIdGeneration.cs b/src/Marten/Schema/Identity/ValueTypeIdGeneration.cs index 819e1e6b05..bde4ff53ad 100644 --- a/src/Marten/Schema/Identity/ValueTypeIdGeneration.cs +++ b/src/Marten/Schema/Identity/ValueTypeIdGeneration.cs @@ -4,14 +4,10 @@ using System.Linq.Expressions; using System.Numerics; using System.Reflection; -using System.Threading; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; using JasperFx.Core; using JasperFx.Core.Reflection; using Marten.Linq.Members; using Marten.Linq.SqlGeneration; -using Marten.Storage; using Weasel.Core; using Weasel.Postgresql; @@ -43,96 +39,6 @@ private ValueTypeIdGeneration(Type outerType, PropertyInfo valueProperty, Type s public bool IsNumeric => false; - public void GenerateCode(GeneratedMethod method, DocumentMapping mapping) - { - var document = new Use(mapping.DocumentType); - - if (SimpleType == typeof(Guid)) - { - generateGuidWrapper(method, mapping, document); - } - else if (SimpleType == typeof(int)) - { - generateIntWrapper(method, mapping, document); - } - else if (SimpleType == typeof(long)) - { - generateLongWrapper(method, mapping, document); - } - else if (SimpleType == typeof(string)) - { - generateStringWrapper(method, mapping, document); - } - else - { - throw new NotSupportedException(); - } - - method.Frames.Code($"return {{0}}.{mapping.CodeGen.AccessId};", document); - } - - private string innerValueAccessor(DocumentMapping mapping) - { - return mapping.IdMember.GetRawMemberType()!.IsNullable() ? $"{mapping.IdMember.Name}.Value" : mapping.IdMember.Name; - } - - private void generateStringWrapper(GeneratedMethod method, DocumentMapping mapping, Use document) - { - method.Frames.Code($"return {{0}}.{innerValueAccessor(mapping)};", document); - } - - private void generateLongWrapper(GeneratedMethod method, DocumentMapping mapping, Use document) - { - var isDefault = mapping.IdMember.GetRawMemberType()!.IsNullable() ? $"{mapping.IdMember.Name} == null" : $"{mapping.IdMember.Name}.Value == default"; - - var database = Use.Type(); - if (Ctor != null) - { - method.Frames.Code( - $"if ({{0}}.{isDefault}) _setter({{0}}, new {OuterType.FullNameInCode()}({{1}}.Sequences.SequenceFor({{2}}).NextLong()));", - document, database, mapping.DocumentType); - } - else - { - method.Frames.Code( - $"if ({{0}}.{isDefault}) _setter({{0}}, {OuterType.FullNameInCode()}.{Builder.Name}({{1}}.Sequences.SequenceFor({{2}}).NextLong()));", - document, database, mapping.DocumentType); - } - } - - private void generateIntWrapper(GeneratedMethod method, DocumentMapping mapping, Use document) - { - var isDefault = mapping.IdMember.GetRawMemberType()!.IsNullable() ? $"{mapping.IdMember.Name} == null" : $"{mapping.IdMember.Name}.Value == default"; - - var database = Use.Type(); - if (Ctor != null) - { - method.Frames.Code( - $"if ({{0}}.{isDefault}) _setter({{0}}, new {OuterType.FullNameInCode()}({{1}}.Sequences.SequenceFor({{2}}).NextInt()));", - document, database, mapping.DocumentType); - } - else - { - method.Frames.Code( - $"if ({{0}}.{isDefault}) _setter({{0}}, {OuterType.FullNameInCode()}.{Builder.Name}({{1}}.Sequences.SequenceFor({{2}}).NextInt()));", - document, database, mapping.DocumentType); - } - } - - private void generateGuidWrapper(GeneratedMethod method, DocumentMapping mapping, Use document) - { - var isDefault = mapping.IdMember.GetRawMemberType()!.IsNullable() ? $"{mapping.IdMember.Name} == null" : $"{mapping.IdMember.Name}.Value == default"; - - var newGuid = $"{typeof(CombGuidIdGeneration).FullNameInCode()}.NewGuid()"; - var create = Ctor == null - ? $"{OuterType.FullNameInCode()}.{Builder.Name}({newGuid})" - : $"new {OuterType.FullNameInCode()}({newGuid})"; - - method.Frames.Code( - $"if ({{0}}.{isDefault}) _setter({{0}}, {create});", - document); - } - public ISelectClause BuildSelectClause(string tableName) { return _selector.CloneToOtherTable(tableName); @@ -222,26 +128,6 @@ public string ParameterValue(DocumentMapping mapping) return $"{mapping.IdMember.Name}.{ValueProperty.Name}"; } - - public void GenerateCodeForFetchingId(int index, GeneratedMethod sync, GeneratedMethod async, - DocumentMapping mapping) - { - if (Builder != null) - { - sync.Frames.Code( - $"var id = {OuterType.FullNameInCode()}.{Builder.Name}(reader.GetFieldValue<{SimpleType.FullNameInCode()}>({index}));"); - async.Frames.CodeAsync( - $"var id = {OuterType.FullNameInCode()}.{Builder.Name}(await reader.GetFieldValueAsync<{SimpleType.FullNameInCode()}>({index}, token));"); - } - else - { - sync.Frames.Code( - $"var id = new {OuterType.FullNameInCode()}(reader.GetFieldValue<{SimpleType.FullNameInCode()}>({index}));"); - async.Frames.CodeAsync( - $"var id = new {OuterType.FullNameInCode()}(await reader.GetFieldValueAsync<{SimpleType.FullNameInCode()}>({index}, token));"); - } - } - public Func BuildInnerValueSource() { var target = Expression.Parameter(typeof(object), "target"); @@ -253,40 +139,6 @@ public Func BuildInnerValueSource() return FastExpressionCompiler.ExpressionCompiler.CompileFast(lambda); } - - public void WriteBulkWriterCode(GeneratedMethod load, DocumentMapping mapping) - { - var dbType = PostgresqlProvider.Instance.ToParameterType(SimpleType); - - if (mapping.IdMember.GetRawMemberType()!.IsNullable()) - { - load.Frames.Code($"writer.Write(document.{mapping.IdMember.Name}.Value.{ValueProperty.Name}, {{0}});", dbType); - } - else - { - load.Frames.Code($"writer.Write(document.{mapping.IdMember.Name}.{ValueProperty.Name}, {{0}});", dbType); - } - } - - public void WriteBulkWriterCodeAsync(GeneratedMethod load, DocumentMapping mapping) - { - var dbType = PostgresqlProvider.Instance.ToParameterType(SimpleType); - - if (mapping.IdMember.GetRawMemberType()!.IsNullable()) - { - load.Frames.Code( - $"await writer.WriteAsync(document.{mapping.IdMember.Name}.Value.{ValueProperty.Name}, {{0}}, {{1}});", - dbType, Use.Type()); - } - else - { - load.Frames.Code( - $"await writer.WriteAsync(document.{mapping.IdMember.Name}.{ValueProperty.Name}, {{0}}, {{1}});", - dbType, Use.Type()); - } - - - } } [UnconditionalSuppressMessage("Trimming", "IL2026", diff --git a/src/Marten/Storage/DataColumn.cs b/src/Marten/Storage/DataColumn.cs index d0edec6b1b..42609fb5b0 100644 --- a/src/Marten/Storage/DataColumn.cs +++ b/src/Marten/Storage/DataColumn.cs @@ -1,4 +1,3 @@ -using JasperFx.CodeGeneration; using Marten.Internal.CodeGeneration; using Marten.Schema; using Weasel.Postgresql.Tables; @@ -12,14 +11,6 @@ public DataColumn(): base("data", "JSONB") AllowNulls = false; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, int index, - DocumentMapping mapping) - { - sync.Frames.DeserializeDocument(mapping, index); - async.Frames.DeserializeDocumentAsync(mapping, index); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return true; diff --git a/src/Marten/Storage/ISelectableColumn.cs b/src/Marten/Storage/ISelectableColumn.cs index cd7e58a8e0..1e443385d1 100644 --- a/src/Marten/Storage/ISelectableColumn.cs +++ b/src/Marten/Storage/ISelectableColumn.cs @@ -1,4 +1,3 @@ -using JasperFx.CodeGeneration; using Marten.Internal.CodeGeneration; using Marten.Schema; @@ -8,9 +7,5 @@ internal interface ISelectableColumn { string Name { get; } - void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, int index, - DocumentMapping mapping); - bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle); } diff --git a/src/Marten/Storage/IdColumn.cs b/src/Marten/Storage/IdColumn.cs index fbd8130dd6..a5dd46cd22 100644 --- a/src/Marten/Storage/IdColumn.cs +++ b/src/Marten/Storage/IdColumn.cs @@ -1,9 +1,5 @@ -using JasperFx.CodeGeneration; -using JasperFx.Core.Reflection; using Marten.Internal.CodeGeneration; using Marten.Schema; -using Marten.Schema.Identity; -using Marten.Util; using Weasel.Postgresql; using Weasel.Postgresql.Tables; @@ -11,46 +7,11 @@ namespace Marten.Storage; internal class IdColumn: TableColumn, ISelectableColumn { - private const string IdentityMapCode = "if (_identityMap.TryGetValue(id, out var existing)) return existing;"; - public IdColumn(DocumentMapping mapping): base("id", PostgresqlProvider.Instance.GetDatabaseType(mapping.InnerIdType(), mapping.EnumStorage)) { } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, int index, - DocumentMapping mapping) - - { - if (storageStyle == StorageStyle.QueryOnly) - { - return; - } - - if (mapping.IdStrategy is ValueTypeIdGeneration st) - { - st.GenerateCodeForFetchingId(index, sync, async, mapping); - } - else if (mapping.IdStrategy is FSharpDiscriminatedUnionIdGeneration fst) - { - fst.GenerateCodeForFetchingId(index, sync, async, mapping); - } - else - { - sync.Frames.Code($"var id = reader.GetFieldValue<{mapping.IdType.FullNameInCode()}>({index});"); - async.Frames.CodeAsync( - $"var id = await reader.GetFieldValueAsync<{mapping.IdType.FullNameInCode()}>({index}, token);"); - } - - - if (storageStyle != StorageStyle.Lightweight) - { - sync.Frames.Code(IdentityMapCode); - async.Frames.Code(IdentityMapCode); - } - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return storageStyle != StorageStyle.QueryOnly; diff --git a/src/Marten/Storage/Metadata/CausationIdColumn.cs b/src/Marten/Storage/Metadata/CausationIdColumn.cs index 38a7fb060f..c293124eee 100644 --- a/src/Marten/Storage/Metadata/CausationIdColumn.cs +++ b/src/Marten/Storage/Metadata/CausationIdColumn.cs @@ -2,9 +2,6 @@ using System.Data.Common; using System.Threading; using System.Threading.Tasks; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; using JasperFx.Events; using Marten.Events; using Marten.Events.Schema; @@ -34,13 +31,6 @@ public CausationIdColumn(): base(ColumnName, x => x.CausationId) ShouldUpdatePartials = true; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, - int index, DocumentMapping mapping) - { - setMemberFromReader(generatedType, async, sync, index, mapping); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return mapping.Metadata.CausationId.EnabledWithMember(); @@ -86,33 +76,6 @@ public CausationIdArgument() DbType = NpgsqlDbType.Varchar; } - public override void GenerateCodeToModifyDocument(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - if (mapping.Metadata.CausationId.Member != null) - { - method.Frames.Code($"var causationId = {{0}}.{nameof(IMartenSession.CausationId)};", - Use.Type()); - method.Frames.SetMemberValue(mapping.Metadata.CausationId.Member, "causationId", mapping.DocumentType, - type); - } - } - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code($"setStringParameter({parameters.Usage}, {{0}}.{nameof(IMartenSession.CausationId)});", - Use.Type()); - } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - load.Frames.CodeAsync("await writer.WriteAsync(\"BULK_INSERT\", {0}, {1});", DbType, - Use.Type()); - } - public string ValueSql(EventGraph graph, AppendMode mode) { return "?"; diff --git a/src/Marten/Storage/Metadata/CorrelationIdColumn.cs b/src/Marten/Storage/Metadata/CorrelationIdColumn.cs index 91bc70fa14..75ef14a0da 100644 --- a/src/Marten/Storage/Metadata/CorrelationIdColumn.cs +++ b/src/Marten/Storage/Metadata/CorrelationIdColumn.cs @@ -2,9 +2,6 @@ using System.Data.Common; using System.Threading; using System.Threading.Tasks; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; using JasperFx.Events; using Marten.Events; using Marten.Events.Schema; @@ -34,13 +31,6 @@ public CorrelationIdColumn(): base(ColumnName, x => x.CorrelationId) ShouldUpdatePartials = true; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, - int index, DocumentMapping mapping) - { - setMemberFromReader(generatedType, async, sync, index, mapping); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return mapping.Metadata.CorrelationId.EnabledWithMember(); @@ -85,33 +75,4 @@ public CorrelationIdArgument() PostgresType = "varchar"; DbType = NpgsqlDbType.Varchar; } - - - public override void GenerateCodeToModifyDocument(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - if (mapping.Metadata.CorrelationId.Member != null) - { - method.Frames.Code($"var correlationId = {{0}}.{nameof(IMartenSession.CorrelationId)};", - Use.Type()); - method.Frames.SetMemberValue(mapping.Metadata.CorrelationId.Member, "correlationId", mapping.DocumentType, - type); - } - } - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code( - $"setStringParameter({parameters.Usage}, {{0}}.{nameof(IMartenSession.CorrelationId)});", - Use.Type()); - } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - load.Frames.CodeAsync("await writer.WriteAsync(\"BULK_INSERT\", {0}, {1});", DbType, - Use.Type()); - } } diff --git a/src/Marten/Storage/Metadata/CreatedAtColumn.cs b/src/Marten/Storage/Metadata/CreatedAtColumn.cs index c3c78a04e1..b3dbee3dc0 100644 --- a/src/Marten/Storage/Metadata/CreatedAtColumn.cs +++ b/src/Marten/Storage/Metadata/CreatedAtColumn.cs @@ -1,6 +1,4 @@ using System; -using JasperFx.CodeGeneration; -using JasperFx.Core.Reflection; using Marten.Internal.CodeGeneration; using Marten.Schema; @@ -15,26 +13,6 @@ public CreatedAtColumn(): base(SchemaConstants.CreatedAtColumn, x => x.CreatedAt Enabled = false; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, - int index, DocumentMapping mapping) - { - var variableName = "created"; - var memberType = typeof(DateTimeOffset); - - if (Member == null) - { - return; - } - - sync.Frames.Code($"var {variableName} = reader.GetFieldValue<{memberType.FullNameInCode()}>({index});"); - async.Frames.CodeAsync( - $"var {variableName} = await reader.GetFieldValueAsync<{memberType.FullNameInCode()}>({index}, token);"); - - sync.Frames.SetMemberValue(Member, variableName, mapping.DocumentType, generatedType); - async.Frames.SetMemberValue(Member, variableName, mapping.DocumentType, generatedType); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return Member != null; diff --git a/src/Marten/Storage/Metadata/DeletedAtColumn.cs b/src/Marten/Storage/Metadata/DeletedAtColumn.cs index 0a29b965dc..75d7d7a183 100644 --- a/src/Marten/Storage/Metadata/DeletedAtColumn.cs +++ b/src/Marten/Storage/Metadata/DeletedAtColumn.cs @@ -1,5 +1,4 @@ using System; -using JasperFx.CodeGeneration; using Marten.Internal.CodeGeneration; using Marten.Schema; @@ -12,13 +11,6 @@ public DeletedAtColumn(): base(SchemaConstants.DeletedAtColumn, x => x.DeletedAt AllowNulls = true; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, - int index, DocumentMapping mapping) - { - setMemberFromReader(generatedType, async, sync, index, mapping); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return Member != null; diff --git a/src/Marten/Storage/Metadata/DocumentTypeColumn.cs b/src/Marten/Storage/Metadata/DocumentTypeColumn.cs index 39a75e3897..b01fc9cdf5 100644 --- a/src/Marten/Storage/Metadata/DocumentTypeColumn.cs +++ b/src/Marten/Storage/Metadata/DocumentTypeColumn.cs @@ -1,5 +1,3 @@ -using JasperFx.CodeGeneration; -using JasperFx.Core.Reflection; using Marten.Internal.CodeGeneration; using Marten.Schema; @@ -12,26 +10,6 @@ public DocumentTypeColumn(DocumentMapping mapping): base(SchemaConstants.Documen DefaultExpression = $"'{mapping.AliasFor(mapping.DocumentType)}'"; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, int index, - DocumentMapping mapping) - { - var variableName = "docType"; - var memberType = typeof(string); - - if (Member == null) - { - return; - } - - sync.Frames.Code($"var {variableName} = reader.GetFieldValue<{memberType.FullNameInCode()}>({index});"); - async.Frames.CodeAsync( - $"var {variableName} = await reader.GetFieldValueAsync<{memberType.FullNameInCode()}>({index}, token);"); - - sync.Frames.SetMemberValue(Member, variableName, mapping.DocumentType, generatedType); - async.Frames.SetMemberValue(Member, variableName, mapping.DocumentType, generatedType); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return true; diff --git a/src/Marten/Storage/Metadata/HeadersColumn.cs b/src/Marten/Storage/Metadata/HeadersColumn.cs index edcbfa0d12..4812a6cc19 100644 --- a/src/Marten/Storage/Metadata/HeadersColumn.cs +++ b/src/Marten/Storage/Metadata/HeadersColumn.cs @@ -1,22 +1,15 @@ -using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Data.Common; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; -using JasperFx.Core.Reflection; using JasperFx.Events; using Marten.Events; using Marten.Events.Schema; using Marten.Internal; -using Marten.Internal.CodeGeneration; using Marten.Schema; using Marten.Schema.Arguments; using Marten.Services; using NpgsqlTypes; -using Weasel.Postgresql; namespace Marten.Storage.Metadata; @@ -100,29 +93,4 @@ public HeadersArgument() PostgresType = "jsonb"; DbType = NpgsqlDbType.Jsonb; } - - public override void GenerateCodeToModifyDocument(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - if (mapping.Metadata.Headers.Member != null) - { - method.Frames.Code($"var headers = {{0}}.{nameof(IMartenSession.Headers)};", - Use.Type()); - method.Frames.SetMemberValue(mapping.Metadata.Headers.Member, "headers", mapping.DocumentType, type); - } - } - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code($"setHeaderParameter({parameters.Usage}, {{0}});", Use.Type()); - } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - load.Frames.CodeAsync($"await writer.WriteAsync({typeof(DBNull).FullNameInCode()}.Value, {{0}}, {{1}});", - DbType, Use.Type()); - } } diff --git a/src/Marten/Storage/Metadata/LastModifiedByColumn.cs b/src/Marten/Storage/Metadata/LastModifiedByColumn.cs index 6cf950e056..093a1c1270 100644 --- a/src/Marten/Storage/Metadata/LastModifiedByColumn.cs +++ b/src/Marten/Storage/Metadata/LastModifiedByColumn.cs @@ -1,8 +1,3 @@ -using System.Threading; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; -using Marten.Internal; using Marten.Internal.CodeGeneration; using Marten.Internal.Sessions; using Marten.Schema; @@ -22,13 +17,6 @@ public LastModifiedByColumn(): base(ColumnName, x => x.LastModifiedBy) ShouldUpdatePartials = true; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, - int index, DocumentMapping mapping) - { - setMemberFromReader(generatedType, async, sync, index, mapping); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return mapping.Metadata.LastModifiedBy.EnabledWithMember(); @@ -56,32 +44,4 @@ public LastModifiedByArgument() PostgresType = "varchar"; DbType = NpgsqlDbType.Varchar; } - - public override void GenerateCodeToModifyDocument(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - if (mapping.Metadata.LastModifiedBy.Member != null) - { - method.Frames.Code($"var lastModifiedBy = {{0}}.{nameof(IMartenSession.CurrentUserName)};", - Use.Type()); - method.Frames.SetMemberValue(mapping.Metadata.LastModifiedBy.Member, "lastModifiedBy", mapping.DocumentType, - type); - } - } - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code( - $"setStringParameter({parameters.Usage}, {{0}}.{nameof(IMartenSession.CurrentUserName)});", - Use.Type()); - } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - load.Frames.CodeAsync("await writer.WriteAsync(\"BULK_INSERT\", {0}, {1});", DbType, - Use.Type()); - } } diff --git a/src/Marten/Storage/Metadata/LastModifiedColumn.cs b/src/Marten/Storage/Metadata/LastModifiedColumn.cs index f6abde6de1..22fc6bdcc3 100644 --- a/src/Marten/Storage/Metadata/LastModifiedColumn.cs +++ b/src/Marten/Storage/Metadata/LastModifiedColumn.cs @@ -1,6 +1,4 @@ using System; -using JasperFx.CodeGeneration; -using JasperFx.Core.Reflection; using Marten.Internal.CodeGeneration; using Marten.Internal.Sessions; using Marten.Schema; @@ -18,26 +16,6 @@ public LastModifiedColumn(): base(SchemaConstants.LastModifiedColumn, x => x.Las ShouldUpdatePartials = true; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, - int index, DocumentMapping mapping) - { - var variableName = "lastModified"; - var memberType = typeof(DateTimeOffset); - - if (Member == null) - { - return; - } - - sync.Frames.Code($"var {variableName} = reader.GetFieldValue<{memberType.FullNameInCode()}>({index});"); - async.Frames.CodeAsync( - $"var {variableName} = await reader.GetFieldValueAsync<{memberType.FullNameInCode()}>({index}, token);"); - - sync.Frames.SetMemberValue(Member, variableName, mapping.DocumentType, generatedType); - async.Frames.SetMemberValue(Member, variableName, mapping.DocumentType, generatedType); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return Member != null; diff --git a/src/Marten/Storage/Metadata/MetadataColumn.cs b/src/Marten/Storage/Metadata/MetadataColumn.cs index beb72b7ffe..0e9b3f05b9 100644 --- a/src/Marten/Storage/Metadata/MetadataColumn.cs +++ b/src/Marten/Storage/Metadata/MetadataColumn.cs @@ -5,10 +5,8 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core.Reflection; using Marten.Internal; -using Marten.Internal.CodeGeneration; using Marten.Internal.Sessions; using Marten.Linq.Parsing; using Marten.Schema; @@ -75,26 +73,6 @@ internal virtual UpsertArgument ToArgument() }; } - protected void setMemberFromReader(GeneratedType generatedType, GeneratedMethod async, GeneratedMethod sync, - int index, - DocumentMapping mapping) - { - if (Member == null) - { - return; - } - - sync.IfDbReaderValueIsNotNull(index, () => - { - sync.AssignMemberFromReader(generatedType, index, mapping.DocumentType, Member.Name); - }); - - async.IfDbReaderValueIsNotNullAsync(index, () => - { - async.AssignMemberFromReaderAsync(generatedType, index, mapping.DocumentType, Member.Name); - }); - } - public virtual void WriteMetadataInUpdateStatement(ICommandBuilder builder, DocumentSessionBase session) { throw new NotSupportedException(); diff --git a/src/Marten/Storage/Metadata/RevisionColumn.cs b/src/Marten/Storage/Metadata/RevisionColumn.cs index 017e27f886..1ad85b729a 100644 --- a/src/Marten/Storage/Metadata/RevisionColumn.cs +++ b/src/Marten/Storage/Metadata/RevisionColumn.cs @@ -1,4 +1,3 @@ -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten.Internal.CodeGeneration; using Marten.Internal.Sessions; @@ -24,23 +23,6 @@ internal override UpsertArgument ToArgument() return new RevisionArgument(); } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, int index, - DocumentMapping mapping) - { - var versionPosition = index; //mapping.IsHierarchy() ? 3 : 2; - - async.Frames.CodeAsync( - $"var version = await reader.GetFieldValueAsync({versionPosition}, token);"); - sync.Frames.Code($"var version = reader.GetFieldValue({versionPosition});"); - - if (Member != null) - { - sync.Frames.SetMemberValue(Member, "version", mapping.DocumentType, generatedType); - async.Frames.SetMemberValue(Member, "version", mapping.DocumentType, generatedType); - } - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { if (Member != null) diff --git a/src/Marten/Storage/Metadata/SoftDeletedColumn.cs b/src/Marten/Storage/Metadata/SoftDeletedColumn.cs index 3c87ddc6ea..54fcfe77e7 100644 --- a/src/Marten/Storage/Metadata/SoftDeletedColumn.cs +++ b/src/Marten/Storage/Metadata/SoftDeletedColumn.cs @@ -1,5 +1,3 @@ -using JasperFx.CodeGeneration; -using JasperFx.Core.Reflection; using Marten.Internal.CodeGeneration; using Marten.Linq.SoftDeletes; using Marten.Schema; @@ -13,28 +11,6 @@ public SoftDeletedColumn(): base(SchemaConstants.DeletedColumn, x => x.Deleted) DefaultExpression = "FALSE"; } - - - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, - int index, DocumentMapping mapping) - { - var variableName = "isDeleted"; - var memberType = typeof(bool); - - if (Member == null) - { - return; - } - - sync.Frames.Code($"var {variableName} = reader.GetFieldValue<{memberType.FullNameInCode()}>({index});"); - async.Frames.CodeAsync( - $"var {variableName} = await reader.GetFieldValueAsync<{memberType.FullNameInCode()}>({index}, token);"); - - sync.Frames.SetMemberValue(Member, variableName, mapping.DocumentType, generatedType); - async.Frames.SetMemberValue(Member, variableName, mapping.DocumentType, generatedType); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return Member != null; diff --git a/src/Marten/Storage/Metadata/TenantIdColumn.cs b/src/Marten/Storage/Metadata/TenantIdColumn.cs index 7bb7df162a..9adb7fce71 100644 --- a/src/Marten/Storage/Metadata/TenantIdColumn.cs +++ b/src/Marten/Storage/Metadata/TenantIdColumn.cs @@ -3,8 +3,6 @@ using System.Threading; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; -using JasperFx.Core.Reflection; using JasperFx.Events; using Marten.Events; using Marten.Events.Schema; @@ -28,26 +26,6 @@ public TenantIdColumn(): base(Name, x => x.TenantId) DefaultExpression = $"'{StorageConstants.DefaultTenantId}'"; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, - int index, DocumentMapping mapping) - { - var variableName = "tenantId"; - var memberType = typeof(string); - - if (Member == null) - { - return; - } - - sync.Frames.Code($"var {variableName} = reader.GetFieldValue<{memberType.FullNameInCode()}>({index});"); - async.Frames.CodeAsync( - $"var {variableName} = await reader.GetFieldValueAsync<{memberType.FullNameInCode()}>({index}, token);"); - - sync.Frames.SetMemberValue(Member, variableName, mapping.DocumentType, generatedType); - async.Frames.SetMemberValue(Member, variableName, mapping.DocumentType, generatedType); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return Member != null; diff --git a/src/Marten/Storage/Metadata/UserNameColumn.cs b/src/Marten/Storage/Metadata/UserNameColumn.cs index 5a899f511f..d0ef37d00a 100644 --- a/src/Marten/Storage/Metadata/UserNameColumn.cs +++ b/src/Marten/Storage/Metadata/UserNameColumn.cs @@ -2,13 +2,9 @@ using System.Data.Common; using System.Threading; using System.Threading.Tasks; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; -using JasperFx.CodeGeneration.Model; using JasperFx.Events; using Marten.Events; using Marten.Events.Schema; -using Marten.Internal; using Marten.Internal.CodeGeneration; using Marten.Internal.Sessions; using Marten.Schema; @@ -34,13 +30,6 @@ public UserNameColumn(): base(ColumnName, x => x.LastModifiedBy) ShouldUpdatePartials = true; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, - int index, DocumentMapping mapping) - { - setMemberFromReader(generatedType, async, sync, index, mapping); - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { return mapping.Metadata.LastModifiedBy.EnabledWithMember(); @@ -86,33 +75,6 @@ public UserNameArgument() DbType = NpgsqlDbType.Varchar; } - public override void GenerateCodeToModifyDocument(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - if (mapping.Metadata.LastModifiedBy.Member != null) - { - method.Frames.Code($"var userName = {{0}}.{nameof(IMartenSession.CurrentUserName)};", - Use.Type()); - method.Frames.SetMemberValue(mapping.Metadata.LastModifiedBy.Member, "userName", mapping.DocumentType, - type); - } - } - - public override void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, - Argument parameters, - DocumentMapping mapping, StoreOptions options) - { - method.Frames.Code($"setStringParameter({parameters.Usage}, {{0}}.{nameof(IMartenSession.CurrentUserName)});", - Use.Type()); - } - - public override void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping) - { - load.Frames.CodeAsync("await writer.WriteAsync(\"BULK_INSERT\", {0}, {1});", DbType, - Use.Type()); - } - public string ValueSql(EventGraph graph, AppendMode mode) { return "?"; diff --git a/src/Marten/Storage/Metadata/VersionColumn.cs b/src/Marten/Storage/Metadata/VersionColumn.cs index 89e48d40f0..7e3f7dccf6 100644 --- a/src/Marten/Storage/Metadata/VersionColumn.cs +++ b/src/Marten/Storage/Metadata/VersionColumn.cs @@ -1,6 +1,4 @@ using System; -using JasperFx.CodeGeneration; -using JasperFx.Core; using Marten.Internal.CodeGeneration; using Marten.Internal.Sessions; using Marten.Schema; @@ -17,32 +15,6 @@ public VersionColumn(): base(SchemaConstants.VersionColumn, x => x.CurrentVersio ShouldUpdatePartials = true; } - public void GenerateCode(StorageStyle storageStyle, GeneratedType generatedType, GeneratedMethod async, - GeneratedMethod sync, int index, - DocumentMapping mapping) - { - var versionPosition = index; //mapping.IsHierarchy() ? 3 : 2; - - - async.Frames.CodeAsync( - $"var version = await reader.GetFieldValueAsync({versionPosition}, token);"); - sync.Frames.Code($"var version = reader.GetFieldValue({versionPosition});"); - - if (storageStyle != StorageStyle.QueryOnly) - { - // Store it - sync.Frames.Code("_versions[id] = version;"); - async.Frames.Code("_versions[id] = version;"); - } - - - if (Member != null) - { - sync.Frames.SetMemberValue(Member, "version", mapping.DocumentType, generatedType); - async.Frames.SetMemberValue(Member, "version", mapping.DocumentType, generatedType); - } - } - public bool ShouldSelect(DocumentMapping mapping, StorageStyle storageStyle) { if (Member != null) diff --git a/src/Marten/Storage/StorageFeatures.cs b/src/Marten/Storage/StorageFeatures.cs index 00276c94ae..b5ba116e3e 100644 --- a/src/Marten/Storage/StorageFeatures.cs +++ b/src/Marten/Storage/StorageFeatures.cs @@ -6,7 +6,6 @@ using System.Reflection; using System.Threading; using ImTools; -using JasperFx.CodeGeneration; using JasperFx.Core; using JasperFx.Core.Reflection; using JasperFx.Descriptors; diff --git a/src/Marten/StoreOptions.GeneratesCode.cs b/src/Marten/StoreOptions.GeneratesCode.cs deleted file mode 100644 index e07971203c..0000000000 --- a/src/Marten/StoreOptions.GeneratesCode.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using JasperFx; -using JasperFx.CodeGeneration; -using JasperFx.Core; -using JasperFx.Descriptors; -using Marten.Internal.CodeGeneration; -using Marten.Schema; -using Microsoft.Extensions.Hosting; - -namespace Marten; - -public partial class StoreOptions: ICodeFileCollection -{ - internal const string PreferJasperFxMessage = - "Prefer using the IServiceCollection.CritterStackDefaults() API to override code generation and AutoCreate configuration across all JasperFx/Critter Stack tools. This API will be removed in Marten 9"; - - /// - /// The main application assembly. By default this is the entry assembly for the application, - /// but you may need to change this in testing scenarios - /// - [Obsolete(PreferJasperFxMessage)] - public Assembly ApplicationAssembly { get; set; } - - private bool? _sourceCodeWritingEnabled; - - [Obsolete(PreferJasperFxMessage)] - public bool SourceCodeWritingEnabled - { - get - { - return _sourceCodeWritingEnabled ?? true; - } - set - { - _sourceCodeWritingEnabled = value; - } - } - - // This would only be set for "additional" document stores - public string StoreName { get; set; } = "Main"; - - /// - /// Root folder where generated code should be placed. By default, this is the IHostEnvironment.ContentRootPath - /// - [Obsolete(PreferJasperFxMessage)] - [IgnoreDescription] - public string GeneratedCodeOutputPath { get; set; } - - public IReadOnlyList BuildFiles() - { - // #4404: the document-storage path no longer emits Roslyn code; - // the closed-shape hierarchy is built reflectively at runtime. - // BuildFiles() exists for the event-storage codegen (pre-flag) - // and other ICodeFileCollection participants — document storage - // contributes nothing here anymore. - Storage.BuildAllMappings(); - return System.Array.Empty(); - } - - [IgnoreDescription] - GenerationRules ICodeFileCollection.Rules => CreateGenerationRules(); - - string ICodeFileCollection.ChildNamespace { get; } = "DocumentStorage"; - - // 9.0: cache the base GenerationRules so we don't redo Path.Combine, - // Assembly.GetEntryAssembly, and the two ReferenceAssembly walks on - // every CreateGenerationRules() call (#4307). Callers that need to - // ReferenceTypes(...) for a specific document type get a Clone() so - // the mutation stays scoped to their compile and doesn't accumulate - // on the cached base. - private GenerationRules? _cachedBaseRules; - private readonly System.Threading.Lock _cachedRulesLock = new(); - - internal GenerationRules CreateGenerationRules() - { - return GetCachedBaseRules().Clone(); - } - - private GenerationRules GetCachedBaseRules() - { - if (_cachedBaseRules is { } existing) - { - return existing; - } - - lock (_cachedRulesLock) - { - if (_cachedBaseRules is { } existing2) - { - return existing2; - } - - var rules = new GenerationRules(SchemaConstants.MartenGeneratedNamespace) - { - TypeLoadMode = GeneratedCodeMode, - GeneratedCodeOutputPath = GeneratedCodeOutputPath ?? AppContext.BaseDirectory - .AppendPath("Internal", "Generated"), - ApplicationAssembly = ApplicationAssembly ?? Assembly.GetEntryAssembly(), - SourceCodeWritingEnabled = SourceCodeWritingEnabled - }; - - if (StoreName.IsNotEmpty() && StoreName != "Marten" && StoreName != "Main") - { - rules.GeneratedNamespace += "." + StoreName; - rules.GeneratedCodeOutputPath = Path.Combine(rules.GeneratedCodeOutputPath, StoreName); - } - - rules.ReferenceAssembly(GetType().Assembly); - rules.ReferenceAssembly(Assembly.GetEntryAssembly()!); - - _cachedBaseRules = rules; - return rules; - } - } - - internal void ReadJasperFxOptions(JasperFxOptions? options) - { - if (options == null) return; - - if (!_tenantIdStyle.HasValue) - { - _tenantIdStyle = options.TenantIdStyle; - } - - ApplicationAssembly ??= options.ApplicationAssembly; - GeneratedCodeOutputPath ??= options.GeneratedCodeOutputPath; - _generatedCodeMode ??= options.ActiveProfile.GeneratedCodeMode; - _autoCreate ??= options.ActiveProfile.ResourceAutoCreate; - _sourceCodeWritingEnabled ??= options.ActiveProfile.SourceCodeWritingEnabled; - } -} diff --git a/src/Marten/StoreOptions.Registration.cs b/src/Marten/StoreOptions.Registration.cs index 0d9c189363..158e6c49d4 100644 --- a/src/Marten/StoreOptions.Registration.cs +++ b/src/Marten/StoreOptions.Registration.cs @@ -98,7 +98,7 @@ public class MartenAssemblyScanner private readonly List> _eventMatchers = new(); /// - /// Which assemblies in addition to the StoreOptions.ApplicationAssembly should + /// Which assemblies in addition to the entry assembly should /// be scanned for potential Marten registrations? /// /// diff --git a/src/Marten/StoreOptions.SourceGeneration.cs b/src/Marten/StoreOptions.SourceGeneration.cs index b1f68ff1e4..78c0b60bde 100644 --- a/src/Marten/StoreOptions.SourceGeneration.cs +++ b/src/Marten/StoreOptions.SourceGeneration.cs @@ -15,18 +15,18 @@ public partial class StoreOptions { /// /// Attempt to use a source-generated type manifest from the given assembly - /// (or the ApplicationAssembly if not specified) to register document types, + /// (or the entry assembly if not specified) to register document types, /// projection types, and event types at startup without runtime assembly scanning. /// This is an opt-in feature that requires the Marten.SourceGeneration analyzer /// package to be referenced in the consuming project. /// /// - /// The assembly to search for the generated manifest. Defaults to ApplicationAssembly. + /// The assembly to search for the generated manifest. Defaults to the entry assembly. /// /// True if a source-generated manifest was found and applied; false otherwise. public bool TryUseSourceGeneratedDiscovery(Assembly? assembly = null) { - assembly ??= ApplicationAssembly; + assembly ??= ApplicationAssembly ?? Assembly.GetEntryAssembly(); if (assembly == null) return false; var manifestType = assembly.GetType("Marten.Generated.DiscoveredMartenTypes"); diff --git a/src/Marten/StoreOptions.cs b/src/Marten/StoreOptions.cs index 71f020ba31..3427a317b3 100644 --- a/src/Marten/StoreOptions.cs +++ b/src/Marten/StoreOptions.cs @@ -9,7 +9,6 @@ using System.Text.RegularExpressions; using ImTools; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Core; using JasperFx.Core.Reflection; using JasperFx.Descriptors; @@ -298,37 +297,30 @@ internal bool ShouldAssertDatabaseMatchesConfigurationOnStartup [ChildDescription] public ProjectionOptions Projections => _projections; + // This would only be set for "additional" document stores + public string StoreName { get; set; } = "Main"; + /// - /// Direct Marten to either generate code at runtime (Dynamic), or attempt to load types from the entry assembly + /// The main application assembly. Defaults to ; + /// override only when the entry-assembly heuristic can't find the consumer's + /// project (e.g. test runners, plug-in hosts). Used by + /// assembly scanning and by + /// . /// - [Obsolete(PreferJasperFxMessage)] - public TypeLoadMode GeneratedCodeMode + public Assembly? ApplicationAssembly { get; set; } + + internal void ReadJasperFxOptions(JasperFxOptions? options) { - get => _generatedCodeMode ?? TypeLoadMode.Dynamic; - set => _generatedCodeMode = value; - } + if (options == null) return; - /// - /// When false, Marten refuses to invoke JasperFx.RuntimeCompiler - /// and will throw if a generated type is missing from the entry assembly. - /// Defaults to true for back-compatibility. - /// - /// - /// - /// Set this to false in combination with - /// = - /// when publishing under PublishAot=true (NativeAOT). The flag - /// lets Marten verify at startup that every required code-generated - /// type was pre-built and shipped in the application assembly, instead - /// of falling back to Roslyn at runtime — which Native AOT can't do. - /// - /// - /// AOT-friendly Tier 1 (#4309). Marten 9 still emits trim warnings on - /// the dynamic codepaths; turning this off lets you opt out of those - /// paths completely so the linker can drop them. - /// - /// - public bool AllowRuntimeCodeGeneration { get; set; } = true; + if (!_tenantIdStyle.HasValue) + { + _tenantIdStyle = options.TenantIdStyle; + } + + ApplicationAssembly ??= options.ApplicationAssembly; + _autoCreate ??= options.ActiveProfile.ResourceAutoCreate; + } /// /// Access to adding custom schema features to this Marten-enabled Postgresql database @@ -499,7 +491,6 @@ public ITenancy Tenancy private bool _shouldApplyChangesOnStartup = false; private bool _shouldAssertDatabaseMatchesConfigurationOnStartup = false; private readonly ProjectionOptions _projections; - private TypeLoadMode? _generatedCodeMode; private readonly StorageFeatures _storage; private Action? _createDatabases; private readonly IProviderGraph _providers; @@ -787,50 +778,6 @@ internal void Validate() } } - /// - /// Meant for testing scenarios to "help" .Net understand where the IHostEnvironment for the - /// Host. You may have to specify the relative path to the entry project folder from the AppContext.BaseDirectory - /// - /// - /// - /// - /// - public void SetApplicationProject(Assembly assembly, - string? hintPath = null) - { - ApplicationAssembly = assembly ?? throw new ArgumentNullException(nameof(assembly)); - - // TODO -- pull this into LamarCodeGeneration itself. - var path = AppContext.BaseDirectory.ToFullPath(); - if (hintPath.IsNotEmpty()) - { - path = path.AppendPath(hintPath).ToFullPath(); - } - else - { - try - { - path = path.TrimEnd(Path.DirectorySeparatorChar); - while (!path.EndsWith("bin")) - { - path = path.ParentDirectory(); - } - - // Go up once to get to the test project directory, then up again to the "src" level, - // then "down" to the application directory - path = path.ParentDirectory().ParentDirectory().AppendPath(assembly.GetName().Name); - } - catch (Exception e) - { - Console.WriteLine("Unable to determine the "); - Console.WriteLine(e); - path = AppContext.BaseDirectory.ToFullPath(); - } - } - - GeneratedCodeOutputPath = path.AppendPath("Internal", "Generated"); - } - /// /// Opt into a multi-tenancy per database strategy where all databases /// are on the same Postgresql server instance diff --git a/src/ModularConfigTests/ConfigurationFixture.cs b/src/ModularConfigTests/ConfigurationFixture.cs index 3c9d2ebb82..826b7fb709 100644 --- a/src/ModularConfigTests/ConfigurationFixture.cs +++ b/src/ModularConfigTests/ConfigurationFixture.cs @@ -1,5 +1,4 @@ using System; -using JasperFx.CodeGeneration; using Marten; using Marten.Testing.Harness; using Microsoft.Extensions.DependencyInjection; @@ -34,6 +33,5 @@ public static void AddBaselineMarten(IServiceCollection services, string schemaN { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = schemaName; - opts.GeneratedCodeMode = TypeLoadMode.Auto; }); } diff --git a/src/MultiDatabaseCommandLineRunner/Program.cs b/src/MultiDatabaseCommandLineRunner/Program.cs index fc1d845134..003a58db43 100644 --- a/src/MultiDatabaseCommandLineRunner/Program.cs +++ b/src/MultiDatabaseCommandLineRunner/Program.cs @@ -2,7 +2,6 @@ using DaemonTests.EventProjections; using DaemonTests.TestingSupport; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Events.Daemon; using JasperFx.Events.Projections; using Marten; @@ -30,7 +29,6 @@ public static IHostBuilder CreateHostBuilder(string[] args) { opts.Connection(ConnectionSource.ConnectionString); opts.RegisterDocumentType(); - opts.GeneratedCodeMode = TypeLoadMode.Auto; }); services.AddMarten(opts => @@ -43,10 +41,6 @@ public static IHostBuilder CreateHostBuilder(string[] args) t => t.WithTenants("chiefs", "chargers", "broncos", "raiders") ); - // This is important, setting this option tells Marten to - // *try* to use pre-generated code at runtime - opts.GeneratedCodeMode = TypeLoadMode.Auto; - // You have to register all persisted document types ahead of time // RegisterDocumentType() is the equivalent of saying Schema.For() // just to let Marten know that document type exists diff --git a/src/StressTests/using_multiple_document_stores_in_same_host.cs b/src/StressTests/using_multiple_document_stores_in_same_host.cs index e5cf092403..b22f61a438 100644 --- a/src/StressTests/using_multiple_document_stores_in_same_host.cs +++ b/src/StressTests/using_multiple_document_stores_in_same_host.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Core; using JasperFx.Core.Reflection; using JasperFx.Events.Daemon; @@ -40,7 +39,6 @@ public using_multiple_document_stores_in_same_host() { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "first_store"; - opts.GeneratedCodeMode = TypeLoadMode.Auto; }); // Just to prove that this doesn't blow up, see GH-2892 @@ -158,38 +156,6 @@ public record SomeSingleTenantedDocument(Guid Id); public class additional_document_store_registration_and_optimized_artifact_workflow { - [Fact] - public void all_the_defaults() - { - using var container = Container.For(services => - { - services.AddMarten(opts => - { - opts.Connection(ConnectionSource.ConnectionString); - }); - - services.AddMartenStore(opts => - { - opts.ApplyChangesLockId += 17; - opts.Connection(ConnectionSource.ConnectionString); - opts.DatabaseSchemaName = "first_store"; - }); - }); - - - var store = container.GetInstance().As(); - - var rules = store.Options.CreateGenerationRules(); - - store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.CreateOrUpdate); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Dynamic); - - rules.GeneratedNamespace.ShouldBe("Marten.Generated.IFirstStore"); - rules.GeneratedCodeOutputPath.ShouldEndWith(Path.Combine("Internal", "Generated", "IFirstStore")); - rules.SourceCodeWritingEnabled.ShouldBeTrue(); - - } - [Fact] public async Task can_resolve_all_stores() { @@ -210,163 +176,6 @@ public async Task can_resolve_all_stores() stores.OfType().Count().ShouldBe(1); } - [Fact] - public void using_optimized_mode_in_development() - { - using var host = new HostBuilder() - .ConfigureServices(services => - { - services.AddMarten(opts => - { - opts.Connection(ConnectionSource.ConnectionString); - opts.SetApplicationProject(GetType().Assembly); - }); - - // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation - services.CritterStackDefaults(x => - { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; - x.Production.ResourceAutoCreate = AutoCreate.None; - }); - - services.AddMartenStore(opts => - { - opts.Connection(ConnectionSource.ConnectionString); - opts.DatabaseSchemaName = "first_store"; - opts.SetApplicationProject(GetType().Assembly); - }); - - - }) - .UseEnvironment("Development") - .Start(); - - - var store = host.Services.GetRequiredService().As(); - - var rules = store.Options.CreateGenerationRules(); - - store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.CreateOrUpdate); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Auto); - - rules.GeneratedNamespace.ShouldBe("Marten.Generated.IFirstStore"); - rules.GeneratedCodeOutputPath.ShouldEndWith(Path.Combine("Internal", "Generated", "IFirstStore")); - rules.SourceCodeWritingEnabled.ShouldBeTrue(); - } - - [Fact] - public void using_optimized_mode_in_production() - { - using var host = new HostBuilder() - .ConfigureServices(services => - { - services.AddMarten(ConnectionSource.ConnectionString); - - services.AddMartenStore(opts => - { - opts.Connection(ConnectionSource.ConnectionString); - opts.DatabaseSchemaName = "first_store"; - opts.SetApplicationProject(GetType().Assembly); - }); - - // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation - services.CritterStackDefaults(x => - { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; - x.Production.ResourceAutoCreate = AutoCreate.None; - }); - }) - .UseEnvironment("Production") - .Start(); - - - var store = host.Services.GetRequiredService().As(); - - var rules = store.Options.CreateGenerationRules(); - - store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.None); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Auto); - - rules.GeneratedNamespace.ShouldBe("Marten.Generated.IFirstStore"); - rules.GeneratedCodeOutputPath.ShouldEndWith(Path.Combine("Internal", "Generated", "IFirstStore")); - rules.SourceCodeWritingEnabled.ShouldBeFalse(); - } - - [Fact] - public void picks_up_application_assembly_and_content_directory_from_IHostEnvironment() - { - var environment = new MartenHostEnvironment(); - - using var host = Host.CreateDefaultBuilder(Array.Empty()) - .ConfigureServices(services => - { - services.AddMarten(ConnectionSource.ConnectionString); - services.AddMartenStore(opts => - { - opts.Connection(ConnectionSource.ConnectionString); - }); - - services.AddSingleton(environment); - }) - .Build(); - - var store = host.Services.GetRequiredService().As(); - store.Options.ApplicationAssembly.ShouldBe(GetType().Assembly); - store.Options.GeneratedCodeOutputPath.ShouldBe(environment.ContentRootPath.ToFullPath().AppendPath("Internal", "Generated")); - - var rules = store.Options.CreateGenerationRules(); - rules.ApplicationAssembly.ShouldBe(store.Options.ApplicationAssembly); - rules.GeneratedCodeOutputPath.ShouldBe(store.Options.GeneratedCodeOutputPath.AppendPath("IFirstStore")); - } - - [Fact] - public void using_optimized_mode_in_production_override_type_load_mode() - { - using var host = new HostBuilder() - .ConfigureServices(services => - { - // Have to help .net here understand what the environment *should* be - services.AddSingleton(new MartenHostEnvironment - { - EnvironmentName = "Production" - }); - - - services.AddMarten(ConnectionSource.ConnectionString); - - services.AddMartenStore(opts => - { - opts.Connection(ConnectionSource.ConnectionString); - opts.DatabaseSchemaName = "first_store"; - opts.SetApplicationProject(typeof(IFirstStore).Assembly); - }); - - // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation - services.CritterStackDefaults(x => - { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; - x.Production.ResourceAutoCreate = AutoCreate.None; - }); - - }) - .Start(); - - - var store = host.Services.GetRequiredService().As(); - - var rules = store.Options.CreateGenerationRules(); - - store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.None); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Static); - - rules.GeneratedNamespace.ShouldBe("Marten.Generated.IFirstStore"); - rules.GeneratedCodeOutputPath.ShouldEndWith(Path.Combine("Internal", "Generated", "IFirstStore")); - rules.SourceCodeWritingEnabled.ShouldBeFalse(); - } - [Fact] public void use_secondary_options_configure_against_additional_store() { @@ -388,10 +197,9 @@ public void use_secondary_options_configure_against_additional_store() }); // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation + // automatic database migrations services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); }) @@ -419,10 +227,9 @@ public void bootstrap_async_daemon_for_secondary_store() }).AddAsyncDaemon(DaemonMode.HotCold); // In a "Production" environment, we're turning off the - // automatic database migrations and dynamic code generation + // automatic database migrations services.CritterStackDefaults(x => { - x.Production.GeneratedCodeMode = TypeLoadMode.Static; x.Production.ResourceAutoCreate = AutoCreate.None; }); @@ -490,19 +297,12 @@ public async Task jasperfx_options_usage_with_ancillary_stores() services.AddJasperFx(opts => { opts.Development.ResourceAutoCreate = AutoCreate.None; - opts.GeneratedCodeOutputPath = "/"; - opts.Development.GeneratedCodeMode = TypeLoadMode.Auto; - - // Default is true - opts.Development.SourceCodeWritingEnabled = false; }); }) .UseEnvironment("Development").StartAsync(); var store = (DocumentStore)host.DocumentStore(); store.Options.AutoCreateSchemaObjects.ShouldBe(AutoCreate.None); - store.Options.SourceCodeWritingEnabled.ShouldBeFalse(); - store.Options.GeneratedCodeMode.ShouldBe(TypeLoadMode.Auto); } } diff --git a/src/ValueTypeTests/StrongTypedId/check_exists_with_strong_typed_ids.cs b/src/ValueTypeTests/StrongTypedId/check_exists_with_strong_typed_ids.cs index 19a708cabf..4dbb5431e1 100644 --- a/src/ValueTypeTests/StrongTypedId/check_exists_with_strong_typed_ids.cs +++ b/src/ValueTypeTests/StrongTypedId/check_exists_with_strong_typed_ids.cs @@ -1,6 +1,5 @@ using System; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten; using Marten.Testing.Harness; @@ -19,11 +18,6 @@ public check_exists_with_strong_typed_ids() { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "strong_typed_exists"; - - opts.ApplicationAssembly = GetType().Assembly; - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory().AppendPath("Internal", "Generated"); }); theSession = theStore.LightweightSession(); diff --git a/src/ValueTypeTests/StrongTypedId/duplicated_value_type_field_operations.cs b/src/ValueTypeTests/StrongTypedId/duplicated_value_type_field_operations.cs index af9edd583c..14fb908593 100644 --- a/src/ValueTypeTests/StrongTypedId/duplicated_value_type_field_operations.cs +++ b/src/ValueTypeTests/StrongTypedId/duplicated_value_type_field_operations.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten; using Marten.Testing.Harness; @@ -22,11 +21,6 @@ public duplicated_value_type_field_operations() opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "duplicated_value_type_field1"; - opts.ApplicationAssembly = GetType().Assembly; - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory().AppendPath("Internal", "Generated"); - opts.RegisterValueType(); opts.Schema.For().Duplicate(x => x.DuplicateValueType); }); diff --git a/src/ValueTypeTests/StrongTypedId/fsharp_discriminated_union_document_operations.cs b/src/ValueTypeTests/StrongTypedId/fsharp_discriminated_union_document_operations.cs index 37b6ec17b0..3d248c2335 100644 --- a/src/ValueTypeTests/StrongTypedId/fsharp_discriminated_union_document_operations.cs +++ b/src/ValueTypeTests/StrongTypedId/fsharp_discriminated_union_document_operations.cs @@ -4,7 +4,6 @@ using System.Text.Json.Serialization; using System.Threading.Tasks; using JasperFx; -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten; using Marten.Exceptions; @@ -31,12 +30,6 @@ public fsharp_discriminated_union_document_operations() options.NameDataLength = 100; options.DatabaseSchemaName = schemaName; - options.ApplicationAssembly = GetType().Assembly; - options.GeneratedCodeMode = TypeLoadMode.Auto; - options.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory() - .AppendPath("Internal", "Generated"); - //For docs on these options see: https://github.com/Tarmil/FSharp.SystemTextJson/blob/master/docs/Customizing.md var jsonFSharpOptions = JsonFSharpOptions diff --git a/src/ValueTypeTests/StrongTypedId/guid_based_document_operations.cs b/src/ValueTypeTests/StrongTypedId/guid_based_document_operations.cs index d5c39674de..01cf392f1e 100644 --- a/src/ValueTypeTests/StrongTypedId/guid_based_document_operations.cs +++ b/src/ValueTypeTests/StrongTypedId/guid_based_document_operations.cs @@ -1,8 +1,6 @@ using System; using System.Linq; using System.Threading.Tasks; -using JasperFx.CodeGeneration; -using JasperFx.CodeGeneration.Frames; using JasperFx.Core; using Marten; using Marten.Exceptions; @@ -23,11 +21,6 @@ public guid_id_document_operations() { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "strong_typed1"; - - opts.ApplicationAssembly = GetType().Assembly; - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory().AppendPath("Internal", "Generated"); }); theSession = theStore.LightweightSession(); @@ -310,11 +303,6 @@ public guid_id_document_operations_with_non_nullable_identifier() { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "strong_typed21"; - - opts.ApplicationAssembly = GetType().Assembly; - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory().AppendPath("Internal", "Generated"); }); theSession = theStore.LightweightSession(); diff --git a/src/ValueTypeTests/StrongTypedId/string_id_document_operations.cs b/src/ValueTypeTests/StrongTypedId/string_id_document_operations.cs index ca5fa955ae..6af98b4a5f 100644 --- a/src/ValueTypeTests/StrongTypedId/string_id_document_operations.cs +++ b/src/ValueTypeTests/StrongTypedId/string_id_document_operations.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten; using Marten.Exceptions; @@ -22,11 +21,6 @@ public string_id_document_operations() { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "strong_typed4"; - - opts.ApplicationAssembly = GetType().Assembly; - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory().AppendPath("Internal", "Generated"); }); theSession = theStore.LightweightSession(); @@ -269,11 +263,6 @@ public string_id_document_operations_with_non_nullable_id() { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "strong_typed23"; - - opts.ApplicationAssembly = GetType().Assembly; - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory().AppendPath("Internal", "Generated"); }); theSession = theStore.LightweightSession(); diff --git a/src/ValueTypeTests/TestingTypes.cs b/src/ValueTypeTests/TestingTypes.cs index 72a484cdf4..439f76e3d8 100644 --- a/src/ValueTypeTests/TestingTypes.cs +++ b/src/ValueTypeTests/TestingTypes.cs @@ -1,6 +1,5 @@ using System; using System.Runtime.CompilerServices; -using JasperFx.CodeGeneration.Frames; using Vogen; namespace ValueTypeTests; diff --git a/src/ValueTypeTests/VogenIds/duplicated_value_type_field_operations.cs b/src/ValueTypeTests/VogenIds/duplicated_value_type_field_operations.cs index 41ebf3e127..96e02a7270 100644 --- a/src/ValueTypeTests/VogenIds/duplicated_value_type_field_operations.cs +++ b/src/ValueTypeTests/VogenIds/duplicated_value_type_field_operations.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten; using Marten.Testing.Harness; @@ -22,11 +21,6 @@ public duplicated_value_type_field_operations() opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "duplicated_value_type_field2"; - opts.ApplicationAssembly = GetType().Assembly; - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory().AppendPath("Internal", "Generated"); - opts.RegisterValueType(); opts.Schema.For().Duplicate(x => x.DuplicateValueType); }); diff --git a/src/ValueTypeTests/VogenIds/guid_based_document_operations.cs b/src/ValueTypeTests/VogenIds/guid_based_document_operations.cs index a2e731d992..2279bb84e8 100644 --- a/src/ValueTypeTests/VogenIds/guid_based_document_operations.cs +++ b/src/ValueTypeTests/VogenIds/guid_based_document_operations.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten; using Marten.Exceptions; @@ -21,11 +20,6 @@ public guid_id_document_operations() { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "strong_typed5"; - - opts.ApplicationAssembly = GetType().Assembly; - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory().AppendPath("Internal", "Generated"); }); theSession = theStore.LightweightSession(); diff --git a/src/ValueTypeTests/VogenIds/string_id_document_operations.cs b/src/ValueTypeTests/VogenIds/string_id_document_operations.cs index 929206e557..20f96657ec 100644 --- a/src/ValueTypeTests/VogenIds/string_id_document_operations.cs +++ b/src/ValueTypeTests/VogenIds/string_id_document_operations.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten; using Marten.Exceptions; @@ -21,11 +20,6 @@ public string_id_document_operations() { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "strong_typed8"; - - opts.ApplicationAssembly = GetType().Assembly; - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory().AppendPath("Internal", "Generated"); }); theSession = theStore.LightweightSession(); diff --git a/src/ValueTypeTests/include_usage.cs b/src/ValueTypeTests/include_usage.cs index f20336266e..35436cdc8a 100644 --- a/src/ValueTypeTests/include_usage.cs +++ b/src/ValueTypeTests/include_usage.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using JasperFx.CodeGeneration; using JasperFx.Core; using Marten; using Marten.Testing.Harness; @@ -22,11 +21,6 @@ public include_usage() { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "strong_typed24"; - - opts.ApplicationAssembly = GetType().Assembly; - opts.GeneratedCodeMode = TypeLoadMode.Auto; - opts.GeneratedCodeOutputPath = - AppContext.BaseDirectory.ParentDirectory().ParentDirectory().ParentDirectory().AppendPath("Internal", "Generated"); }); theSession = theStore.LightweightSession();