Skip to content

Fix hstore SQL literal generation for null and escaped values - #3780

Merged
roji merged 4 commits into
npgsql:mainfrom
brianpursley:hstore-fix
Oct 24, 2026
Merged

roji merged 4 commits into
npgsql:mainfrom
brianpursley:hstore-fix

Conversation

@brianpursley

@brianpursley brianpursley commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix hstore SQL literal generation bugs in NpgsqlHstoreTypeMapping.

Fixes #4103.

Details

The previous implementation produced invalid or corrupted literals in several cases:

  • A null-valued entry would not have the separating comma emitted leading to unexpected results
  • Empty dictionaries produced an unterminated literal
  • Keys/values containing special characters were not escaped correctly

This PR updates hstore literal generation to:

  • Emit separators independently of null handling
  • Handle empty dictionaries correctly
  • Escape \, " and ' appropriately for use inside the generated SQL literal

Unit tests were added for each of these fixed cases.

Copilot AI review requested due to automatic review settings March 12, 2026 21:55

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes SQL literal generation for PostgreSQL hstore in NpgsqlHstoreTypeMapping to correctly handle null values, empty dictionaries, and escaping of special characters, with unit tests covering the corrected behavior.

Changes:

  • Reworked hstore SQL literal generation to emit separators correctly and support empty dictionaries.
  • Added proper escaping for \, " and ' when generating hstore SQL literals.
  • Added unit tests for null values, escaping, and empty dictionaries.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/EFCore.PG/Storage/Internal/Mapping/NpgsqlHstoreTypeMapping.cs Fixes hstore SQL literal formatting/escaping and handles empty dictionaries safely.
test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingTest.cs Adds unit test coverage for the fixed hstore literal generation edge cases.

Copilot AI review requested due to automatic review settings March 12, 2026 22:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

@brianpursley

brianpursley commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Here is a simple Program.cs that exercises the changes:

using var dbContext = new ExampleDbContext();
dbContext.Database.EnsureDeleted();
dbContext.Database.EnsureCreated();

dbContext.Blogs.Add(new Blog { Name = "ABC"});
dbContext.SaveChanges();

var blog = dbContext.Blogs.Single(b => b.Name == "ABC");

foreach (var item in blog.Features!)
{
    Console.WriteLine($"{item.Key}: {item.Value ?? "<NULL>"}");
}

public class ExampleDbContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasPostgresExtension("hstore");
        modelBuilder.Entity<Blog>()
            .Property(x => x.Features)
            .HasDefaultValue(new Dictionary<string, string?>
            {
                ["k1"] = null,
                ["k\"2\""] = "v\"2\"",
                ["k'3'"] = "v'3'",
                ["k\\4"] = "v\\4"
            });
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseNpgsql("Host=localhost;Username=postgres;Password=postgres;Database=ExampleDb")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();
    }
}

public class Blog
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public Dictionary<string, string?>? Features { get; set; } 
}

Logged table creation:

CREATE TABLE "Blogs" (
    "Id" integer GENERATED BY DEFAULT AS IDENTITY,
    "Name" text NOT NULL,
    "Features" hstore DEFAULT HSTORE '"k1"=>NULL,"k\"2\""=>"v\"2\"","k''3''"=>"v''3''","k\\4"=>"v\\4"',
    CONSTRAINT "PK_Blogs" PRIMARY KEY ("Id")
);

Output:

k1: <NULL>
k\4: v\4
k"2": v"2"
k'3': v'3'

For contrast, running this test program without the PR results in a syntax error because of lack of escape handling:

fail: 3/17/2026 14:42:59.033 RelationalEventId.CommandError[20102] (Microsoft.EntityFrameworkCore.Database.Command) 
      Failed executing DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE "Blogs" (
          "Id" integer GENERATED BY DEFAULT AS IDENTITY,
          "Name" text NOT NULL,
          "Features" hstore DEFAULT HSTORE '"k1"=>NULL"k"2""=>"v"2"","k'3'"=>"v'3'","k\4"=>"v\4"',
          CONSTRAINT "PK_Blogs" PRIMARY KEY ("Id")
      );
Unhandled exception. Npgsql.PostgresException (0x80004005): 42601: syntax error at or near "3"

POSITION: 167
   at Npgsql.Internal.NpgsqlConnector.ReadMessageLong(Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
   at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
   at Npgsql.NpgsqlDataReader.NextResult()
   at Npgsql.NpgsqlCommand.ExecuteReader(Boolean async, CommandBehavior behavior, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(Boolean async, CommandBehavior behavior, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteNonQuery()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.Execute(IReadOnlyList`1 migrationCommands, IRelationalConnection connection, MigrationExecutionState executionState, Boolean beginTransaction, Boolean commitTransaction, Nullable`1 isolationLevel)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.<>c.<ExecuteNonQuery>b__3_1(DbContext _, ValueTuple`6 s)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded) in /Users/bpursley/projects/efcore.pg/src/EFCore.PG/Storage/Internal/NpgsqlExecutionStrategy.cs:line 46
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IReadOnlyList`1 migrationCommands, IRelationalConnection connection, MigrationExecutionState executionState, Boolean commitTransaction, Nullable`1 isolationLevel)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.CreateTables() in /Users/bpursley/projects/efcore.pg/src/EFCore.PG/Storage/Internal/NpgsqlDatabaseCreator.cs:line 349
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated()
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()
   at Program.<Main>$(String[] args) in /Users/bpursley/projects/efcore.pg/src/ConsoleApp1/Program.cs:line 3
  Exception data:
    Severity: ERROR
    SqlState: 42601
    MessageText: syntax error at or near "3"
    Position: 167
    File: scan.l
    Line: 1244
    Routine: scanner_yyerror

@roji roji left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @brianpursley, LGTM and sorry it took so long to get this reviewed. Rebased, pushed a tiny commit to improve test coverage, and will merge and backport.

If you want, post a comment on #4103 and I'll assign it to you for credit.

@roji
roji merged commit 157ae7f into npgsql:main Oct 24, 2026
8 checks passed
roji added a commit that referenced this pull request Oct 24, 2026
…#4107)

(cherry picked from commit 157ae7f)

Co-authored-by: Brian Pursley <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot App <[email protected]>
roji added a commit that referenced this pull request Oct 24, 2026
…#4105)

(cherry picked from commit 157ae7f)

Co-authored-by: Brian Pursley <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot App <[email protected]>
roji added a commit that referenced this pull request Oct 24, 2026
…#4106)

(cherry picked from commit 157ae7f)

Co-authored-by: Brian Pursley <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

hstore SQL literals corrupt null values and backslashes and fail for empty dictionaries and quotes

3 participants