diff --git a/docs/guides/modeling/conventions.md b/docs/guides/modeling/conventions.md index e8f6694..bf1a248 100644 --- a/docs/guides/modeling/conventions.md +++ b/docs/guides/modeling/conventions.md @@ -15,6 +15,7 @@ for the behaviors that are policy, not mapping. | Element names (Cosmos DB) | camelCase (System.Text.Json web defaults) | | Columns vs navigations (relational) | scalars (and scalar collections, for stores with array columns) map to columns; entity references and entity collections are navigations | | Foreign keys (relational `Include`) | reference `Order` → `OrderId` on this entity; collection of `Item` → `{Entity}Id` on the element (`Reference(…)`/`Collection(…)` override) | +| A stored null, on read | `null` in the member, or its type's default when the member cannot hold null, on every engine and every read (by key, listings, raw SQL), whatever the member's initializer: `int? Quota { get; set; } = 10` reads a NULL row as `null`, never 10. An initializer is what a new entity starts with, not what a read fills in | ## `DataConventions` — the write-policy object diff --git a/src/eQuantic.Core.Data.Cassandra/CassandraMapper.cs b/src/eQuantic.Core.Data.Cassandra/CassandraMapper.cs index d4fd57d..18b43bd 100644 --- a/src/eQuantic.Core.Data.Cassandra/CassandraMapper.cs +++ b/src/eQuantic.Core.Data.Cassandra/CassandraMapper.cs @@ -223,12 +223,18 @@ public static TEntity Materialize(CassandraEntityConfiguration configur // lower-cased name; the driver's by-name lookup is case-sensitive, so read with that name (the // property, matched case-insensitively, still carries the original casing). var name = column.Name.ToLowerInvariant(); - if (property is null || !property.CanWrite || row.IsNull(name)) + if (property is null || !property.CanWrite) { continue; } - property.SetValue(entity, Value(row, column, property.PropertyType, name)); + // A null is written too: skipped, a member the entity initializes would read its initializer, not what the + // row holds. A member that cannot hold null reads its type's default. + property.SetValue(entity, row.IsNull(name) + ? property.PropertyType.IsValueType && Nullable.GetUnderlyingType(property.PropertyType) is null + ? Activator.CreateInstance(property.PropertyType) + : null + : Value(row, column, property.PropertyType, name)); } return entity; diff --git a/src/eQuantic.Core.Data.Relational/RelationalMaterializer.cs b/src/eQuantic.Core.Data.Relational/RelationalMaterializer.cs index 701d188..abc417d 100644 --- a/src/eQuantic.Core.Data.Relational/RelationalMaterializer.cs +++ b/src/eQuantic.Core.Data.Relational/RelationalMaterializer.cs @@ -27,13 +27,12 @@ public static object Materialize(Type entityType, DbDataReader reader, IReadOnly var entity = accessor?.Create() ?? Activator.CreateInstance(entityType)!; for (var ordinal = 0; ordinal < selected.Count; ordinal++) { - if (reader.IsDBNull(ordinal)) - { - continue; - } - + // A NULL is written too: skipped, a member the entity initializes would read its initializer, not what + // the row holds. var column = selected[ordinal]; - var value = Cell(column, reader.GetValue(ordinal), column.Property.PropertyType); + var value = reader.IsDBNull(ordinal) + ? NullFor(column.Property.PropertyType) + : Cell(column, reader.GetValue(ordinal), column.Property.PropertyType); if (accessor is not null) { accessor.Set(entity, column.Property.Name, value); @@ -56,15 +55,19 @@ public static TEntity MaterializeByName(DbDataReader reader, Relational var entity = Activator.CreateInstance()!; for (var ordinal = 0; ordinal < reader.FieldCount; ordinal++) { - if (reader.IsDBNull(ordinal)) + var name = reader.GetName(ordinal); + var column = configuration.Columns.FirstOrDefault(candidate => + string.Equals(candidate.Name, name, StringComparison.OrdinalIgnoreCase)); + if (column is null) { continue; } - var name = reader.GetName(ordinal); - var column = configuration.Columns.FirstOrDefault(candidate => - string.Equals(candidate.Name, name, StringComparison.OrdinalIgnoreCase)); - if (column is not null) + if (reader.IsDBNull(ordinal)) + { + column.Property.SetValue(entity, NullFor(column.Property.PropertyType)); + } + else { Assign(entity, column, reader.GetValue(ordinal)); } @@ -73,6 +76,13 @@ public static TEntity MaterializeByName(DbDataReader reader, Relational return entity; } + /// + /// What a NULL cell reads as in a member of : null, or the type's default + /// where it cannot hold one, as a projection reads it. Never the value the member was initialized with. + /// + internal static object? NullFor(Type memberType) => + memberType.IsValueType && Nullable.GetUnderlyingType(memberType) is null ? Activator.CreateInstance(memberType) : null; + /// Converts a reader value into a target CLR type (nullable unwrap, enum and numeric coercions). internal static object? ChangeValue(object? value, Type target) { diff --git a/src/eQuantic.Core.Data.Relational/RelationalRowBinder.cs b/src/eQuantic.Core.Data.Relational/RelationalRowBinder.cs index d280d25..df11634 100644 --- a/src/eQuantic.Core.Data.Relational/RelationalRowBinder.cs +++ b/src/eQuantic.Core.Data.Relational/RelationalRowBinder.cs @@ -78,12 +78,10 @@ public TResult Bind(DbDataReader reader) foreach (var (ordinal, property) in _bindings) { - if (reader.IsDBNull(ordinal)) - { - continue; - } - - var value = RelationalMaterializer.ChangeValue(reader.GetValue(ordinal), property.PropertyType); + // A NULL is written too, so a member the result type initializes reads what the row holds. + var value = reader.IsDBNull(ordinal) + ? RelationalMaterializer.NullFor(property.PropertyType) + : RelationalMaterializer.ChangeValue(reader.GetValue(ordinal), property.PropertyType); if (_accessor is not null) { _accessor.Set(result!, property.Name, value); diff --git a/tests/eQuantic.Core.Data.Cassandra.Tests/CassandraWriteOutcomeTests.cs b/tests/eQuantic.Core.Data.Cassandra.Tests/CassandraWriteOutcomeTests.cs index 73b1f9d..74e6fbf 100644 --- a/tests/eQuantic.Core.Data.Cassandra.Tests/CassandraWriteOutcomeTests.cs +++ b/tests/eQuantic.Core.Data.Cassandra.Tests/CassandraWriteOutcomeTests.cs @@ -84,6 +84,27 @@ public sealed class Page : IEntity public void SetKey(Guid key) => Id = key; } +/// +/// A row whose nullable members start with a value, as a generated model carries a column's default: a stored null +/// must read as null, never as the value the member starts with. +/// +public sealed class Preset : IEntity +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + public string? Note { get; set; } = "initial"; + + public int? Quota { get; set; } = 10; + + public bool? Enabled { get; set; } = true; + + public DateTime? Since { get; set; } = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + public Guid GetKey() => Id; + + public void SetKey(Guid key) => Id = key; +} + /// A row whose number and stamp the store assigns. public sealed class Voucher : IEntity { @@ -117,6 +138,7 @@ private static void Model(CassandraModelBuilder builder) => builder .Entity(entity => entity.Table("queued_jobs").PartitionKey(x => x.Id)) .Entity(entity => entity.Table("item_types").PartitionKey(x => x.Id)) .Entity(entity => entity.Table("pages").PartitionKey(x => x.Id)) + .Entity(entity => entity.Table("presets").PartitionKey(x => x.Id)) .Entity(entity => entity .Table("vouchers") .PartitionKey(x => x.Id) @@ -135,6 +157,7 @@ await _db.Resolve().ApplyAsync(new MigrationBuilder() .For(table => table.EnsureCollection()) .For(table => table.EnsureCollection()) .For(table => table.EnsureCollection()) + .For(table => table.EnsureCollection()) .For(table => table.EnsureCollection()) .For(table => table.EnsureCollection()) .Operations); @@ -546,4 +569,28 @@ public async Task A_member_scoped_modify_leaves_the_other_members() Assert.That(stored.Locked, Is.True); Assert.That(stored.Body, Is.EqualTo("text")); } + + [Test] + public async Task A_stored_null_reads_as_null_in_a_member_that_starts_with_a_value() + { + var preset = new Preset { Note = null, Quota = null, Enabled = null, Since = null }; + var kept = new Preset(); + using (var seed = NewScope()) + { + await Repo(seed).AddAsync(preset); + await Repo(seed).AddAsync(kept); + await Commit(seed); + } + + using var check = NewScope(); + var stored = (await Repo(check).GetAsync(preset.Id))!; + Assert.That(new object?[] { stored.Note, stored.Quota, stored.Enabled, stored.Since }, Is.All.Null); + + var listed = (await Repo(check).GetAllAsync()).Single(row => row.Id == preset.Id); + Assert.That(new object?[] { listed.Note, listed.Quota, listed.Enabled, listed.Since }, Is.All.Null); + + var other = (await Repo(check).GetAsync(kept.Id))!; + Assert.That((other.Note, other.Quota, other.Enabled, other.Since), + Is.EqualTo(("initial", (int?)10, (bool?)true, (DateTime?)new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)))); + } } diff --git a/tests/eQuantic.Core.Data.CosmosDb.Tests/CosmosTestServer.cs b/tests/eQuantic.Core.Data.CosmosDb.Tests/CosmosTestServer.cs index 63ae0bd..41f2c9f 100644 --- a/tests/eQuantic.Core.Data.CosmosDb.Tests/CosmosTestServer.cs +++ b/tests/eQuantic.Core.Data.CosmosDb.Tests/CosmosTestServer.cs @@ -157,6 +157,7 @@ private static void RegisterEntities(CosmosModelBuilder model) => ReadShapesMode .Entity(entity => entity.Container(ContainerName).PartitionKey(x => x.Category)) .Entity(entity => entity.Container(ContainerName).PartitionKey(x => x.Category)) .Entity(entity => entity.Container(ContainerName).PartitionKey(x => x.Category)) + .Entity(entity => entity.Container(ContainerName).PartitionKey(x => x.Category)) .Entity(entity => entity.Container(ContainerName).PartitionKey(x => x.Category).ConcurrencyToken(x => x.ETag)) .Entity(entity => entity.Container("rel_items").PartitionKey(x => x.Category)) .Entity(entity => entity.Container("rel_mentions").PartitionKey(x => x.Category)) diff --git a/tests/eQuantic.Core.Data.CosmosDb.Tests/CosmosWriteOutcomeTests.cs b/tests/eQuantic.Core.Data.CosmosDb.Tests/CosmosWriteOutcomeTests.cs index 31e7b0f..71c057c 100644 --- a/tests/eQuantic.Core.Data.CosmosDb.Tests/CosmosWriteOutcomeTests.cs +++ b/tests/eQuantic.Core.Data.CosmosDb.Tests/CosmosWriteOutcomeTests.cs @@ -96,6 +96,29 @@ public sealed class Page : IEntity public void SetKey(string key) => Id = key; } +/// +/// A document whose nullable members start with a value, as a generated model carries a column's default: a stored +/// null must read as null, never as the value the member starts with. +/// +public sealed class Preset : IEntity +{ + public string Id { get; set; } = Guid.NewGuid().ToString("N"); + + public string Category { get; set; } = ""; + + public string? Note { get; set; } = "initial"; + + public int? Quota { get; set; } = 10; + + public bool? Enabled { get; set; } = true; + + public DateTime? Since { get; set; } = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + public string GetKey() => Id; + + public void SetKey(string key) => Id = key; +} + /// /// A record with more members than Cosmos DB patches in one operation: an update of all twelve, with the status, goes /// as several patches of the item in one transactional batch. Its _etag is its concurrency token. @@ -531,6 +554,30 @@ public async Task A_member_scoped_modify_leaves_the_other_members() Assert.That(stored.Locked, Is.True); Assert.That(stored.Body, Is.EqualTo("text")); } + + [Test] + public async Task A_stored_null_reads_as_null_in_a_member_that_starts_with_a_value() + { + var preset = new Preset { Category = Partition, Note = null, Quota = null, Enabled = null, Since = null }; + var kept = new Preset { Category = Partition }; + using (var seed = NewScope()) + { + await RepoOf(seed).AddAsync(preset); + await RepoOf(seed).AddAsync(kept); + await Commit(seed); + } + + using var check = NewScope(); + var stored = (await RepoOf(check).GetAsync(preset.Id))!; + Assert.That(new object?[] { stored.Note, stored.Quota, stored.Enabled, stored.Since }, Is.All.Null); + + var listed = (await RepoOf(check).GetFilteredAsync(row => row.Id == preset.Id)).Single(); + Assert.That(new object?[] { listed.Note, listed.Quota, listed.Enabled, listed.Since }, Is.All.Null); + + var other = (await RepoOf(check).GetAsync(kept.Id))!; + Assert.That((other.Note, other.Quota, other.Enabled, other.Since), + Is.EqualTo(("initial", (int?)10, (bool?)true, (DateTime?)new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)))); + } // ---------------------------------------------------------------- more paths than one patch takes private static readonly System.Linq.Expressions.Expression> TwelveMembers = x => new diff --git a/tests/eQuantic.Core.Data.MongoDb.Tests/MongoWriteOutcomeTests.cs b/tests/eQuantic.Core.Data.MongoDb.Tests/MongoWriteOutcomeTests.cs index 5d06d6d..dca3f48 100644 --- a/tests/eQuantic.Core.Data.MongoDb.Tests/MongoWriteOutcomeTests.cs +++ b/tests/eQuantic.Core.Data.MongoDb.Tests/MongoWriteOutcomeTests.cs @@ -105,6 +105,26 @@ public sealed class Page : IEntity public void SetKey(string key) => Id = key; } +/// +/// A document whose nullable members start with a value, as a generated model carries a column's default: a stored +/// null must read as null, never as the value the member starts with. +/// +public sealed class Preset : IEntity +{ + public string Id { get; set; } = Guid.NewGuid().ToString("N"); + public string? Note { get; set; } = "initial"; + + public int? Quota { get; set; } = 10; + + public bool? Enabled { get; set; } = true; + + public DateTime? Since { get; set; } = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + public string GetKey() => Id; + + public void SetKey(string key) => Id = key; +} + /// An account whose e-mail is unique under the index ix_users_email. public sealed class UserAccount : IEntity { @@ -682,4 +702,28 @@ public async Task A_member_scoped_modify_leaves_the_other_members() Assert.That(stored.Locked, Is.True); Assert.That(stored.Body, Is.EqualTo("text")); } + + [Test] + public async Task A_stored_null_reads_as_null_in_a_member_that_starts_with_a_value() + { + var preset = new Preset { Note = null, Quota = null, Enabled = null, Since = null }; + var kept = new Preset(); + using (var seed = NewScope()) + { + await Repo(seed).AddAsync(preset); + await Repo(seed).AddAsync(kept); + await Commit(seed); + } + + using var check = NewScope(); + var stored = (await Repo(check).GetAsync(preset.Id))!; + Assert.That(new object?[] { stored.Note, stored.Quota, stored.Enabled, stored.Since }, Is.All.Null); + + var listed = (await Repo(check).GetAllAsync()).Single(row => row.Id == preset.Id); + Assert.That(new object?[] { listed.Note, listed.Quota, listed.Enabled, listed.Since }, Is.All.Null); + + var other = (await Repo(check).GetAsync(kept.Id))!; + Assert.That((other.Note, other.Quota, other.Enabled, other.Since), + Is.EqualTo(("initial", (int?)10, (bool?)true, (DateTime?)new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)))); + } } diff --git a/tests/eQuantic.Core.Data.MySql.Tests/MariaDbTests.cs b/tests/eQuantic.Core.Data.MySql.Tests/MariaDbTests.cs index 9cf2f29..50a9c9c 100644 --- a/tests/eQuantic.Core.Data.MySql.Tests/MariaDbTests.cs +++ b/tests/eQuantic.Core.Data.MySql.Tests/MariaDbTests.cs @@ -124,6 +124,9 @@ public Task A_staged_insert_of_a_taken_key_fails_the_commit_atomically() => [Test] public Task A_member_scoped_modify_leaves_the_other_members() => WriteOutcomeScenarios.PartialModifyKeepsOtherMembers(NewScope); + [Test] + public Task A_stored_null_reads_as_null_in_a_member_that_starts_with_a_value() => WriteOutcomeScenarios.StoredNullReadsAsNull(NewScope); + [Test] public Task A_bulk_load_of_a_taken_key_fails() => WriteOutcomeScenarios.BulkInsertOfTakenKeyFails(NewScope); diff --git a/tests/eQuantic.Core.Data.MySql.Tests/MySqlWriteOutcomeTests.cs b/tests/eQuantic.Core.Data.MySql.Tests/MySqlWriteOutcomeTests.cs index 57cc3c3..8ca5fc0 100644 --- a/tests/eQuantic.Core.Data.MySql.Tests/MySqlWriteOutcomeTests.cs +++ b/tests/eQuantic.Core.Data.MySql.Tests/MySqlWriteOutcomeTests.cs @@ -78,6 +78,9 @@ public Task A_staged_insert_of_a_taken_key_fails_the_commit_atomically() => [Test] public Task A_member_scoped_modify_leaves_the_other_members() => WriteOutcomeScenarios.PartialModifyKeepsOtherMembers(NewScope); + [Test] + public Task A_stored_null_reads_as_null_in_a_member_that_starts_with_a_value() => WriteOutcomeScenarios.StoredNullReadsAsNull(NewScope); + [Test] public Task A_bulk_load_of_a_taken_key_fails() => WriteOutcomeScenarios.BulkInsertOfTakenKeyFails(NewScope); diff --git a/tests/eQuantic.Core.Data.MySql.Tests/WriteOutcomeScenarios.cs b/tests/eQuantic.Core.Data.MySql.Tests/WriteOutcomeScenarios.cs index 160aae3..2d03780 100644 --- a/tests/eQuantic.Core.Data.MySql.Tests/WriteOutcomeScenarios.cs +++ b/tests/eQuantic.Core.Data.MySql.Tests/WriteOutcomeScenarios.cs @@ -161,6 +161,27 @@ public sealed class TickedNote : IEntity, IEntityTimeTrack public void SetKey(Guid key) => Id = key; } +/// +/// A row whose nullable members start with a value, as a generated model carries a column's default: a stored null +/// must read as null, never as the value the member starts with. +/// +public sealed class Preset : IEntity +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + public string? Note { get; set; } = "initial"; + + public int? Quota { get; set; } = 10; + + public bool? Enabled { get; set; } = true; + + public DateTime? Since { get; set; } = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + public Guid GetKey() => Id; + + public void SetKey(Guid key) => Id = key; +} + /// The write-outcome entities' mapping and migration, shared by every relational suite. internal static class WriteOutcomeSchema { @@ -170,6 +191,7 @@ public static Relational.RelationalModelBuilder Configure(Relational.RelationalM .Entity(_ => { }) .Entity(_ => { }) .Entity(_ => { }) + .Entity(entity => entity.Table("presets")) .Entity(entity => entity.Table("users")) .Entity(entity => entity.Key(x => x.Id, generated: true)) .Entity(_ => { }) @@ -192,6 +214,7 @@ public static IMigrationBuilder Migrate(IMigrationBuilder migration, bool partia .For(job => job.EnsureCollection()) .For(itemType => itemType.EnsureCollection()) .For(page => page.EnsureCollection()) + .For(preset => preset.EnsureCollection()) .For(user => user .EnsureCollection() .Index(x => x.Email, options => options.Unique().Named("ix_users_email"))) @@ -598,6 +621,37 @@ public static async Task PartialModifyKeepsOtherMembers(Func newS Assert.That(stored.Body, Is.EqualTo("text")); } + /// + /// A stored null reads as null in a member the entity initializes, by key and in a list: the materializer writes + /// a NULL cell instead of leaving the member as it started. + /// + public static async Task StoredNullReadsAsNull(Func newScope) + { + var preset = new Preset { Note = null, Quota = null, Enabled = null, Since = null }; + var kept = new Preset(); + using (var seed = newScope()) + { + await Repo(seed).AddAsync(preset); + await Repo(seed).AddAsync(kept); + await Commit(seed); + } + + using var check = newScope(); + var stored = (await Repo(check).GetAsync(preset.Id))!; + Assert.That(stored.Note, Is.Null); + Assert.That(stored.Quota, Is.Null); + Assert.That(stored.Enabled, Is.Null); + Assert.That(stored.Since, Is.Null); + + var listed = (await Repo(check).GetAllAsync()).Single(row => row.Id == preset.Id); + Assert.That(new object?[] { listed.Note, listed.Quota, listed.Enabled, listed.Since }, Is.All.Null); + + // What was stored as a value still reads as that value. + var other = (await Repo(check).GetAsync(kept.Id))!; + Assert.That((other.Note, other.Quota, other.Enabled, other.Since), + Is.EqualTo(("initial", (int?)10, (bool?)true, (DateTime?)new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)))); + } + /// /// An upsert on a key the store generates: the row holding the entity's key is updated, and a key no row holds /// inserts a row the store numbers, as an insert of a new entity does. diff --git a/tests/eQuantic.Core.Data.PostgreSql.Tests/PostgreSqlWriteOutcomeTests.cs b/tests/eQuantic.Core.Data.PostgreSql.Tests/PostgreSqlWriteOutcomeTests.cs index e2b4a2c..21fad73 100644 --- a/tests/eQuantic.Core.Data.PostgreSql.Tests/PostgreSqlWriteOutcomeTests.cs +++ b/tests/eQuantic.Core.Data.PostgreSql.Tests/PostgreSqlWriteOutcomeTests.cs @@ -83,6 +83,31 @@ public Task A_staged_insert_of_a_taken_key_fails_the_commit_atomically() => [Test] public Task A_member_scoped_modify_leaves_the_other_members() => WriteOutcomeScenarios.PartialModifyKeepsOtherMembers(NewScope); + [Test] + public Task A_stored_null_reads_as_null_in_a_member_that_starts_with_a_value() => WriteOutcomeScenarios.StoredNullReadsAsNull(NewScope); + + [Test] + public async Task A_stored_null_reads_as_null_through_raw_sql_too() + { + var preset = new Preset { Note = null, Quota = null, Enabled = null, Since = null }; + using (var seed = NewScope()) + { + await seed.ServiceProvider.GetRequiredService>().AddAsync(preset); + await seed.ServiceProvider.GetRequiredService().CommitAsync(); + } + + using var scope = NewScope(); + const string sql = "SELECT * FROM \"presets\" WHERE \"id\" = @p0"; + var repository = (RelationalReadRepository)scope.ServiceProvider.GetRequiredService>(); + var entity = (await repository.FromSqlAsync(sql, [preset.Id])).Single(); + var bound = (await ((RelationalUnitOfWork)scope.ServiceProvider.GetRequiredService()).QueryAsync(sql, [preset.Id])).Single(); + + foreach (var read in new[] { entity, bound }) + { + Assert.That(new object?[] { read.Note, read.Quota, read.Enabled, read.Since }, Is.All.Null); + } + } + [Test] public Task A_bulk_load_of_a_taken_key_fails() => WriteOutcomeScenarios.BulkInsertOfTakenKeyFails(NewScope); diff --git a/tests/eQuantic.Core.Data.PostgreSql.Tests/WriteOutcomeScenarios.cs b/tests/eQuantic.Core.Data.PostgreSql.Tests/WriteOutcomeScenarios.cs index 5680ad2..0275d9e 100644 --- a/tests/eQuantic.Core.Data.PostgreSql.Tests/WriteOutcomeScenarios.cs +++ b/tests/eQuantic.Core.Data.PostgreSql.Tests/WriteOutcomeScenarios.cs @@ -161,6 +161,27 @@ public sealed class TickedNote : IEntity, IEntityTimeTrack public void SetKey(Guid key) => Id = key; } +/// +/// A row whose nullable members start with a value, as a generated model carries a column's default: a stored null +/// must read as null, never as the value the member starts with. +/// +public sealed class Preset : IEntity +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + public string? Note { get; set; } = "initial"; + + public int? Quota { get; set; } = 10; + + public bool? Enabled { get; set; } = true; + + public DateTime? Since { get; set; } = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + public Guid GetKey() => Id; + + public void SetKey(Guid key) => Id = key; +} + /// The write-outcome entities' mapping and migration, shared by every relational suite. internal static class WriteOutcomeSchema { @@ -170,6 +191,7 @@ public static Relational.RelationalModelBuilder Configure(Relational.RelationalM .Entity(_ => { }) .Entity(_ => { }) .Entity(_ => { }) + .Entity(entity => entity.Table("presets")) .Entity(entity => entity.Table("users")) .Entity(entity => entity.Key(x => x.Id, generated: true)) .Entity(_ => { }) @@ -192,6 +214,7 @@ public static IMigrationBuilder Migrate(IMigrationBuilder migration, bool partia .For(job => job.EnsureCollection()) .For(itemType => itemType.EnsureCollection()) .For(page => page.EnsureCollection()) + .For(preset => preset.EnsureCollection()) .For(user => user .EnsureCollection() .Index(x => x.Email, options => options.Unique().Named("ix_users_email"))) @@ -598,6 +621,37 @@ public static async Task PartialModifyKeepsOtherMembers(Func newS Assert.That(stored.Body, Is.EqualTo("text")); } + /// + /// A stored null reads as null in a member the entity initializes, by key and in a list: the materializer writes + /// a NULL cell instead of leaving the member as it started. + /// + public static async Task StoredNullReadsAsNull(Func newScope) + { + var preset = new Preset { Note = null, Quota = null, Enabled = null, Since = null }; + var kept = new Preset(); + using (var seed = newScope()) + { + await Repo(seed).AddAsync(preset); + await Repo(seed).AddAsync(kept); + await Commit(seed); + } + + using var check = newScope(); + var stored = (await Repo(check).GetAsync(preset.Id))!; + Assert.That(stored.Note, Is.Null); + Assert.That(stored.Quota, Is.Null); + Assert.That(stored.Enabled, Is.Null); + Assert.That(stored.Since, Is.Null); + + var listed = (await Repo(check).GetAllAsync()).Single(row => row.Id == preset.Id); + Assert.That(new object?[] { listed.Note, listed.Quota, listed.Enabled, listed.Since }, Is.All.Null); + + // What was stored as a value still reads as that value. + var other = (await Repo(check).GetAsync(kept.Id))!; + Assert.That((other.Note, other.Quota, other.Enabled, other.Since), + Is.EqualTo(("initial", (int?)10, (bool?)true, (DateTime?)new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)))); + } + /// /// An upsert on a key the store generates: the row holding the entity's key is updated, and a key no row holds /// inserts a row the store numbers, as an insert of a new entity does. diff --git a/tests/eQuantic.Core.Data.SqlServer.Tests/SqlServerWriteOutcomeTests.cs b/tests/eQuantic.Core.Data.SqlServer.Tests/SqlServerWriteOutcomeTests.cs index 8da0ccd..f412d46 100644 --- a/tests/eQuantic.Core.Data.SqlServer.Tests/SqlServerWriteOutcomeTests.cs +++ b/tests/eQuantic.Core.Data.SqlServer.Tests/SqlServerWriteOutcomeTests.cs @@ -78,6 +78,9 @@ public Task A_staged_insert_of_a_taken_key_fails_the_commit_atomically() => [Test] public Task A_member_scoped_modify_leaves_the_other_members() => WriteOutcomeScenarios.PartialModifyKeepsOtherMembers(NewScope); + [Test] + public Task A_stored_null_reads_as_null_in_a_member_that_starts_with_a_value() => WriteOutcomeScenarios.StoredNullReadsAsNull(NewScope); + [Test] public Task A_bulk_load_of_a_taken_key_fails() => WriteOutcomeScenarios.BulkInsertOfTakenKeyFails(NewScope); diff --git a/tests/eQuantic.Core.Data.SqlServer.Tests/WriteOutcomeScenarios.cs b/tests/eQuantic.Core.Data.SqlServer.Tests/WriteOutcomeScenarios.cs index 489469f..583dfc3 100644 --- a/tests/eQuantic.Core.Data.SqlServer.Tests/WriteOutcomeScenarios.cs +++ b/tests/eQuantic.Core.Data.SqlServer.Tests/WriteOutcomeScenarios.cs @@ -161,6 +161,27 @@ public sealed class TickedNote : IEntity, IEntityTimeTrack public void SetKey(Guid key) => Id = key; } +/// +/// A row whose nullable members start with a value, as a generated model carries a column's default: a stored null +/// must read as null, never as the value the member starts with. +/// +public sealed class Preset : IEntity +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + public string? Note { get; set; } = "initial"; + + public int? Quota { get; set; } = 10; + + public bool? Enabled { get; set; } = true; + + public DateTime? Since { get; set; } = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + public Guid GetKey() => Id; + + public void SetKey(Guid key) => Id = key; +} + /// The write-outcome entities' mapping and migration, shared by every relational suite. internal static class WriteOutcomeSchema { @@ -170,6 +191,7 @@ public static Relational.RelationalModelBuilder Configure(Relational.RelationalM .Entity(_ => { }) .Entity(_ => { }) .Entity(_ => { }) + .Entity(entity => entity.Table("presets")) .Entity(entity => entity.Table("users")) .Entity(entity => entity.Key(x => x.Id, generated: true)) .Entity(_ => { }) @@ -192,6 +214,7 @@ public static IMigrationBuilder Migrate(IMigrationBuilder migration, bool partia .For(job => job.EnsureCollection()) .For(itemType => itemType.EnsureCollection()) .For(page => page.EnsureCollection()) + .For(preset => preset.EnsureCollection()) .For(user => user .EnsureCollection() .Index(x => x.Email, options => options.Unique().Named("ix_users_email"))) @@ -598,6 +621,37 @@ public static async Task PartialModifyKeepsOtherMembers(Func newS Assert.That(stored.Body, Is.EqualTo("text")); } + /// + /// A stored null reads as null in a member the entity initializes, by key and in a list: the materializer writes + /// a NULL cell instead of leaving the member as it started. + /// + public static async Task StoredNullReadsAsNull(Func newScope) + { + var preset = new Preset { Note = null, Quota = null, Enabled = null, Since = null }; + var kept = new Preset(); + using (var seed = newScope()) + { + await Repo(seed).AddAsync(preset); + await Repo(seed).AddAsync(kept); + await Commit(seed); + } + + using var check = newScope(); + var stored = (await Repo(check).GetAsync(preset.Id))!; + Assert.That(stored.Note, Is.Null); + Assert.That(stored.Quota, Is.Null); + Assert.That(stored.Enabled, Is.Null); + Assert.That(stored.Since, Is.Null); + + var listed = (await Repo(check).GetAllAsync()).Single(row => row.Id == preset.Id); + Assert.That(new object?[] { listed.Note, listed.Quota, listed.Enabled, listed.Since }, Is.All.Null); + + // What was stored as a value still reads as that value. + var other = (await Repo(check).GetAsync(kept.Id))!; + Assert.That((other.Note, other.Quota, other.Enabled, other.Since), + Is.EqualTo(("initial", (int?)10, (bool?)true, (DateTime?)new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)))); + } + /// /// An upsert on a key the store generates: the row holding the entity's key is updated, and a key no row holds /// inserts a row the store numbers, as an insert of a new entity does.