++ed by:
STAUGAARD NICKL CAMSPI MARKSTOS SRCHULO
16 non-PAUSE users
Author image Juerd Waalboer

NAME

DBIx::Simple - Easy-to-use OO interface to DBI, capable of emulating subqueries

SYNOPSIS

OVERVIEW

DBIx::Simple

    $db = DBIx::Simple->connect(...)  # or ->new

    $db->omniholder         $db->emulate_subqueries  # or ->esq 

    $db->begin_work         $db->commit
    $db->rollback           $db->disconnect
    $db->func(...)

    $result = $db->query(...)

DBIx::Simple::Result

    @row = $result->list    @rows = $result->flat
    $row = $result->array   @rows = $result->arrays
    $row = $result->hash    @rows = $result->hashes

    %map = $result->map_arrays(...)
    %map = $result->map_hashes(...)
    %map = $result->map

    $rows = $result->rows

    $result->finish

EXAMPLES

General

    #!/usr/bin/perl -w
    use strict;
    use DBIx::Simple;

    # Instant database with DBD::SQLite
    my $db = DBIx::Simple->connect('dbi:SQLite:dbname=file.dat');

    # Connecting to a MySQL database
    my $db = DBIx::Simple->connect(
        'DBI:mysql:database=test',     # DBI source specification
        'test', 'test',                # Username and password
        { RaiseError => 1 }            # Additional options
    );

    # Using an existing database handle
    my $db = DBIx::Simple->connect($dbh);

    # Abstracted example: $db->query($query, @variables)->what_you_want;

    $db->commit or die $db->error;

Simple Queries

    $db->query('DELETE FROM foo WHERE id = ?', $id) or die $db->error;

    for (1..100) {
        $db->query(
            'INSERT INTO randomvalues VALUES (?, ?)',
            int rand(10),
            int rand(10)
        ) or die $db->error;
    }

    $db->query(
        'INSERT INTO sometable VALUES (??)',
        $first, $second, $third, $fourth, $fifth, $sixth
    );
    # (??) is expanded to (?, ?, ?, ?, ?, ?) automatically

Single row queries

    my ($two)          = $db->query('SELECT 1 + 1')->list;
    my ($three, $four) = $db->query('SELECT 3, 2 + 2')->list;

    my ($name, $email) = $db->query(
        'SELECT name, email FROM people WHERE email = ? LIMIT 1',
        $mail
    )->list;

Fetching all rows in one go

One big flattened list (primarily for single column queries)

    my @names = $db->query('SELECT name FROM people WHERE id > 5')->flat;

Rows as array references

    for my $row ($db->query('SELECT name, email FROM people')->arrays) {
        print "Name: $row->[0], Email: $row->[1]\n";
    }

Rows as hash references

    for my $row ($db->query('SELECT name, email FROM people')->hashes) {
        print "Name: $row->{name}, Email: $row->{email}\n";
    }

Fetching one row at a time

Rows as lists

    {
        my $result = $db->query('SELECT name, email FROM people');
        while (my @row = $result->list) {
            print "Name: $row[0], Email: $row[1]\n";
        }
    }

Rows as array references

    {
        my $result = $db->query('SELECT name, email FROM people');
        while (my $row = $result->array) {
            print "Name: $row->[0], Email: $row->[1]\n";
        }
    }

Rows as hash references

    {
        my $result = $db->query('SELECT name, email FROM people');
        while (my $row = $result->hash) {
            print "Name: $row->{name}, Email: $row->{email}\n";
        }
    }

Building maps (also fetching all rows in one go)

A hash of hashes

    my $customers =
        $db
        -> query('SELECT id, name, location FROM people')
        -> map_hashes('id');

    # $customers = { $id => { name => $name, location => $location } }

A hash of arrays

    my $customers =
        $db
        -> query('SELECT id, name, location FROM people')
        -> map_arrays(0);

    # $customers = { $id => [ $name, $location ] }

A hash of values (two-column queries)

    my $names =
        $db
        -> query('SELECT id, name FROM people')
        -> map;

    # $names = { $id => $name }

Subquery emulation

    $db->emulate_subqueries = 1;
    
    my @projects = $db->query(q{
        SELECT project_name
        FROM   projects
        WHERE  user_id = (
            SELECT id
            FROM   users
            WHERE  email = ?
        )
    }, $email )->flat;

DESCRIPTION

DBIx::Simple provides a simplified interface to DBI, Perl's powerful database module.

This module is aimed at rapid development and easy maintenance. Query preparation and execution are combined in a single method, the result object (which is a wrapper around the statement handle) provides easy row-by-row and slurping methods.

The query method returns either a result object, or a dummy object. The dummy object returns undef (or an empty list) for all methods and when used in boolean context, is false. The dummy object lets you postpone (or skip) error checking, but it also makes immediate error checking a simple $db->query(...) or die $db->{reason}.

For users of poorly equipped databases (like MySQL), DBIx::Simple provides emulation of subqueries by interpolating intermediate results. For users of better database systems (like SQLite and PostgreSQL), the module provides direct access to DBI's transaction related methods.

DBIx::Simple methods

DBIx::Simple->connect($dbh)
DBIx::Simple->connect($dsn, $user, $pass, \%options)

The connect or new class method takes either an existing DBI object ($dbh), or a list of arguments to pass to DBI->connect. See DBI for a detailed description.

You cannot use this method to clone a DBIx::Simple object: the $dbh passed should be a DBI::db object, not a DBIx::Simple object.

This method is the constructor and returns a DBIx::Simple object on success. On failure, it returns undef.

omniholder($new_value)

This returns the omniholder string, after setting a new string if one is given. Use a $new_value of undef or an empty string to disable the omniholder feature. Note that the given $new_value is not a regular expression. The default omniholder is (??).

As shown in the SYNOPSIS, you can use an omniholder to avoid having to count question marks. In a query, (??) (or whatever string you set using this method) is replaced with (?, ?, ?, ...), with as many question marks as @values passed to the query method (see below).

emulate_subqueries($bool), esq($bool)

DBIx::Simple can emulate nested subqueries (SELECT only) by executing them and interpolating the results. This methods enables or disables this feature. Subquery emulation is disabled by default, and should not be used if the database provides real subqueries.

Only subqueries like (SELECT ...) (note the parentheses) are interpolated.

Please note that emulation is done by doing multiple queries and is not atomic, as it would be if the database supported real subqueries. The queries are executed independently.

error

Returns the error string of the last DBI method. See the discussion of "err" and "errstr" in DBI.

query($query, @values)

The query method pepares and executes the query and returns a result object.

If an omniholder (see above) is present in the query, it is replaced with a list of as many question marks as @values. If subquery emulation (see above) is enabled, subquery results are interpolated in the main query before the main query is executed.

The database drivers substitute placeholders (question marks that do not appear in quoted literals) in the query with the given @values, after them escaping them. You should always use placeholders, and never use user input in database queries.

On success, returns a DBIx::Simple::Result object and sets $db->{success} to 1.

On failure, returns a DBIx::Simple::Dummy object and sets $db->{success} to 0.

begin_work, commit, rollback

These transaction related methods call the DBI respective methods and Do What You Mean. See DBI for details.

func(...)

This calls the func method of DBI. See DBI for details.

disconnect

Destroys (finishes) active statements and disconnects. Whenever the database object is destroyed, this happens automatically. After disconnecting, you can no longer use the database object or any of its result object.

DBIx::Simple::Dummy

The query method of DBIx::Simple returns a dummy object on failure. Its methods all return an empty list or undef, depending on context. When used in boolean context, a dummy object evaluates to false.

DBIx::Simple::Result methods

list

Fetches a single row and returns a list of values. In scalar context, this returns only the last value.

array

Fetches a single row and returns an array reference.

hash

Fetches a single row and returns a hash reference.

flat

Fetches all remaining rows and returns a flattened list.

arrays

Fetches all remaining rows and returns a list of array references.

In scalar context, returns an array reference.

hashes

Fetches all remaining rows and returns a list of hash references.

In scalar context, returns an array reference.

map_arrays($column_number)

Constructs a hash of array references keyed by the values in the chosen column.

In scalar context, returns a hash reference.

map_hashes($column_name)

Constructs a hash of hash references keyed by the values in the chosen column.

In scalar context, returns a hash.

map

Constructs a simple hash, using the first two columns as key/value pairs. Should only be used with queries that return two columns.

In scalar context, returns a reference to the hash.

rows

Returns the number of rows affected by the last row affecting command, or -1 if the number of rows is not known or not available.

For SELECT statements, it is generally not possible to know how many rows are returned. MySQL does provide this information. See DBI for a detailed explanation.

finish

Finishes the statement. After finishing a statement, it can no longer be used. When the result object is destroyed, its statement handle is automatically finished and destroyed. There should be no reason to call this method explicitly; just let the result object go out of scope.

MISCELLANEOUS

Although this module has been tested thoroughly in production environments, it still has no automated test suite. If you want to write tests, please contact me.

The mapping methods do not check whether the keys are unique. Rows that are fetched later overwrite earlier ones.

PrintError is disabled by default. If you enable it, beware that it will report line numbers in DBIx/Simple.pm.

Note: this module does not provide any SQL abstraction and never will. If you don't want to write SQL queries, use DBIx::Abstract.

LICENSE

There is no license. This software was released into the public domain. Do with it what you want, but on your own risk. The author disclaims any responsibility.

AUTHOR

Juerd Waalboer <juerd@cpan.org> <http://juerd.nl/>

SEE ALSO

perl, perlref, DBI