11// Copyright (c) Microsoft Corporation.
22// Licensed under the MIT License.
33
4+ using System . Data ;
45using System . Data . Common ;
56using System . Text ;
7+ using Azure . DataApiBuilder . Config . DatabasePrimitives ;
68using Azure . DataApiBuilder . Config . ObjectModel ;
79using Azure . DataApiBuilder . Core . Models ;
810using 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}" ...
0 commit comments