From e243e8e547c0618005fd8cf71f0dc25d0d13b430 Mon Sep 17 00:00:00 2001 From: Andrea Piovanelli <83577153+AndreaPiovanelli@users.noreply.github.com> Date: Thu, 11 Apr 2024 20:27:03 +0200 Subject: [PATCH] Incorrect NOLOCK position in queries where there is no table alias (#8783) "WITH(NOLOCK)" is positioned before the where clause if there is no alias for the table. --- src/Orchard/Data/NoLockInterceptor.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/Orchard/Data/NoLockInterceptor.cs b/src/Orchard/Data/NoLockInterceptor.cs index 91da20f2c31..d06873b30ac 100644 --- a/src/Orchard/Data/NoLockInterceptor.cs +++ b/src/Orchard/Data/NoLockInterceptor.cs @@ -42,7 +42,7 @@ private string GetPrefixedTableName(string tableName) { return _shellSettings.DataTablePrefix + "_" + tableName; } - + // based on https://stackoverflow.com/a/39518098/2669614 public override SqlString OnPrepareStatement(SqlString sql) { // only work on select queries @@ -167,7 +167,7 @@ public override SqlString OnPrepareStatement(SqlString sql) { } } // rebuild query - for(int i = 0; i < affectedCaptures.Count; i++) { + for (int i = 0; i < affectedCaptures.Count; i++) { var inner = affectedCaptures[i]; for (int j = i + 1; j < affectedCaptures.Count; j++) { var outer = affectedCaptures[j]; @@ -203,7 +203,7 @@ public CaptureWrapper(Capture source, IEnumerable tableNames) { public bool IsAltered { get; set; } public void AddNoLockHints() { - Value = AddNoLockHints(Value, TableNames); + Value = AddNoLockHints(Value, TableNames); } private string AddNoLockHints(string query, IEnumerable tableNames) { @@ -240,13 +240,19 @@ private string AddNoLockHints(string query, IEnumerable tableNames) { if (tableIndex == fromIndex + 1 || parts[tableIndex - 1].Equals(",")) { - parts.Insert(tableIndex + 2, "WITH(NOLOCK)"); + if (parts[tableIndex + 1].Equals("where", StringComparison.OrdinalIgnoreCase)) { + // There is no alias in the query, so we add "WITH(NOLOCK)" immediately after table name but before the "where" clause. + parts.Insert(tableIndex + 1, "WITH(NOLOCK)"); + } else { + // We add "WITH(NOLOCK)" after the table alias. + parts.Insert(tableIndex + 2, "WITH(NOLOCK)"); + } } else { // probably doing a join, so edit the next "on" and make it // "WITH (NOLOCK) on" for (int i = tableIndex + 1; i < whereIndex; i++) { if (parts[i].Trim().Equals("WITH(NOLOCK)", StringComparison.OrdinalIgnoreCase)) { - // we processed this table anme already + // we processed this table name already. break; } if (parts[i].Trim().Equals("on", StringComparison.OrdinalIgnoreCase)) {