Skip to content

Fix issues with line breaks in string literals #1478

Activity

  1. added this to the 5.0.0 milestone on Aug 29, 2020
  2. self-assigned this
    on Aug 29, 2020
  3. added 2 commits that reference this issue on Aug 29, 2020
    6abeeac
    b915abf
  4. modified the milestones: 5.0.0, 6.0.0 on Oct 25, 2020
  5. modified the milestones: 6.0.0, Backlog on Jul 16, 2021
  6. added theissue type on Jun 14, 2025
  7. roji commented on Oct 21, 2026

    @roji
    MemberAuthor

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    Confirmed on released Npgsql provider 10.0.3, 8.0.11, and current main (59473359), executing generated idempotent migration scripts against an isolated PostgreSQL 18 instance. Reading the database back confirms that string defaults, inserted seed data, table comments, and column comments all acquire indentation, and CRLF is normalized to LF. For example, "Don't\r\nGO\r\n this way\\n\r\n" becomes "Don't\n GO\n this way\\n\n ". This is a longstanding provider bug, not an identified recent regression; no last-known-working version was established.

    EF's migration script builder indents command text and normalizes physical line endings. Npgsql currently emits physical CR/LF inside ordinary string literals, so this formatting changes the value. The PostgreSQL-specific fix is to use an escape string literal, e.g. E'Don''t\r\nGO\r\n', for strings containing CR/LF, escaping existing backslashes as well. This is still a literal, so unlike concatenation it is valid in COMMENT ON ... IS ... and other literal-only contexts.

    Related work:

    minimal repro

    Console application referencing Npgsql.EntityFrameworkCore.PostgreSQL 10.0.3 and Testcontainers.PostgreSql 4.15.0, with a Docker-compatible runtime:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Infrastructure;
    using Microsoft.EntityFrameworkCore.Migrations;
    using Microsoft.Extensions.Logging;
    using Npgsql;
    using Testcontainers.PostgreSql;
    
    await using var postgres = new PostgreSqlBuilder("postgres:18").Build();
    await postgres.StartAsync();
    Environment.SetEnvironmentVariable("Test__Npgsql__DefaultConnection", postgres.GetConnectionString());
    
    await using var context = new TestContext();
    var script = context.GetService<IMigrator>().GenerateScript(options: MigrationsSqlGenerationOptions.Idempotent);
    await context.Database.ExecuteSqlRawAsync(script);
    await context.Database.ExecuteSqlRawAsync("""INSERT INTO "Blogs" ("Id") VALUES (2)""");
    
    await using var connection = new NpgsqlConnection(postgres.GetConnectionString());
    await connection.OpenAsync();
    foreach (var sql in new[]
    {
        """SELECT "Name" FROM "Blogs" WHERE "Id" = 1""",
        """SELECT "Name" FROM "Blogs" WHERE "Id" = 2""",
        """SELECT obj_description('"Blogs"'::regclass)""",
        """SELECT col_description('"Blogs"'::regclass, 2)"""
    })
    {
        await using var command = new NpgsqlCommand(sql, connection);
        var actual = (string)(await command.ExecuteScalarAsync())!;
        Console.WriteLine($"{System.Text.Json.JsonSerializer.Serialize(actual)}; exact match: {actual == TestContext.Value}");
    }
    
    public class TestContext : DbContext
    {
        public const string Value = "Don't\r\nGO\r\n  this way\\n\r\n";
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(Environment.GetEnvironmentVariable("Test__Npgsql__DefaultConnection"))
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    }
    
    [DbContext(typeof(TestContext))]
    [Migration("20261021000000_Multiline")]
    public class MultilineMigration : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                "Blogs",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false),
                    Name = table.Column<string>(
                        type: "text", nullable: false,
                        defaultValue: TestContext.Value, comment: TestContext.Value)
                },
                constraints: table => table.PrimaryKey("PK_Blogs", x => x.Id),
                comment: TestContext.Value);
            migrationBuilder.InsertData(
                "Blogs", ["Id", "Name"], ["integer", "text"], [1, TestContext.Value]);
        }
    }

    All four exact-match checks return False.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions