DBIx::Simple(3pm)
okay so you just opened DBIx::Simple(3pm), straight out of the User Contributed Perl Documentation pile, and bestieβ¦ this is the page where your database code stops being a whole entire ordeal. π
Sit down, hydrate, let's go.
πΈ NAME πΈ
DBIx::Simple β Very complete easy-to-use OO interface to DBI. That's the whole vibe. It's an object-oriented bestie for DBI and it wants you to have a good time.
β¨ SYNOPSIS β¨
π¦ DBIx::Simple
$db = DBIx::Simple->connect(...) # or ->new
$db->keep_statements = 16
$db->lc_columns = 1
$db->result_class = 'DBIx::Simple::Result';
$db->begin_work $db->commit
$db->rollback $db->disconnect
$db->func(...) $db->last_insert_id
$result = $db->query(...)
π¦ DBIx::SImple + SQL::Interp
(yes, the capital I in the middle is the original's, not a typo we invented β we don't make the rules, we just report them π)
$result = $db->iquery(...)
π¦ DBIx::Simple + SQL::Abstract
$db->abstract = SQL::Abstract->new(...)
$result = $db->select(...)
$result = $db->insert(...)
$result = $db->update(...)
$result = $db->delete(...)
π¦ DBIx::Simple::Result
@columns = $result->columns
$result->into($foo, $bar, $baz)
$row = $result->fetch
@row = $result->list @rows = $result->flat
$row = $result->array @rows = $result->arrays
$row = $result->hash @rows = $result->hashes
@row = $result->kv_list @rows = $result->kv_flat
$row = $result->kv_array @rows = $result->kv_arrays
$obj = $result->object @objs = $result->objects
%map = $result->map %grouped = $result->group
%map = $result->map_hashes(...) %grouped = $result->group_hashes(...)
%map = $result->map_arrays(...) %grouped = $result->group_arrays(...)
$rows = $result->rows
$dump = $result->text
$result->finish
π¦ DBIx::Simple::Result + DBIx::XHTML_Table
$html = $result->html(...)
$table_object = $result->xto(...)
π¦ Examples
Please read DBIx::Simple::Examples for code examples. There's a whole other page of them, go look. π
π DESCRIPTION π
DBIx::Simple hands you a simplified interface to DBI, Perl's powerful database module. It's giving "glow-up for your queries."
This module is aimed at rapid development and easy maintenance. Query preparation and execution are combined into a single method, and the result object β which is a wrapper around the statement handle β serves up easy row-by-row and slurping methods. Slurping. As a treat.
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 as simple as:
$db->query(...) or die $db->error
π DBIx::Simple methods
β Class methods
connect($dbh),connect($dsn, $user, $pass, \%options),new($dbh),new($dsn, $user, $pass, \%options)β Theconnectornewclass method takes either an existing DBI object ($dbh), or a list of arguments to pass toDBI->connect. See DBI for a detailed description.
You cannot use this method to clone a DBIx::Simple object: the $dbh you pass in should be a DBI::db object, not a DBIx::Simple object. No copy-paste shortcuts here, bestie.
For new connections, PrintError is disabled by default. If you go ahead and enable it, beware: it will report line numbers in DBIx/Simple.pm. Not your file. Their file.
For new connections, RaiseError is enabled by default β unless the environment variable PERL_DBIX_SIMPLE_NO_RAISEERROR is set to a non-empty non-0 value. So that's the escape hatch, and now you know it exists. π«Ά
This method is the constructor and returns a DBIx::Simple object on success. On failure, it returns undef.
β Object methods
query($query, @values)β Prepares and executes the query and returns a result object.
If the string (??) is present in the query, it is replaced with a list of as many question marks as @values. Manifesting placeholders.
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 raw user input in database queries. Never. Raw. User input. In. Queries. That's the whole rule.
On success, returns a DBIx::Simple::Result object. On failure, returns a DBIx::Simple::Dummy object.
iquery(...)β Uses SQL::Interp to interpolate values into a query, and uses the resulting generated query and bind arguments withquery. See SQL::Interp's documentation for usage information.
Requires Mark Stosberg's SQL::Interp, which is available from CPAN. SQL::Interp is a fork from David Manura's SQL::Interpolate. Genealogy, iconic.
select,insert,update,deleteβ Calls the respective method onabstract, and uses the resulting generated query and bind arguments withquery. See SQL::Abstract's documentation for usage information. You can override the object by assigning to theabstractproperty.
Requires Nathan Wiger's SQL::Abstract, which is available from CPAN.
begin_work,begin,commit,rollbackβ These transaction related methods call the DBI respective methods and Do What You Mean. See DBI for details.
begin is an alias for begin_work.
func(...)β Calls thefuncmethod of DBI. See DBI for details.last_insert_id(...)β Calls thelast_insert_idmethod of DBI. See DBI for details. Note that this feature requires DBI 1.38 or newer.disconnectβ Destroys (finishes) active statements and disconnects. Whenever the database object is destroyed, this happens automatically if DBIx::Simple handled the connection (i.e. you didn't use an existing DBI handle). After disconnecting, you can no longer use the database object or any of its result objects. Gone. Ghosted. Fr fr.
β Object properties
dbhβ Exposes the internal database handle. Use this only if you know what you are doing. Keeping a reference or doing queries can interfere with DBIx::Simple's garbage collection and error reporting. Lowkey a "you've been warned" moment.lc_columns = $boolβ When true at time of query execution, makes several result object methods use lower cased column names.lc_columnsis true by default.keep_statements = $integerβ Sets the number of statement objects that DBIx::Simple can keep for reuse. This can dramatically speed up repeated queries (like when used in a loop).keep_statementsis 16 by default.
A query is only reused if it equals a previously used one literally. This means that to benefit from this caching mechanism, you must use placeholders and never interpolate variables yourself.
# Wrong:
$db->query("INSERT INTO foo VALUES ('$foo', '$bar', '$baz')");
$db->query("SELECT FROM foo WHERE foo = '$foo' OR bar = '$bar'");
# Right:
$db->query('INSERT INTO foo VALUES (??)', $foo, $bar, $baz);
$db->query('SELECT FROM foo WHERE foo = ? OR bar = ?', $foo, $baz);
Of course, automatic value escaping is a much better reason for using placeholders. The caching is just the bonus.
result_class = $stringβ Class to use for result objects. Defaults to DBIx::Simple::Result. A constructor is not used.errorβ Returns the error string of the last DBI method. See the discussion of"err"and"errstr"in DBI.abstract = SQL::Abstract->new(...)β Sets the object to use with theselect,insert,updateanddeletemethods. On first access, will create one with SQL::Abstract's default options.
Requires Nathan Wiger's SQL::Abstract, which is available from CPAN.
In theory, you can assign any object to this property, as long as that object has these four methods, and they return a list suitable for use with the query method. In theory. π
π 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.
It's the polite little "no thoughts, head empty" object. It won't crash on you, it just won't do anything.
π DBIx::Simple::Result methods
Methods documented to return "a list" return a reference to an array of the same in scalar context, unless something else is explicitly mentioned. Write that down.
columnsβ Returns a list of column names. Affected bylc_columns.bind(LIST)β Binds the given LIST of variables to the columns. Unlike with DBI'sbind_columns, passing references is not needed.
Bound variables are very efficient. Binding a tied variable doesn't work. Doesn't work. Don't fight it.
attr(...)β Returns a copy of an sth attribute (property). See"Statement Handle Attributes"in DBI for details.func(...)β This calls thefuncmethod on the sth of DBI. See DBI for details.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. Let it leave the group chat on its own.
π Fetching a single row at a time
fetchβ Returns a reference to the array that holds the values. This is the same array every time.
Subsequent fetches (using any method) may change the values in the variables passed and the returned reference's array. Same array, same vibes, different contents.
into(LIST)β Combinesbindwithfetch. Returns whatfetchreturns.listβ Returns a list of values, or (in scalar context), only the last value.arrayβ Returns a reference to an array.hashβ Returns a reference to a hash, keyed by column name. Affected bylc_columns.kv_listβ Returns an ordered list of interleaved keys and values. Affected bylc_columns.kv_arrayβ bestie, this one hands you a ref to an array of interleaved column names and values. Likekv, but it stays an array reference even when you're in list context. Affected bylc_columns. πobject($class, ...)β gives you back an instance of$class. Peep "Object construction" for the tea. Possibly affected bylc_columns. β¨
π¦ Fetching all remaining rows π¦
Grab everything that's left in the result, no crumbs:
flatβ returns a flattened list. Simple as that. πarraysβ returns a list of references to arrays.hashesβ returns a list of references to hashes, keyed by column name. Affected bylc_columns. πkv_flatβ returns a flattened list of interleaved column names and values. Affected bylc_columns.kv_arraysβ returns a list of references to arrays of interleaved column names and values. Affected bylc_columns.objects($class, ...)β returns a list of instances of$class. See "Object construction". Possibly affected bylc_columns. πmapgroupβ builds a lil' hash using the two columns as key/value pairs. Should only be used with queries that return exactly two columns, okay? Returns a list of interleaved keys and values, or (in scalar context) a reference to a hash.
With unique keys, use map. With non-unique keys, use group, which gives you an array of values per key. π
map_hashes($column_name)group_arrays($column_number)β builds a hash keyed by the values in the chosen column, and returns a list of interleaved keys and values, or (in scalar context) a reference to a hash. Affected bylc_columns.
With unique keys, use map_hashes, which gives a single hash per key. With non-unique keys, use group_hashes, which gives an array of hashes per key.
map_arrays($column_number)group_arrays($column_number)β builds a hash keyed by the values in the chosen column, and returns a list of interleaved keys and values, or (in scalar context) a reference to a hash.
With unique keys, use map_arrays, which gives a single array per key. With non-unique keys, use group_arrays, which gives an array of arrays per key.
xto(%attr)β returns aDBIx::XHTML_Tableobject, passing the constructor a reference to%attr.
Requires Jeffrey Hayes Anderson's DBIx::XHTML_Table, which is available from CPAN. π
Ngl, in general using the html method (described right below, keep reading bestie) is much easier. xto is here in case you need more flexibility. Not affected by lc_columns.
html(%attr)β returns an (X)HTML formatted table, using theDBIx::XHTML_Tablemodule. Passes a reference to%attrto both the constructor and theoutputmethod.
Requires Jeffrey Hayes Anderson's DBIx::XHTML_Table, which is available from CPAN.
This method is a shortcut method. That means that
$result->html
$result->html(
tr => { bgcolor => [ 'silver', 'white' ] },
no_ucfirst => 1
)
do the same as:
$result->xto->output
$result->xto(
tr => { bgcolor => [ 'silver', 'white' ] }
)->output(
no_ucfirst => 1
);
text($type)β returns a string with a simple text representation of the data.$typecan be any of:neat,table,box. It defaults totableifText::Tableis installed, and toneatif it isn't.
table and box require Anno Siegel's Text::Table, which is available from CPAN. πΈ
π§ Object construction π§
So DBIx::Simple has basic support for returning results as objects. The actual construction method has to be provided by the chosen class, which makes this whole thing rather advanced and maybe not it for beginning programmers. π
When the object or objects method is called on the result object returned by one of the query methods, two approaches are tried. Either way, pass the name of a class as the first argument. A prefix of a single colon can be used as an alias for DBIx::Simple::Result::, e.g. :Example is short for DBIx::Simple::Result::Example. Modules are loaded on demand. β¨
The default class when no class is given is :RowObject. It requires Jos Boumans' Object::Accessor, which is available from CPAN.
π Simple object construction π
When object is given a class that provides a new method, but not a new_from_dbix_simple method, new is called with a list of interleaved column names and values, like a flattened hash, but ordered. objects causes new to be called multiple times, once for each remaining row.
Example:
{
package DBIx::Simple::Result::ObjectExample;
sub new {
my ($class, %args) = @_;
return bless $class, \%args;
}
sub foo { ... }
sub bar { ... }
}
$db->query('SELECT foo, bar FROM baz')->object(':ObjectExample')->foo();
β Advanced object construction β
When object or objects is given a class that provides a new_from_dbix_simple method, any new is ignored, and new_from_dbix_simple is called with a list of the DBIx::Simple::Result object and any arguments passed to object or objects.
new_from_dbix_simple is called in scalar context for object, and in list context for objects. In scalar context, it should fetch exactly one row, and in list context, it should fetch all remaining rows.
Example:
{
package DBIx::Simple::Result::ObjectExample;
sub new_from_dbix_simple {
my ($class, $result, @args) = @_;
return map { bless $class, $_ } $result->hashes if wantarray;
return bless $class, $result->hash;
}
sub foo { ... }
sub bar { ... }
}
$db->query('SELECT foo, bar FROM baz')->object(':ObjectExample')->foo();
π MISCELLANEOUS π
Heads up bestie: the mapping methods do not check whether the keys are unique. Rows that are fetched later overwrite earlier ones. Periodt. π
π LICENSE π
Pick your favourite OSI approved license :)
http://www.opensource.org/licenses/alphabetical
π AUTHOR π
Juerd Waalboer <#####@juerd.nl> <http://juerd.nl/>
πΈ SEE ALSO πΈ
perl, perlref
DBI, DBIx::Simple::Examples, SQL::Abstract, DBIx::XHTML_Table
That's the whole page, babe β this was perl v5.36.0, dated 2023-09-01, and it's DBIx::Simple(3pm). Go write some queries, you absolute icon. π
β¨
π¦ where this page comes from
- debian trixie: libdbix-simple-perl 1.37-3 Β· any-OSI
- ubuntu noble: libdbix-simple-perl 1.37-3 Β· any-OSI
- ubuntu resolute: libdbix-simple-perl 1.37-3 Β· any-OSI
- ubuntu stonking: libdbix-simple-perl 1.37-3 Β· any-OSI
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms