Skip to content

Commit 29da187

Browse files
authored
Cherry pick #3787 into release/2.1 (#3838)
## Why make this change? Closes #3837 ## What is this change? ## How was this tested? - [x] Integration Tests - [x] Unit Tests ## Sample Request(s) N/A
1 parent b86e343 commit 29da187

12 files changed

Lines changed: 778 additions & 3 deletions

‎src/Core/Models/DbConnectionParam.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,9 @@ public DbConnectionParam(object? value, DbType? dbType = null, SqlDbType? sqlDbT
3535

3636
// Nullable integer parameter representing length. nullable for back compatibility and for where its not needed
3737
public int? Length { get; set; }
38+
39+
/// <summary>
40+
/// Whether the database should infer this parameter's native type from its SQL context.
41+
/// </summary>
42+
public bool UseDatabaseTypeInference { get; set; }
3843
}

‎src/Core/Resolvers/DWSqlQueryBuilder.cs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -442,7 +442,14 @@ public string Build(SqlUpsertQueryStructure structure)
442442
string pkPredicates = JoinPredicateStrings(Build(structure.Predicates));
443443

444444
string updateOperations = Build(structure.UpdateOperations, ", ");
445-
string queryToGetCountOfRecordWithPK = $"SELECT COUNT(*) as {COUNT_ROWS_WITH_GIVEN_PK} FROM {tableName} WHERE {pkPredicates}";
445+
// Data Warehouse logical keys are not necessarily enforced by a unique constraint. For an
446+
// insert-capable upsert, take and hold an exclusive source-table lock before checking whether
447+
// the key exists so concurrent requests cannot both choose INSERT. Update-only fallback queries
448+
// cannot insert and therefore do not need this additional serialization.
449+
string existenceCheckTable = structure.IsFallbackToUpdate
450+
? tableName
451+
: $"{tableName} WITH (TABLOCKX, HOLDLOCK)";
452+
string queryToGetCountOfRecordWithPK = $"SELECT COUNT(*) as {COUNT_ROWS_WITH_GIVEN_PK} FROM {existenceCheckTable} WHERE {pkPredicates}";
446453

447454
// Query to get the number of records with a given PK.
448455
string prefixQuery = $"DECLARE @ROWS_TO_UPDATE int;" +

‎src/Core/Resolvers/MsSqlQueryBuilder.cs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,14 @@ public string Build(SqlUpsertQueryStructure structure)
285285
string updateOperations = Build(structure.UpdateOperations, ", ");
286286
string columnsToBeReturned =
287287
MakeOutputColumns(structure.OutputColumns, isUpdateTriggerEnabled ? string.Empty : OutputQualifier.Inserted.ToString());
288-
string queryToGetCountOfRecordWithPK = $"SELECT COUNT(*) as {COUNT_ROWS_WITH_GIVEN_PK} FROM {tableName} WHERE {pkPredicates}";
288+
// Insert-capable upserts must serialize the existence decision with competing upserts for
289+
// the same key. UPDLOCK avoids lock-conversion deadlocks and HOLDLOCK retains the key-range
290+
// lock (including a missing-key range) through the ambient transaction. Update-only fallback
291+
// queries do not have an insert race and retain the existing locking behavior.
292+
string existenceCheckTable = structure.IsFallbackToUpdate
293+
? tableName
294+
: $"{tableName} WITH (UPDLOCK, HOLDLOCK)";
295+
string queryToGetCountOfRecordWithPK = $"SELECT COUNT(*) as {COUNT_ROWS_WITH_GIVEN_PK} FROM {existenceCheckTable} WHERE {pkPredicates}";
289296

290297
// Query to get the number of records with a given PK.
291298
string prefixQuery = $"DECLARE @ROWS_TO_UPDATE int;" +

‎src/Core/Resolvers/PostgreSqlExecutor.cs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
using Microsoft.AspNetCore.Http;
1414
using Microsoft.Extensions.Logging;
1515
using Npgsql;
16+
using NpgsqlTypes;
1617

1718
namespace Azure.DataApiBuilder.Core.Resolvers
1819
{
@@ -148,10 +149,40 @@ private static bool ShouldManagedIdentityAccessBeAttempted(NpgsqlConnectionStrin
148149
return string.IsNullOrEmpty(builder.Password);
149150
}
150151

152+
/// <inheritdoc />
153+
public override void PopulateDbTypeForParameter(
154+
KeyValuePair<string, DbConnectionParam> parameterEntry,
155+
DbParameter parameter)
156+
{
157+
if (parameterEntry.Value.UseDatabaseTypeInference && parameter is NpgsqlParameter npgsqlParameter)
158+
{
159+
npgsqlParameter.NpgsqlDbType = NpgsqlDbType.Unknown;
160+
}
161+
}
162+
151163
/// <inheritdoc/>
152164
public override async Task<DbResultSet> GetMultipleResultSetsIfAnyAsync(
153165
DbDataReader dbDataReader, List<string>? args = null)
154166
{
167+
// Insert-capable PostgreSQL upserts acquire a transaction-level advisory lock in a separate
168+
// first statement. Consume that result before reading the existence count. Keeping the lock
169+
// statement separate ensures the count receives a fresh READ COMMITTED snapshot after any
170+
// competing same-key transaction has committed.
171+
if (Enumerable.Range(0, dbDataReader.FieldCount).Any(
172+
ordinal => string.Equals(
173+
dbDataReader.GetName(ordinal),
174+
PostgresQueryBuilder.UPSERT_LOCK_ACQUIRED,
175+
StringComparison.Ordinal)))
176+
{
177+
if (!await dbDataReader.NextResultAsync())
178+
{
179+
throw new DataApiBuilderException(
180+
message: $"Neither insert nor update could be performed.",
181+
statusCode: HttpStatusCode.InternalServerError,
182+
subStatusCode: DataApiBuilderException.SubStatusCodes.UnexpectedError);
183+
}
184+
}
185+
155186
// RS1: COUNT of rows matching PK (no policy) — used to distinguish
156187
// "row doesn't exist" from "row exists but policy blocked".
157188
DbResultSet resultSetWithCountOfRowsWithGivenPk = await ExtractResultSetFromDbDataReaderAsync(dbDataReader);

‎src/Core/Resolvers/PostgresQueryBuilder.cs‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
// Copyright (c) Microsoft Corporation.
22
// Licensed under the MIT License.
33

4+
using System.Data;
45
using System.Data.Common;
56
using System.Text;
7+
using Azure.DataApiBuilder.Config.DatabasePrimitives;
68
using Azure.DataApiBuilder.Config.ObjectModel;
79
using Azure.DataApiBuilder.Core.Models;
810
using Npgsql;
@@ -19,6 +21,7 @@ public class PostgresQueryBuilder : BaseSqlQueryBuilder, IQueryBuilder
1921
private const string UPDATE_UPSERT = "updated";
2022
public const string COUNT_ROWS_WITH_GIVEN_PK = "cnt_rows_to_update";
2123
public const string IS_FALLBACK_TO_UPDATE = "is_fallback_to_update";
24+
public const string UPSERT_LOCK_ACQUIRED = "___upsert_lock_acquired___";
2225

2326
private static DbCommandBuilder _builder = new NpgsqlCommandBuilder();
2427

@@ -133,6 +136,40 @@ public string Build(SqlUpsertQueryStructure structure)
133136
string pkPredicates = Build(structure.Predicates);
134137
string isFallbackToUpdateSqlLiteral = structure.IsFallbackToUpdate ? "TRUE" : "FALSE";
135138

139+
string lockQuery = string.Empty;
140+
if (!structure.IsFallbackToUpdate)
141+
{
142+
// PostgreSQL row locks cannot protect a key that does not exist. Serialize insert-capable
143+
// upserts with a transaction-level advisory lock. Use a key-scoped resource only when every
144+
// key value is converted to a representation-stable, non-collatable CLR type. Otherwise use
145+
// a source-scoped resource because distinct request representations can compare equal under
146+
// the backing key's type or collation (for example character(n) padding or nondeterministic
147+
// collations).
148+
// Keep acquisition in its own statement so the following READ COMMITTED statement obtains
149+
// its snapshot only after a competing lock holder has committed.
150+
List<string> lockComponents = new()
151+
{
152+
$"'{EscapeSqlLiteral(structure.DatabaseObject.SchemaName)}'",
153+
$"'{EscapeSqlLiteral(structure.DatabaseObject.Name)}'"
154+
};
155+
List<string> primaryKeys = structure.PrimaryKey();
156+
157+
if (primaryKeys.All(primaryKey => IsRepresentationStableKey(structure.GetColumnDefinition(primaryKey))))
158+
{
159+
Dictionary<string, string> primaryKeyParameters = structure.Predicates.ToDictionary(
160+
predicate => predicate.Left!.AsColumn()!.ColumnName,
161+
predicate => predicate.Right.AsString()!);
162+
163+
foreach (string primaryKey in primaryKeys)
164+
{
165+
lockComponents.Add($"'{EscapeSqlLiteral(primaryKey)}'");
166+
lockComponents.Add(primaryKeyParameters[primaryKey]);
167+
}
168+
}
169+
170+
lockQuery = $"SELECT pg_advisory_xact_lock(hashtextextended(jsonb_build_array({string.Join(", ", lockComponents)})::text, 0)) AS {UPSERT_LOCK_ACQUIRED}; ";
171+
}
172+
136173
// RS1: COUNT of rows matching PK (no policy) — used to distinguish
137174
// "row doesn't exist" from "row exists but policy blocked" in the executor.
138175
string countQuery = $"SELECT COUNT(*) AS {COUNT_ROWS_WITH_GIVEN_PK}, " +
@@ -175,10 +212,32 @@ public string Build(SqlUpsertQueryStructure structure)
175212
$"SELECT {BuildListOfLabels(structure.OutputColumns)}, {UPSERT_IDENTIFIER_COLUMN_NAME} FROM update_cte UNION ALL " +
176213
$"SELECT {BuildListOfLabels(structure.OutputColumns)}, {UPSERT_IDENTIFIER_COLUMN_NAME} FROM insert_cte;";
177214

178-
return $"{countQuery}; {cteQuery}";
215+
return $"{lockQuery}{countQuery}; {cteQuery}";
179216
}
180217
}
181218

219+
/// <summary>
220+
/// Returns whether DAB converts the key to a canonical, non-collatable value before binding it.
221+
/// Keep this allowlist conservative; unknown types use the correctness-first source lock.
222+
/// </summary>
223+
private static bool IsRepresentationStableKey(ColumnDefinition columnDefinition)
224+
{
225+
if (columnDefinition.IsNullable || columnDefinition.IsArrayType)
226+
{
227+
return false;
228+
}
229+
230+
return (columnDefinition.SystemType == typeof(short) && columnDefinition.DbType == DbType.Int16) ||
231+
(columnDefinition.SystemType == typeof(int) && columnDefinition.DbType == DbType.Int32) ||
232+
(columnDefinition.SystemType == typeof(long) && columnDefinition.DbType == DbType.Int64) ||
233+
(columnDefinition.SystemType == typeof(Guid) && columnDefinition.DbType == DbType.Guid);
234+
}
235+
236+
private static string EscapeSqlLiteral(string value)
237+
{
238+
return value.Replace("'", "''", StringComparison.Ordinal);
239+
}
240+
182241
/// <summary>
183242
/// Build list of LabelledColumns as:
184243
/// "{label1}", "{label2}" ...

‎src/Core/Resolvers/Sql Query Structures/SqlUpsertQueryStructure.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,16 @@ private void PopulateColumns(
154154
// as Update request uses Where clause to target item by PK.
155155
if (primaryKeys.Contains(backingColumn!))
156156
{
157+
// A CLR string is normally sent by Npgsql as PostgreSQL text. For upsert key
158+
// predicates, that can change the backing column's equality semantics (for
159+
// example, character(n) trailing-space handling). Let PostgreSQL infer the
160+
// native parameter type from the column comparison instead.
161+
if (MetadataProvider.GetDatabaseType() is DatabaseType.PostgreSQL &&
162+
Parameters[paramIdentifier].Value is string)
163+
{
164+
Parameters[paramIdentifier].UseDatabaseTypeInference = true;
165+
}
166+
157167
PopulateColumnsAndParams(backingColumn!);
158168

159169
// PK added as predicate for Update Operation

‎src/Service.Tests/DatabaseSchema-PostgreSql.sql‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ DROP TABLE IF EXISTS foo.magazines;
2020
DROP TABLE IF EXISTS bar.magazines;
2121
DROP TABLE IF EXISTS stocks_price;
2222
DROP TABLE IF EXISTS stocks;
23+
DROP TABLE IF EXISTS fixed_width_key_upsert;
2324
DROP TABLE IF EXISTS comics;
2425
DROP TABLE IF EXISTS brokers;
2526
DROP TABLE IF EXISTS array_type_table;
@@ -137,6 +138,11 @@ CREATE TABLE stocks(
137138
PRIMARY KEY(categoryid, pieceid)
138139
);
139140

141+
CREATE TABLE fixed_width_key_upsert(
142+
id character(8) PRIMARY KEY,
143+
value int NOT NULL
144+
);
145+
140146
CREATE TABLE stocks_price(
141147
categoryid int NOT NULL,
142148
pieceid int NOT NULL,
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
using System.Threading.Tasks;
5+
using Microsoft.VisualStudio.TestTools.UnitTesting;
6+
7+
namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests
8+
{
9+
/// <summary>
10+
/// Concurrent same-key PUT/PATCH upsert coverage for SQL Server.
11+
/// </summary>
12+
[TestClass, TestCategory(TestCategory.MSSQL)]
13+
public class MsSqlUpsertConcurrencyTests : UpsertConcurrencyTestBase
14+
{
15+
[ClassInitialize]
16+
public static async Task SetupAsync(TestContext context)
17+
{
18+
DatabaseEngine = TestCategory.MSSQL;
19+
await InitializeTestFixture();
20+
}
21+
22+
protected override string GetRowCountQuery(int pieceId)
23+
{
24+
return $"SELECT COUNT(*) AS [cnt] FROM {_Composite_NonAutoGenPK_TableName} " +
25+
$"WHERE [categoryid] = 0 AND [pieceid] = {pieceId} " +
26+
"FOR JSON PATH, WITHOUT_ARRAY_WRAPPER";
27+
}
28+
}
29+
}
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
using System;
5+
using System.Collections.Generic;
6+
using System.Linq;
7+
using System.Net;
8+
using System.Net.Http;
9+
using System.Net.Http.Json;
10+
using System.Text.Json;
11+
using System.Threading.Tasks;
12+
using Azure.DataApiBuilder.Config.ObjectModel;
13+
using Azure.DataApiBuilder.Core.Authorization;
14+
using Microsoft.VisualStudio.TestTools.UnitTesting;
15+
using static Azure.DataApiBuilder.Core.AuthenticationHelpers.AppServiceAuthentication;
16+
17+
namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests
18+
{
19+
/// <summary>
20+
/// Concurrent same-key PUT/PATCH upsert coverage for PostgreSQL.
21+
/// </summary>
22+
[TestClass, TestCategory(TestCategory.POSTGRESQL)]
23+
public class PostgreSqlUpsertConcurrencyTests : UpsertConcurrencyTestBase
24+
{
25+
private const string FIXED_WIDTH_KEY_ENTITY = "FixedWidthKeyUpsert";
26+
27+
[ClassInitialize]
28+
public static async Task SetupAsync(TestContext context)
29+
{
30+
DatabaseEngine = TestCategory.POSTGRESQL;
31+
await InitializeTestFixture(
32+
customEntities: new List<string[]>
33+
{
34+
new[] { FIXED_WIDTH_KEY_ENTITY, "fixed_width_key_upsert" }
35+
});
36+
}
37+
38+
protected override string GetRowCountQuery(int pieceId)
39+
{
40+
return "SELECT json_build_object('cnt', COUNT(*)) AS data " +
41+
$"FROM {_Composite_NonAutoGenPK_TableName} " +
42+
$"WHERE categoryid = 0 AND pieceid = {pieceId}";
43+
}
44+
45+
/// <summary>
46+
/// Values with different trailing-space representations compare equal for a character(n) key and
47+
/// must therefore be serialized as the same logical key.
48+
/// </summary>
49+
[TestMethod]
50+
public async Task ConcurrentUpsertsSerializeDatabaseEqualFixedWidthKeys()
51+
{
52+
for (int iteration = 0; iteration < 8; iteration++)
53+
{
54+
string key = $"K{iteration:D3}";
55+
string[] databaseEqualKeys = { key, key + " ", key + " ", key + " " };
56+
Task<HttpResponseMessage>[] requests = databaseEqualKeys
57+
.Select((databaseEqualKey, index) => SendFixedWidthKeyUpsertAsync(databaseEqualKey, index + 1))
58+
.ToArray();
59+
60+
HttpResponseMessage[] responses = await Task.WhenAll(requests);
61+
try
62+
{
63+
foreach (HttpResponseMessage response in responses)
64+
{
65+
string responseBody = await response.Content.ReadAsStringAsync();
66+
Assert.IsTrue(
67+
response.StatusCode is HttpStatusCode.OK or HttpStatusCode.Created,
68+
$"Fixed-width key upsert failed with {(int)response.StatusCode} " +
69+
$"({response.StatusCode}). Body: {responseBody}");
70+
}
71+
72+
Assert.AreEqual(1, responses.Count(response => response.StatusCode == HttpStatusCode.Created));
73+
Assert.AreEqual(databaseEqualKeys.Length - 1, responses.Count(response => response.StatusCode == HttpStatusCode.OK));
74+
75+
string rowCountJson = await GetDatabaseResultAsync(
76+
$"SELECT json_build_object('cnt', COUNT(*)) AS data FROM fixed_width_key_upsert WHERE id = '{key}'");
77+
using JsonDocument rowCountDocument = JsonDocument.Parse(rowCountJson);
78+
Assert.AreEqual(1, rowCountDocument.RootElement.GetProperty("cnt").GetInt32());
79+
}
80+
finally
81+
{
82+
foreach (HttpResponseMessage response in responses)
83+
{
84+
response.Dispose();
85+
}
86+
}
87+
}
88+
}
89+
90+
private static Task<HttpResponseMessage> SendFixedWidthKeyUpsertAsync(string key, int value)
91+
{
92+
HttpRequestMessage request = new(
93+
HttpMethod.Put,
94+
$"api/{FIXED_WIDTH_KEY_ENTITY}/id/{Uri.EscapeDataString(key)}")
95+
{
96+
Content = JsonContent.Create(new Dictionary<string, object> { { "value", value } })
97+
};
98+
99+
request.Headers.Add(
100+
AuthenticationOptions.CLIENT_PRINCIPAL_HEADER,
101+
AuthTestHelper.CreateAppServiceEasyAuthToken(
102+
roleClaimType: AuthenticationOptions.ROLE_CLAIM_TYPE,
103+
additionalClaims: new List<AppServiceClaim>
104+
{
105+
new() { Typ = AuthenticationOptions.ROLE_CLAIM_TYPE, Val = "authenticated" }
106+
}));
107+
request.Headers.Add(AuthorizationResolver.CLIENT_ROLE_HEADER, "authenticated");
108+
109+
return HttpClient.SendAsync(request);
110+
}
111+
}
112+
}

0 commit comments

Comments
 (0)