The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


SQL::Stash - A stash for SQL queries


        package SQL::Stash::Foo;
        use base qw(SQL::Stash);
        __PACKAGE__->stash('select_foo', 'SELECT * FROM Foo');

        package main;
        my $dbh = DBI->connect('dbi:SQLite:dbname=:memory:', '', '');
        my $stash = SQL::Stash::Foo->new();
        my $sth = $stash->retrieve('select_foo');
        while(my $row = $sth->fetchrow_arrayref()) {
                print("$_\n") for @$row;


SQL::Stash is a simple query library for SQL statements. SQL statements are populated at the class level. SQL::Stash objects prepare these statements as late as possible (i.e. before they are executed).

SQL::Stash is in concept very similar to Ima::DBI, but differs by having instance-specific database handles and statements, and by supporting externally defined database handles.




Designated constructor. Instantiates a new SQL::Stash object. The dbh argument, a DBI-like object, must be provided.

        my $dbh = DBI->connect('dbi:SQLite:dbname=:memory:', '', '');
        my $stash = SQL::Stash->new('dbh' => $dbh);


        SQL::Stash::Foo->stash($name, $statement, $should_cache);
        $stash->stash($name, $statement, $should_cache);

Stash an SQL statement. The method can be called both on the class and instance. If the class method is called the statement will be added to the global stash. If the instance method is called the statement will only be added to the instance-specific stash.

The name is used as an identifier in order to later retrieve it. The should_cache parameter is optional and specifies whether prepare() or prepare_cached() is used to prepare the statement. It defaults to true.

        SQL::Stash::Foo->stash('select_foo', 'SELECT * FROM Foo');


        $stash->retrieve($name, @_);

Prepare the statement stored via stash, identified by name, and return a prepared statement handle. The SQL statement may be modified by transform_sql before it is prepared.


        $stash->transform_sql($sql, @_)

Transform the SQL statement before it is prepared to enable dynamically generated statements. The default implementation is to use sprintf, but sub-classes may override this method to perform any transformation.

        $stash->transform_sql("SELECT * FROM %s", "table");
        #=> SELECT * FROM table


Ima::DBI SQL::Bibliosoph SQL::Snippet


Sebastian Nowicki <>