【发布时间】:2010-09-18 18:09:18
【问题描述】:
我有一些代码需要在插入数据库之前确保某些数据在 mysql 枚举中。我发现这样做的最干净的方法是以下代码:
sub enum_values {
my ( $self, $schema, $table, $column ) = @_;
# don't eval to let the error bubble up
my $columns = $schema->storage->dbh->selectrow_hashref(
"SHOW COLUMNS FROM `$table` like ?",
{},
$column
);
unless ($columns) {
X::Internal::Database::UnknownColumn->throw(
column => $column,
table => $table,
);
}
my $type = $columns->{Type} or X::Panic->throw(
details => "Could not determine type for $table.$column",
);
unless ( $type =~ /\Aenum\((.*)\)\z/ ) {
X::Internal::Database::IncorrectTypeForColumn->throw(
type_wanted => 'enum',
type_found => $type,
);
}
$type = $1;
require Text::CSV_XS;
my $csv = Text::CSV_XS->new;
$csv->parse($type) or X::Panic->throw(
details => "Could not parse enum CSV data: ".$csv->error_input,
);
return map { /\A'(.*)'\z/; $1 }$csv->fields;
}
我们正在使用DBIx::Class。当然有更好的方法来实现这一点吗? (请注意,$table 变量来自我们的代码,不是来自任何外部来源。因此,没有安全问题。
【问题讨论】:
标签: mysql perl enums dbix-class