instance method table_structure_sql

Ruby on Rails 8.0.4

Since v7.2.3 Private

Available in: v7.2.3 v8.0.4 v8.1.2

Signature

table_structure_sql(table_name, column_names = nil)

No documentation comment.

Parameters

table_name req
column_names opt = nil
Source
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 757
        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})"))/i)
                .map(&:strip)
        end

Defined in activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb line 757 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::ConnectionAdapters::SQLite3Adapter

Type at least 2 characters to search.

↑↓ navigate · open · esc close