1

我有一个关于 Rails 3.0.2 的项目。它相当大并且与 MySQL 数据库配合得很好。但是当我尝试使用 SQLite 数据库运行它时,迁移过程中出现错误:

SQLite3::SQLException: near "CASCADE": syntax error: DROP TABLE "table_name" CASCADE

我搜索并发现可能'PRAGMA foreign_keys = ON'对 SQLite 会有所帮助。所以我之前尝试过添加'execute("PRAGMA foreign_keys = ON")'迁移,'DROP TABLE table_name'但这没有帮助。

如何在 Rails3 中为 SQLite 打开 foreign_keys?

宝石版本

  • sqlite3 (1.3.6)
  • sqlite3-ruby (1.3.3)
4

1 回答 1

0

Here's the syntax diagram for SQLite's DROP TABLE:

enter image description here

In case the image moves, the syntax is like this:

drop table if exists db_name.table_name

where the if exists and db_name. parts are optional. There is no CASCADE in there so SQLite simply doesn't support CASCADE when using DROP TABLE and there's nothing you can do to add it (unless, of course, you want to hack the SQLite C source and add it yourself). You have to accept certain limitations when using SQLite, this is one of them.

If you want to use one migration for both SQLite and MySQL then you'll have to check which database is being used and execute the appropriate SQL or find something that works everywhere (i.e. perform the CASCADE by hand). The easy way to check which database you're using that I can think of right now would be:

case connection
when ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
    # PostgreSQL things go here
when ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
    # MySQL things go here
when ActiveRecord::ConnectionAdapters::SQLiteAdapter
    # SQLite things go here
...
end
于 2012-06-03T18:47:29.300 回答