如何在附加的sqlite数据库中创建外键?

时间:2011-07-15 05:49:53

标签: perl sqlite dbix-class

我正在尝试创建一个sqlite3数据库作为模仿生产环境的测试环境。由于生产设置方式,表格采用多种模式。

我在DBIx :: Class中设置了类,使用$schema->storage->dbh_do将数据库附加到模式,并使用$schema-deploy()创建数据库。

但是,当在第二个表上创建外键时,我收到以下错误:

DBIx::Class::Schema::deploy(): DBIx::Class::Schema::deploy(): DBI Exception: DBD::SQLite::db do failed: near ".": syntax error 

DBIx::Class最简单的测试复制如下:

sqlite3 initial.db
SQLite version 3.6.23
Enter ".help" for instructions
Enter SQL statements terminated with a ";"   
sqlite> attach database 'other.db' as 'other';
sqlite> create table other.a( col1_a, col2_a);
sqlite> create table other.b( col1_b, col2_b, foreign key(col1_b) references other.a(col1_a));
Error: near ".": syntax error
sqlite> create table other.b( col1_b, col2_b, foreign key(col1_b) references a(col1_a));
sqlite> 

从外键子句中删除模式将成功创建表。

如何使用DBIx :: Class创建外部模式中的表?

编辑:代码的完整示例。

package MyApp::Schema;
use base qw/DBIx::Class::Schema/;
__PACKAGE__->load_namespaces();
1;


package MyApp::Schema::Result::A;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('other_db.A');
__PACKAGE__->add_columns(qw/ a1 a2 /);
__PACKAGE__->set_primary_key('a1');
__PACKAGE__->has_many(bs => 'MyApp::Schema::Result::B', 'b1');
1;

package MyApp::Schema::Result::B;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('other_db.B');
__PACKAGE__->add_columns(qw/ b1 b2 /);
__PACKAGE__->set_primary_key('b1');
__PACKAGE__->belongs_to(a => 'MyApp::Schema::Result::A', 'b1');
1;

主要剧本:

use MyApp::Schema;

my $schema = MyApp::Schema->connect('dbi:SQLite:dbname=test.db','','',{});

my $res = $schema->storage->dbh_do(
    sub {
        my ($storage, $dbh) = @_;
        $dbh->do("attach database 'other.db' as other_db");
    }
);

$schema->deploy();

给出的错误是:

DBIx::Class::Schema::deploy(): DBIx::Class::Schema::deploy(): DBI Exception: DBD::SQLite::db do failed: near ".": syntax error [for Statement "CREATE TABLE other_db.B (
  b1  NOT NULL,
  b2  NOT NULL,
  PRIMARY KEY (b1),
  FOREIGN KEY(b1) REFERENCES other_db.A(a1)
)"] at dbi.pl line 17
 (running "CREATE TABLE other_db.B (
  b1  NOT NULL,
  b2  NOT NULL,
  PRIMARY KEY (b1),
  FOREIGN KEY(b1) REFERENCES other_db.A(a1)
)") at dbi.pl line 17

1 个答案:

答案 0 :(得分:2)

简单的答案是,在外键定义中使用表名时,您不能(也不需要)指定数据库名称。 sqlite文档表明它是这样的。

此链接显示如何在“create table db.table”部分中使用具有新表名的数据库名称:

http://www.sqlite.org/lang_createtable.html

此链接显示了如何在外键定义中使用数据库名称:

http://www.sqlite.org/syntaxdiagrams.html#foreign-key-clause