Skip to content

Commit

Permalink
more descriptive nested lock error message
Browse files Browse the repository at this point in the history
Co-authored-by: Ryan Krage <[email protected]>
  • Loading branch information
rkrage and Ryan Krage committed Sep 8, 2023
1 parent 0149c4f commit 7144675
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
10 changes: 6 additions & 4 deletions lib/pg_ha_migrations/safe_statements.rb
Original file line number Diff line number Diff line change
Expand Up @@ -606,17 +606,19 @@ def safely_acquire_lock_for_table(table, &block)
_check_postgres_adapter!

schema, table = _schema_and_table_for(table)
fully_qualified_table = "#{connection.quote_schema_name(schema)}.#{connection.quote_table_name(table)}"

# Disallow nested locks unless targeting the same table
if nested_lock && Thread.current[__method__] != "#{schema}_#{table}"
raise PgHaMigrations::InvalidMigrationError, "Nested lock detected!"
if nested_lock && Thread.current[__method__] != fully_qualified_table
raise PgHaMigrations::InvalidMigrationError, "Nested lock detected! Cannot acquire lock on #{fully_qualified_table} while #{Thread.current[__method__]} is locked."
else
Thread.current[__method__] = "#{schema}_#{table}"
Thread.current[__method__] = fully_qualified_table
end

fully_qualified_table = "#{connection.quote_schema_name(schema)}.#{connection.quote_table_name(table)}"
target_schemas_and_tables = [[schema, table]]

# Locking a partitioned table will also lock child tables (including sub-partitions),
# so we need to check for blocking queries on those tables as well
if _partitioned_table?(schema, table)
target_schemas_and_tables.concat(_partitions_for_table(schema, table, include_sub_partitions: true))
end
Expand Down
10 changes: 8 additions & 2 deletions spec/safe_statements_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3698,11 +3698,17 @@ def up
# thread variable doesn't incorrectly get reset
expect do
migration.safely_acquire_lock_for_table("foo")
end.to raise_error(PgHaMigrations::InvalidMigrationError, "Nested lock detected!")
end.to raise_error(
PgHaMigrations::InvalidMigrationError,
"Nested lock detected! Cannot acquire lock on \"public\".\"foo\" while \"public\".\"bogus_table\" is locked."
)

migration.safely_acquire_lock_for_table("foo")
end
end.to raise_error(PgHaMigrations::InvalidMigrationError, "Nested lock detected!")
end.to raise_error(
PgHaMigrations::InvalidMigrationError,
"Nested lock detected! Cannot acquire lock on \"public\".\"foo\" while \"public\".\"bogus_table\" is locked."
)

expect(locks_for_table(table_name, connection: alternate_connection)).to be_empty
end
Expand Down

0 comments on commit 7144675

Please sign in to comment.