【问题标题】:How to call Postgres function in DBIx::Class如何在 DBIx::Class 中调用 Postgres 函数
【发布时间】:2015-04-26 12:04:19
【问题描述】:

我目前正在使用DBIx::Class,我想知道如何使用 DBIx 在某个数据库模式中调用现有的 Postgres 函数。

我的 DBI 代码:

my $table = $self->{dbh}->quote_identifier(
                    undef,
                    'foo',
                    'myFunction'
                    );

my $sqlst = qq{ SELECT foobar FROM $table($some_data); };

到目前为止,我发现的事情是使用从我的 DBIx::Class::Schema 对象中检索到的 dbh 对象来调用所述函数:

my $return_data = {};

my $sql = qq{SELECT foobar FROM "foo"."myFunction"($some_data)};

$self->{schema}->storage->dbh_do( sub {
    my ($storage, $dbh) = @_;
    $menu_list = $dbh->selectrow_hashref(
        $sql,
        { slice => {} }
    );
});

还有比这更好/更简单的解决方案吗?

我也偶然发现了DBIx::ProcedureCall,但在使用数据库架构时我无法让它工作。

非常感谢任何帮助!

【问题讨论】:

    标签: perl postgresql dbix-class


    【解决方案1】:

    如果你想使用SQL Functions as Table Sources,应该可以像这样创建一个虚拟的DBIx::Class::ResultSource::View:

    package MyApp::Schema::Result::MyFunction;
    
    use base qw/DBIx::Class::Core/;
    
    __PACKAGE__->table_class('DBIx::Class::ResultSource::View');
    
    __PACKAGE__->table('myFunction');
    __PACKAGE__->result_source_instance->is_virtual(1);
    __PACKAGE__->result_source_instance->view_definition(
        'SELECT foobar FROM "foo"."myFunction"(?)'
    );
    __PACKAGE__->add_columns(
        'foobar' => {
            data_type => 'varchar',
        },
    );
    

    视图可以这样使用:

    my $rs = $schema->resultset('MyFunction')->select({}, {
        bind => [ 'arg' ],
    });
    

    这将创建一个不必要的子查询:

    SELECT me.foobar FROM (SELECT foobar FROM "foo"."myFunction"(?)) me
    

    但我认为它应该有效。

    【讨论】:

    • 我有点希望有一种更短的方法来调用 DB 函数,而不是为每个函数创建视图 ;-) 但我想我现在会这样做。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2010-12-18
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2016-08-25
    • 1970-01-01
    • 2011-05-26
    相关资源
    最近更新 更多