mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Fix create_table
with query from relation
If a relation has binds, `connection.to_sql(relation)` without binds will generate invalid SQL. It should use `relation.to_sql` in that case.
This commit is contained in:
parent
42a8072193
commit
7dbe62006d
2 changed files with 10 additions and 7 deletions
|
@ -55,7 +55,7 @@ module ActiveRecord
|
|||
|
||||
create_sql << "(#{statements.join(', ')})" if statements.present?
|
||||
add_table_options!(create_sql, table_options(o))
|
||||
create_sql << " AS #{@conn.to_sql(o.as)}" if o.as
|
||||
create_sql << " AS #{to_sql(o.as)}" if o.as
|
||||
create_sql
|
||||
end
|
||||
|
||||
|
@ -114,6 +114,11 @@ module ActiveRecord
|
|||
sql
|
||||
end
|
||||
|
||||
def to_sql(sql)
|
||||
sql = sql.to_sql if sql.respond_to?(:to_sql)
|
||||
sql
|
||||
end
|
||||
|
||||
def foreign_key_in_create(from_table, to_table, options)
|
||||
options = foreign_key_options(from_table, to_table, options)
|
||||
accept ForeignKeyDefinition.new(from_table, to_table, options)
|
||||
|
|
|
@ -502,11 +502,10 @@ class MigrationTest < ActiveRecord::TestCase
|
|||
|
||||
unless mysql_enforcing_gtid_consistency?
|
||||
def test_create_table_with_query
|
||||
Person.connection.create_table(:person, force: true)
|
||||
|
||||
Person.connection.create_table :table_from_query_testings, as: "SELECT id FROM person"
|
||||
Person.connection.create_table :table_from_query_testings, as: "SELECT id FROM people WHERE id = 1"
|
||||
|
||||
columns = Person.connection.columns(:table_from_query_testings)
|
||||
assert_equal [1], Person.connection.select_values("SELECT * FROM table_from_query_testings")
|
||||
assert_equal 1, columns.length
|
||||
assert_equal "id", columns.first.name
|
||||
ensure
|
||||
|
@ -514,11 +513,10 @@ class MigrationTest < ActiveRecord::TestCase
|
|||
end
|
||||
|
||||
def test_create_table_with_query_from_relation
|
||||
Person.connection.create_table(:person, force: true)
|
||||
|
||||
Person.connection.create_table :table_from_query_testings, as: Person.select(:id)
|
||||
Person.connection.create_table :table_from_query_testings, as: Person.select(:id).where(id: 1)
|
||||
|
||||
columns = Person.connection.columns(:table_from_query_testings)
|
||||
assert_equal [1], Person.connection.select_values("SELECT * FROM table_from_query_testings")
|
||||
assert_equal 1, columns.length
|
||||
assert_equal "id", columns.first.name
|
||||
ensure
|
||||
|
|
Loading…
Reference in a new issue