Perl 使用DBIx::Class,如何检查表是否存在?
我的目标是创建一个函数,该函数将创建我的MySQL db表(已经使用通过DBIx::Class定义的模式),如果它还没有创建的话。否则,它只会创建对$schema的引用 目前,我了解如何使用以下代码创建不存在的表:Perl 使用DBIx::Class,如何检查表是否存在?,perl,dbix-class,Perl,Dbix Class,我的目标是创建一个函数,该函数将创建我的MySQL db表(已经使用通过DBIx::Class定义的模式),如果它还没有创建的话。否则,它只会创建对$schema的引用 目前,我了解如何使用以下代码创建不存在的表: my $schema = MyApp::Schema->connect( $dsn, $user, $password, ); $schema->deploy( { add_drop_table => 1 } ); 我需要添加更多的逻辑,这样
my $schema = MyApp::Schema->connect(
$dsn,
$user,
$password,
);
$schema->deploy( { add_drop_table => 1 } );
我需要添加更多的逻辑,这样它就不会试图添加已经存在的表。如果每次都要创建表,可以在create table语句中使用“Drop table if exists”。如果您不想弄乱数据,那么您可以始终执行“显示表”并解析结果,例如
my $tables = $dbh->selectall_arrayref(qq|Show tables|) or die "Can't show tables " . $dbh->errstr();
if (@$tables) {
foreach my $table (@$tables) {
if ($table->[0] eq 'sometablename') {
# Table sometablename exists
}
}
}
这可能不是最便宜的检查(特别是对于某些DBs),但对于DBIC来说有点惯用
my $schema = MySchema->connect(...);
for my $source_name ( $schema->sources )
{
eval { $schema->resultset($source_name)->count };
print $source_name, " is ", $@ ? "missing? $@" : "OK\n";
}
更新,这有点笨拙(根据您的喜好重新整理行/单个/首先/全部),但它的优点是相当便宜
eval {
$schema->resultset($source_name)
->search({},
{ where => \q{ 1 = 0 },
rows => 1 })
->single;
};
最后我这样做了,$schema是一个全局变量由于使用了,此解决方案仅适用于MySQL(据我所知) 我这样称呼它:
$schema = MyApp::Schema->connect(
$dsn,
$user,
$password,
);
my $table_exists = tableExists("mytable");
if ( !defined $table_exists ) {
print "Deploying schema...", $/;
$schema->deploy();
print "Done", $/;
}
和
$schema = MyApp::Schema->connect(
$dsn,
$user,
$password,
);
my $table_exists = tableExists("mytable");
if ( !defined $table_exists ) {
print "Deploying schema...", $/;
$schema->deploy();
print "Done", $/;
}