在没有execute()的情况下创建sqlite dbs

时间:2011-12-08 22:51:47

标签: ruby-on-rails ruby-on-rails-3 sqlite

我有一个像这样的控制器:

def download_link
  #It starts a background process to handle all these things
  temp_file = Tempfile.new 'temp_file'
  temp_sqlite_db = SQLite3::Database.new temp_file.path

  temp_sqlite_db.execute("CREATE TABLE inspection (id INTEGER NOT NULL,desc VARCHAR(255));")
  inspections = Inspection.a_heavy_query_that_doesnt_worths_to_wait_so_much_for_a_reply
  # Some code inserting records and creating tables, with execute() too 
  # more code, compressing the db and sending an email with a download link to the zip file
end

现在,我想知道是否有办法替换execute()函数,并可能创建表并保存像inspection.create(something)这样的记录。提前致谢

1 个答案:

答案 0 :(得分:0)

如果有人需要类似的东西,那就是我的实施:

# config/initializers/sql_returner.rb
module ActiveRecord
  class Base

    def sql_insert
      if attributes_with_quotes.empty?
        connection.empty_insert_statement(self.class.table_name)
      else
        "INSERT INTO #{self.class.quoted_table_name} " +
        "(#{quoted_column_names.join(', ')}) " +
        "VALUES(#{attributes_with_quotes.values.join(', ')});"
      end
    end

    def self.sql_create
      "CREATE TABLE #{table_name} (" +
      " #{ self.columns.collect{ |column|
        column_sql = " #{ column.name }  #{ sql_type column } "
        column_sql << " PRIMARY KEY " if column.primary
        column_sql << " NOT NULL " unless column.null
        column_sql
      }.join(', ') } );"
    end

    private

    def self.sql_type column
      case column.type
      when 'datetime', 'string'
        'TEXT'
      else
        column.type.to_s
      end
    end

  end
end

然后,如果我需要创建表并插入记录,以问题的相同代码为例,我必须运行:

def download_link
  temp_file = Tempfile.new 'temp_file'
  temp_sqlite_db = SQLite3::Database.new temp_file.path

  temp_sqlite_db.execute(Inspection.sql_create)
  inspections = Inspection.a_heavy_query_that_doesnt_worths_to_wait_so_much_for_a_reply
  insert = ""
  inspections.each{ |insp|
    insert << insp.return_insert_sql
  }
  #.....
end

对于第一种方法sql_insert,我以ActiveRecord的create method代码为例。我知道也许有些小猫死了编码这个实现,但至少对我来说它是有效的。