我正在尝试创建一个 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