method
table_structure_sql
v7.2.3 -
Show latest stable
- Class:
ActiveRecord::ConnectionAdapters::SQLite3Adapter
table_structure_sql(table_name, column_names = nil)private
No documentation available.
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 719
def table_structure_sql(table_name, column_names = nil)
unless column_names
column_info = table_info(table_name)
column_names = column_info.map { |column| column["name"] }
end
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",
# "o_id" integer,
# CONSTRAINT "fk_rails_78146ddd2e" FOREIGN KEY ("o_id") REFERENCES "os" ("id"));
result = query_value(sql, "SCHEMA")
return [] unless result
# Splitting with left parentheses and discarding the first part will return all
# columns separated with comma(,).
result.partition(UNQUOTED_OPEN_PARENS_REGEX)
.last
.sub(FINAL_CLOSE_PARENS_REGEX, "")
# column definitions can have a comma in them, so split on commas followed
# by a space and a column name in quotes or followed by the keyword CONSTRAINT
.split(/,(?=\s(?:CONSTRAINT|"(?:#{Regexp.union(column_names).source})"))/)
.map(&:strip)
end