Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 62 additions & 23 deletions src/EFCore.PG/Migrations/NpgsqlMigrationsSqlGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -410,8 +410,11 @@ protected override void Generate(AlterColumnOperation operation, IModel? model,
var column = model?.GetRelationalModel().FindTable(operation.Table, operation.Schema)
?.Columns.FirstOrDefault(c => c.Name == operation.Name);

ApplyTsVectorColumnSql(operation, model, operation.Schema, operation.Table);
ApplyTsVectorColumnSql(operation.OldColumn, model, operation.OldColumn.Schema, operation.OldColumn.Table);
ApplyTsVectorColumnSql(operation, model, operation.Name, operation.Schema, operation.Table);

// Note: OldColumn doesn't have Schema, Table or Name populated (https://github.com/dotnet/efcore/issues/28041), so we take these
// from the new column (they're identical in any case).
ApplyTsVectorColumnSql(operation.OldColumn, model, operation.Name, operation.Schema, operation.Table);

if (operation.ComputedColumnSql != operation.OldColumn.ComputedColumnSql
|| operation.IsStored != operation.OldColumn.IsStored)
Expand Down Expand Up @@ -840,7 +843,7 @@ protected override void Generate(
var indexColumns = GetIndexColumns(operation);

var columnsExpression = operation[NpgsqlAnnotationNames.TsVectorConfig] is string tsVectorConfig
? ColumnsToTsVector(indexColumns.Select(i => i.Name), tsVectorConfig, model, operation.Schema, operation.Table)
? ColumnsToTsVector(operation.Name, indexColumns.Select(i => i.Name), tsVectorConfig, model, operation.Schema, operation.Table)
: IndexColumnList(indexColumns, method);

builder
Expand Down Expand Up @@ -1508,7 +1511,7 @@ protected override void ColumnDefinition(
}
}

ApplyTsVectorColumnSql(operation, model, schema, table);
ApplyTsVectorColumnSql(operation, model, operation.Name, schema, table);

if (operation.ComputedColumnSql is not null)
{
Expand Down Expand Up @@ -1561,7 +1564,7 @@ protected override void ColumnDefinition(
/// Checks for a <see cref="NpgsqlAnnotationNames.TsVectorConfig"/> annotation on the given column, and if found, assigns
/// the appropriate SQL to <see cref="ColumnOperation.ComputedColumnSql"/>.
/// </summary>
protected virtual void ApplyTsVectorColumnSql(ColumnOperation column, IModel? model, string? schema, string table)
protected virtual void ApplyTsVectorColumnSql(ColumnOperation column, IModel? model, string name, string? schema, string table)
{
if (column[NpgsqlAnnotationNames.TsVectorConfig] is string tsVectorConfig)
{
Expand All @@ -1573,7 +1576,7 @@ protected virtual void ApplyTsVectorColumnSql(ColumnOperation column, IModel? mo
$"{nameof(NpgsqlAnnotationNames.TsVectorProperties)} is absent or empty");
}

column.ComputedColumnSql = ColumnsToTsVector(tsVectorIncludedColumns, tsVectorConfig, model, schema, table);
column.ComputedColumnSql = ColumnsToTsVector(name, tsVectorIncludedColumns, tsVectorConfig, model, schema, table);
column.IsStored = true;

column.RemoveAnnotation(NpgsqlAnnotationNames.TsVectorConfig);
Expand Down Expand Up @@ -1974,25 +1977,61 @@ private string IndexColumnList(IndexColumn[] columns, string? method)
return builder.ToString();
}

private string ColumnsToTsVector(IEnumerable<string> columns, string tsVectorConfig, IModel? model, string? schema, string table)
private string ColumnsToTsVector(
string columnOrIndexName,
IEnumerable<string> columnNames,
string tsVectorConfig,
IModel? model,
string? schema,
string table)
{
return new StringBuilder()
.Append("to_tsvector(")
.Append(_stringTypeMapping.GenerateSqlLiteral(tsVectorConfig))
.Append(", ")
.Append(string.Join(" || ' ' || ", columns.Select(GetTsVectorColumnExpression)))
.Append(")")
.ToString();

string GetTsVectorColumnExpression(string columnName)
{
var delimitedColumnName = DelimitIdentifier(columnName);
var column = model?.GetRelationalModel()
.FindTable(table, schema)?.Columns.FirstOrDefault(c => c.Name == columnName);
return column?.IsNullable != false
? $"coalesce({delimitedColumnName}, '')"
: delimitedColumnName;
var columns = columnNames
.Select(columnName => model?.GetRelationalModel().FindTable(table, schema)?.Columns.FirstOrDefault(c => c.Name == columnName))
.ToArray();

IEnumerable<IGrouping<string, IColumn>> columnGroups = columns
.GroupBy(
c => c?.StoreType switch
{
"json" => "json",
"jsonb" => "jsonb",
null => "null",
_ => "text"

// Note: we currently don't support array_to_tsvector since it doesn't accept a search configuration
})!;

var tsVectorConfigLiteral = _stringTypeMapping.GenerateSqlLiteral(tsVectorConfig);

var builder = new StringBuilder();

foreach (var columnGroup in columnGroups)
{
if (builder.Length > 0)
{
builder.Append(" || ");
}

builder.Append(columnGroup.Key switch
{
"text" => $"to_tsvector({tsVectorConfigLiteral}, {string.Join(" || ' ' || ", columnGroup.Select(TextColumn))})",
"json" => string.Join(" || ", columnGroup.Select(c =>
$@"json_to_tsvector({tsVectorConfigLiteral}, {JsonColumn(c)}, '""all""')")),
"jsonb" => string.Join(" || ", columnGroup.Select(c =>
$@"jsonb_to_tsvector({tsVectorConfigLiteral}, {JsonColumn(c)}, '""all""')")),
"null" => throw new InvalidOperationException(
$"Column or index {columnOrIndexName} refers to unknown column in tsvector definition"),
_ => throw new ArgumentOutOfRangeException()
});
}

return builder.ToString();

string TextColumn(IColumn column)
=> column.IsNullable ? $"coalesce({DelimitIdentifier(column.Name)}, '')" : DelimitIdentifier(column.Name);

string JsonColumn(IColumn column)
=> column.IsNullable ? $"coalesce({DelimitIdentifier(column.Name)}, '{{}}')" : DelimitIdentifier(column.Name);
}

private static bool TryParseSchema(string identifier, out string name, out string? schema)
Expand Down
176 changes: 113 additions & 63 deletions test/EFCore.PG.FunctionalTests/Migrations/MigrationsNpgsqlTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -910,36 +910,6 @@ await Test(
@"ALTER TABLE ""People"" ADD ""Name"" text NULL;");
}

[Fact]
public virtual async Task Add_column_generated_tsvector()
{
if (TestEnvironment.PostgresVersion.IsUnder(12))
{
return;
}

await Test(
builder => builder.Entity(
"Blogs", e =>
{
e.Property<string>("Title").IsRequired();
e.Property<string>("Description");
}),
_ => { },
builder => builder.Entity("Blogs").Property<NpgsqlTsVector>("TsVector")
.IsGeneratedTsVectorColumn("english", "Title", "Description"),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "TsVector");
Assert.Equal("tsvector", column.StoreType);
Assert.Equal(@"to_tsvector('english'::regconfig, ((""Title"" || ' '::text) || COALESCE(""Description"", ''::text)))", column.ComputedColumnSql);
});

AssertSql(
@"ALTER TABLE ""Blogs"" ADD ""TsVector"" tsvector GENERATED ALWAYS AS (to_tsvector('english', ""Title"" || ' ' || coalesce(""Description"", ''))) STORED;");
}

[Fact]
public virtual async Task Add_column_with_compression_method()
{
Expand Down Expand Up @@ -1618,39 +1588,6 @@ await Test(
}
#pragma warning restore CS0618

[Fact]
public virtual async Task Alter_column_generated_tsvector_change_config()
{
if (TestEnvironment.PostgresVersion.IsUnder(12))
{
return;
}

await Test(
builder => builder.Entity(
"Blogs", e =>
{
e.Property<string>("Title").IsRequired();
e.Property<string>("Description");
}),
builder => builder.Entity("Blogs").Property<NpgsqlTsVector>("TsVector")
.IsGeneratedTsVectorColumn("german", "Title", "Description"),
builder => builder.Entity("Blogs").Property<NpgsqlTsVector>("TsVector")
.IsGeneratedTsVectorColumn("english", "Title", "Description"),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "TsVector");
Assert.Equal("tsvector", column.StoreType);
Assert.Equal(@"to_tsvector('english'::regconfig, ((""Title"" || ' '::text) || COALESCE(""Description"", ''::text)))", column.ComputedColumnSql);
});

AssertSql(
@"ALTER TABLE ""Blogs"" DROP COLUMN ""TsVector"";",
//
@"ALTER TABLE ""Blogs"" ADD ""TsVector"" tsvector GENERATED ALWAYS AS (to_tsvector('english', ""Title"" || ' ' || coalesce(""Description"", ''))) STORED;");
}

[Fact]
public virtual async Task Alter_column_computed_set_collation()
{
Expand Down Expand Up @@ -2861,6 +2798,119 @@ public virtual Task Alter_collation_throws()

#endregion PostgreSQL collation management

#region PostgreSQL full-text search

[Fact]
public virtual async Task Add_column_generated_tsvector_over_text()
{
if (TestEnvironment.PostgresVersion.IsUnder(12))
{
return;
}

await Test(
builder => builder.Entity("Blogs", e => e.Property<string>("TextColumn").IsRequired()),
_ => { },
builder => builder.Entity("Blogs").Property<NpgsqlTsVector>("SearchColumn").IsGeneratedTsVectorColumn("english", "TextColumn"),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "SearchColumn");
Assert.Equal("tsvector", column.StoreType);
});

AssertSql(
@"ALTER TABLE ""Blogs"" ADD ""SearchColumn"" tsvector GENERATED ALWAYS AS (to_tsvector('english', ""TextColumn"")) STORED;");
}

[Fact]
public virtual async Task Add_column_generated_tsvector_over_jsonb()
{
if (TestEnvironment.PostgresVersion.IsUnder(12))
{
return;
}

await Test(
builder => builder.Entity("People").Property<string>("JsonbColumn").HasColumnType("jsonb").IsRequired(),
_ => { },
builder => builder.Entity("People").Property<NpgsqlTsVector>("SearchColumn").IsGeneratedTsVectorColumn("english", "JsonbColumn"),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "SearchColumn");
Assert.Equal("tsvector", column.StoreType);
});

AssertSql(
@"ALTER TABLE ""People"" ADD ""SearchColumn"" tsvector GENERATED ALWAYS AS (jsonb_to_tsvector('english', ""JsonbColumn"", '""all""')) STORED;");
}

[Fact]
public virtual async Task Add_column_generated_tsvector_over_mixed()
{
if (TestEnvironment.PostgresVersion.IsUnder(12))
{
return;
}

await Test(
builder =>
{
builder.Entity("People").Property<string>("RequiredTextColumn").IsRequired();
builder.Entity("People").Property<string>("OptionalTextColumn");
builder.Entity("People").Property<string>("RequiredJsonbColumn").HasColumnType("jsonb").IsRequired();
builder.Entity("People").Property<string>("OptionalJsonColumn").HasColumnType("json");
},
_ => { },
builder => builder.Entity("People").Property<NpgsqlTsVector>("SearchColumn")
.IsGeneratedTsVectorColumn("english", "RequiredTextColumn", "OptionalTextColumn", "RequiredJsonbColumn", "OptionalJsonColumn"),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "SearchColumn");
Assert.Equal("tsvector", column.StoreType);
});

AssertSql(
@"ALTER TABLE ""People"" ADD ""SearchColumn"" tsvector GENERATED ALWAYS AS (to_tsvector('english', ""RequiredTextColumn"" || ' ' || coalesce(""OptionalTextColumn"", '')) || jsonb_to_tsvector('english', ""RequiredJsonbColumn"", '""all""') || json_to_tsvector('english', coalesce(""OptionalJsonColumn"", '{}'), '""all""')) STORED;");
}

[Fact]
public virtual async Task Alter_column_generated_tsvector_change_config()
{
if (TestEnvironment.PostgresVersion.IsUnder(12))
{
return;
}

await Test(
builder => builder.Entity(
"Blogs", e =>
{
e.Property<string>("Title").IsRequired();
e.Property<string>("Description");
}),
builder => builder.Entity("Blogs").Property<NpgsqlTsVector>("TsVector")
.IsGeneratedTsVectorColumn("german", "Title", "Description"),
builder => builder.Entity("Blogs").Property<NpgsqlTsVector>("TsVector")
.IsGeneratedTsVectorColumn("english", "Title", "Description"),
model =>
{
var table = Assert.Single(model.Tables);
var column = Assert.Single(table.Columns, c => c.Name == "TsVector");
Assert.Equal("tsvector", column.StoreType);
Assert.Equal(@"to_tsvector('english'::regconfig, ((""Title"" || ' '::text) || COALESCE(""Description"", ''::text)))", column.ComputedColumnSql);
});

AssertSql(
@"ALTER TABLE ""Blogs"" DROP COLUMN ""TsVector"";",
//
@"ALTER TABLE ""Blogs"" ADD ""TsVector"" tsvector GENERATED ALWAYS AS (to_tsvector('english', ""Title"" || ' ' || coalesce(""Description"", ''))) STORED;");
}

#endregion PostgreSQL full-text search

protected override string NonDefaultCollation => "POSIX";

public class MigrationsNpgsqlFixture : MigrationsFixtureBase
Expand Down