Skip to content

Commit

Permalink
Incorrect NOLOCK position in queries where there is no table alias (#…
Browse files Browse the repository at this point in the history
…8783)

"WITH(NOLOCK)" is positioned before the where clause if there is no alias for the table.
  • Loading branch information
AndreaPiovanelli authored Apr 11, 2024
1 parent 441c6da commit e243e8e
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/Orchard/Data/NoLockInterceptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -203,7 +203,7 @@ public CaptureWrapper(Capture source, IEnumerable<string> tableNames) {
public bool IsAltered { get; set; }

public void AddNoLockHints() {
Value = AddNoLockHints(Value, TableNames);
Value = AddNoLockHints(Value, TableNames);
}

private string AddNoLockHints(string query, IEnumerable<string> tableNames) {
Expand Down Expand Up @@ -240,13 +240,19 @@ private string AddNoLockHints(string query, IEnumerable<string> 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)) {
Expand Down

0 comments on commit e243e8e

Please sign in to comment.