【问题标题】:How to create CSV/Excel of schema.rb file如何创建 schema.rb 文件的 CSV/Excel
【发布时间】:2019-08-01 21:27:08
【问题描述】:

我想从 db/schema.rb 文件创建一个 CSV/Excel 文件。我可以将表名及其属性名转储到文件中,但我也想转储其他信息,例如索引和列约束等。

这是我的代码

require 'write_xlsx'
Rails.application.eager_load!
# Create a new Excel workbook
workbook = WriteXLSX.new('schema.xlsx')

# Add a worksheet
worksheet = workbook.add_worksheet

# Add and define a format
format = workbook.add_format # Add a format
format.set_bold
format.set_color('red')
format.set_align('center')

# Write a formatted and unformatted string, row and column notation.
col = row = 0
worksheet.write(0, 0, 'Table Name')
worksheet.write(0, 1, 'Attributes')
worksheet.write(0, 2, 'Attribute Type')
worksheet.write(0, 3, 'Attribute constraints')
worksheet.write(0, 4, 'Comments')
ApplicationRecord.descendants.each_with_index do |model, _index|
  row += 1
  worksheet.write(row, 0, model.name)
  worksheet.write(row, 1, '')
  model.attribute_types.each_pair do |attribute, attribute_type|
    row += 1
    worksheet.write(row, 1, attribute)
    worksheet.write(row, 2, attribute_type.type)
    worksheet.write(row, 3, JSON.parse(attribute_type.to_json))
  end
end

workbook.close

我也从 PG 管理员那里尝试过,但得到了预期的结果。

COPY (select * from information_schema.columns) TO '/home/sachin/ruby/profile_service/columns.csv' with delimiter ',' csv header;

【问题讨论】:

  • 您需要程序化解决方案吗?如果没有,您可以使用 Postico 之类的工具运行查询 select * from information_schema.columns,然后将结果导出为 CSV。
  • @aridlehoover 是的,我需要一个程序化解决方案。这将显示约束和索引以及表的列。
  • 我强烈建议您熟悉 ActiveRecord::SchemaDumper。 github.com/rails/rails/blob/master/activerecord/lib/…

标签: ruby-on-rails ruby excel csv schema


【解决方案1】:

我不知道您是否可以使用简单的“export_to_csv”方法,但如果您想扩展通过 ActiveRecord 收集所有数据库信息的方法,而不是我认为在 schema_dumper.rb 中的方法,您会找到所需的一切。只需按照SchemaDumper#dump 收集所有信息的方式即可。

您可以使用

获取SchemaDumper 对象
connection = ApplicationRecord.connection
dumper = connection.create_schema_dumper({})

获取表的索引信息的方法似乎是:

table = connection.tables.first
connection.indexes(table)

SchemaDumper.column_spec 可能对您的用例也有用:

column = connection.columns(table).first
dumper.send(:column_spec, column) # => [:integer, {:null=>"false", :auto_increment=>"true"}]

【讨论】:

    猜你喜欢
    • 2011-01-26
    • 1970-01-01
    • 2011-09-24
    • 2012-11-02
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    相关资源
    最近更新 更多