Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The SQLite3 adapter now implements the supports_deferrable_constraints? contract #49376

Merged
merged 1 commit into from
Oct 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
* The SQLite3 adapter now implements the `supports_deferrable_constraints?` contract

Allows foreign keys to be deferred by adding the `:deferrable` key to the `foreign_key` options.

```ruby
add_reference :person, :alias, foreign_key: { deferrable: :deferred }
add_reference :alias, :person, foreign_key: { deferrable: :deferred }
```

*Stephen Margheim*

* Add `set_constraints` helper for PostgreSQL

```ruby
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ module ConnectionAdapters
module SQLite3
class SchemaCreation < SchemaCreation # :nodoc:
private
def visit_AddForeignKey(o)
super.dup.tap do |sql|
sql << " DEFERRABLE INITIALLY #{o.options[:deferrable].to_s.upcase}" if o.deferrable
end
end

def visit_ForeignKeyDefinition(o)
super.dup.tap do |sql|
sql << " DEFERRABLE INITIALLY #{o.deferrable.to_s.upcase}" if o.deferrable
end
end

def supports_index_using?
false
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ def indexes(table_name)
end

def add_foreign_key(from_table, to_table, **options)
if options[:deferrable] == true
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rails main branch version is already 7.2.0.alpha, I'd like to keep this deprecation message as the PostgreSQL adapter does.

ActiveRecord.deprecator.warn(<<~MSG)
`deferrable: true` is deprecated in favor of `deferrable: :immediate`, and will be removed in Rails 7.2.
MSG

ActiveRecord.deprecator.warn(<<~MSG)
`deferrable: true` is deprecated in favor of `deferrable: :immediate`, and will be removed in Rails 7.2.
MSG

options[:deferrable] = :immediate
end

assert_valid_deferrable(options[:deferrable])

alter_table(from_table) do |definition|
to_table = strip_table_name_prefix_and_suffix(to_table)
definition.foreign_key(to_table, **options)
Expand Down Expand Up @@ -185,6 +195,12 @@ def quoted_scope(name = nil, type: nil)
scope[:type] = type if type
scope
end

def assert_valid_deferrable(deferrable)
return if !deferrable || %i(immediate deferred).include?(deferrable)

raise ArgumentError, "deferrable must be `:immediate` or `:deferred`, got: `#{deferrable.inspect}`"
end
end
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,10 @@ def supports_lazy_transactions?
true
end

def supports_deferrable_constraints?
true
end

# REFERENTIAL INTEGRITY ====================================

def disable_referential_integrity # :nodoc:
Expand Down Expand Up @@ -367,15 +371,31 @@ def add_reference(table_name, ref_name, **options) # :nodoc:
end
alias :add_belongs_to :add_reference

FK_REGEX = /.*FOREIGN KEY\s+\("(\w+)"\)\s+REFERENCES\s+"(\w+)"\s+\("(\w+)"\)/
DEFERRABLE_REGEX = /DEFERRABLE INITIALLY (\w+)/
def foreign_keys(table_name)
# SQLite returns 1 row for each column of composite foreign keys.
fk_info = internal_exec_query("PRAGMA foreign_key_list(#{quote(table_name)})", "SCHEMA")
# Deferred or immediate foreign keys can only be seen in the CREATE TABLE sql
fk_defs = table_structure_sql(table_name)
.select do |column_string|
column_string.start_with?("CONSTRAINT") &&
column_string.include?("FOREIGN KEY")
end
.to_h do |fk_string|
_, from, table, to = fk_string.match(FK_REGEX).to_a
_, mode = fk_string.match(DEFERRABLE_REGEX).to_a
deferred = mode&.downcase&.to_sym || false
[[table, from, to], deferred]
end

grouped_fk = fk_info.group_by { |row| row["id"] }.values.each { |group| group.sort_by! { |row| row["seq"] } }
grouped_fk.map do |group|
row = group.first
options = {
on_delete: extract_foreign_key_action(row["on_delete"]),
on_update: extract_foreign_key_action(row["on_update"])
on_update: extract_foreign_key_action(row["on_update"]),
deferrable: fk_defs[[row["table"], row["from"], row["to"]]]
}

if group.one?
Expand Down Expand Up @@ -649,24 +669,11 @@ def translate_exception(exception, message:, sql:, binds:)
def table_structure_with_collation(table_name, basic_structure)
collation_hash = {}
auto_increments = {}
sql = <<~SQL
SELECT sql FROM
(SELECT * FROM sqlite_master UNION ALL
SELECT * FROM sqlite_temp_master)
WHERE type = 'table' AND name = #{quote(table_name)}
SQL

# Result will have following sample string
# CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
# "password_digest" varchar COLLATE "NOCASE");
result = query_value(sql, "SCHEMA")

if result
# Splitting with left parentheses and discarding the first part will return all
# columns separated with comma(,).
columns_string = result.split("(", 2).last
column_strings = table_structure_sql(table_name)

columns_string.split(",").each do |column_string|
if column_strings.any?
column_strings.each do |column_string|
# This regex will match the column name and collation type and will save
# the value in $1 and $2 respectively.
collation_hash[$1] = $2 if COLLATE_REGEX =~ column_string
Expand All @@ -691,6 +698,28 @@ def table_structure_with_collation(table_name, basic_structure)
end
end

def table_structure_sql(table_name)
sql = <<~SQL
SELECT sql FROM
(SELECT * FROM sqlite_master UNION ALL
SELECT * FROM sqlite_temp_master)
WHERE type = 'table' AND name = #{quote(table_name)}
SQL

# Result will have following sample string
# CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
# "password_digest" varchar COLLATE "NOCASE");
result = query_value(sql, "SCHEMA")

return [] unless result

# Splitting with left parentheses and discarding the first part will return all
# columns separated with comma(,).
columns_string = result.split("(", 2).last

columns_string.split(",").map(&:strip)
end

def arel_visitor
Arel::Visitors::SQLite.new(self)
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class ReferencesForeignKeyInCreateTest < ActiveRecord::TestCase
fks.map { |fk| [fk.from_table, fk.to_table, fk.column] })
end

if current_adapter?(:PostgreSQLAdapter)
if ActiveRecord::Base.connection.supports_deferrable_constraints?
test "deferrable: false option can be passed" do
@connection.create_table :testings do |t|
t.references :testing_parent, foreign_key: { deferrable: false }
Expand Down