DBIx-Simple-1.37/0000755000175000017500000000000013212613525012465 5ustar juerdjuerdDBIx-Simple-1.37/META.yml0000644000175000017500000000107213212613525013736 0ustar juerdjuerd--- abstract: 'Very complete easy-to-use OO interface to DBI' author: - 'Juerd Waalboer ' build_requires: ExtUtils::MakeMaker: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.24, CPAN::Meta::Converter version 2.150010' license: unknown meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: DBIx-Simple no_index: directory: - t - inc requires: DBI: '1.21' version: '1.37' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' DBIx-Simple-1.37/META.json0000644000175000017500000000166613212613525014117 0ustar juerdjuerd{ "abstract" : "Very complete easy-to-use OO interface to DBI", "author" : [ "Juerd Waalboer " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.24, CPAN::Meta::Converter version 2.150010", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "DBIx-Simple", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "DBI" : "1.21" } } }, "release_status" : "stable", "version" : "1.37", "x_serialization_backend" : "JSON::PP version 2.27400_02" } DBIx-Simple-1.37/Changes0000644000175000017500000002320213212613410013750 0ustar juerdjuerdRevision history for Perl extension DBIx::Simple. Incompatible changes are marked with "!!". Incompatibility with and changes in "undocumented features" are not always specifically mentioned here. 1.37 2017-12-08 23:49 - POD syntax fix 1.36 2017-12-08 21:23 - $result->object and $result->objects now load any module on demand. (Suggested by Krasimir Berov.) - New: $result->group, $result->group_hashes, $result->group_arrays. (Suggested by Mark Overmeer.) - Fixed typo in 1.35 release date below. (Reported by Sjors Gielen.) - Changed changelog date format from insane to ISO 8601-ish. 1.35 2011-01-04 23:48 !! - RaiseError is now enabled by default, as announced three years ago. Set PERL_DBIX_SIMPLE_NO_RAISEERROR=1 to get the old behavior. 1.34 2010-12-12 16:28 - Added missing documentation. (Reported by Krasimir Berov.) - Fixed off-by-20 mistake in unit tests. 1.33 2010-12-04 00:30 - New license: any(OSI). - Documentation overhaul. - New: $result->kv_list, $result->kv_array, $result->kv_flat, $result->kv_arrays. Handy if the unordered nature of hashes gets in the way. - New: $result->object, $result->objects. - Fixed bug #26924. Cache lookup missed statements at index 0. (Reported by Stanis Trendelenburg via RT.) - Please note that very probably RaiseError will be enabled by default in the next version. 1.32 2007-07-17 14:58 - Test updated to conform to fixed bug in Test::More. See http://www.nntp.perl.org/group/perl.qa/2007/09/msg9269.html 1.31 2007-07-15 00:29 - New: $db->iquery. This method loads SQL::Interp on demand. The feature was requested by several people. Thanks go out to David Manura for writing SQL::Interpolate, and to Mark Stosberg for improving it and releasing that as SQL::Interp. 1.30 2007-04-08 02:29 - Fixed bug #18629. Apparently Want does not consider a method call in rvalue context. The premature optimization that used Want has simply been removed. (Reported by Tomi via RT.) - Fixed bug #22829. With connect($dbh) or new($dbh), DBIx::Simple no longer disconnects implicitly. (Reported by BORISZ via RT.) 1.29 2007-04-04 02:22 - Fixed documentation typo. 1.28 2007-04-04 02:16 - New: $db->result_class. This allows using a custom subclass. - $result->flat now returns an array reference in scalar context. - Optimized: map (up to 15% faster). - The "map" method now really requires exactly two columns. - Minor documentation improvements. 1.27 2007-0318 21:14 !! - Bugfix: (??) was replaced when quoted !! - Bugfix: \' escaping was assumed, but actually only MySQL uses that - New: support \' escaping only for DBD::mysql - New: test suite! - Removed dependency on Data::Swap !! - Removed compatibility package DBIx::Simple::SQE 1.26 2004-11-30 14:25 - Removed documentation of emulate_subqueries. - Minor documentation fixes. 1.25 2004-06-21 09:39 - New: $result->text. - This new method can use Anno Siegel's Text::Table (loaded on demand). 1.24 2004-06-20 21:32 - New: $result->xto. - New: $result->html. - These new methods use Jeffrey Hayes Anderson's DBIx::XHTML_Table (loaded on demand). - New: $result->text. - Documentation =~ s/ESQ/SQE/g. (Reported by Larry Kos) 1.23 2004-06-10 00:00 - New: DBIx::Simple::SQE. - New: $db->abstract. - New: $db->select. - New: $db->insert. - New: $db->update. - New: $db->delete. - These new methods use Nathan Wiger's SQL::Abstract (loaded on demand) and are based on a suggestion by simonm (perlmonks.org). - Yes, I lied. I said that this module would never get SQL abstraction, but this was too easy to add and doesn't hurt anyone who doesn't use it. - New: $db->begin, an alias for $db->begin_work. !! - Removed: $db->emulate_subqueries, $db->esq. (But see DBIx::Simple::SQE.) !! - Removed: $db->omniholder. (Now a constant: always "(??)".) 1.22 2004-05-06 17:30 - Changed the declaration of a variable so that it doesn't blow up under 5.8.4's better strict. This should also fix a still undiscovered bug in the deprecated subquery emulation. (Reported and patched by Jos Boumans ) 1.21 2004-04-29 14:40 - Removed two nonsense entries from the changelog. $db->array and $db->hash do NOT reuse. 1.20 2004-04-27 11:15 - Almost a complete rewrite :) - $db->emulate_subqueries is now deprecated. Use a better database engine instead. - $db->omniholder is now deprecated. The omniholder will be constant. - $db->{success} is now deprecated. Use the return value of $db->query instead. - $db->{reason} is now deprecated. Use $db->error instead. !! - $db->{dbi} has been renamed. Use $db->dbh instead (not $db->{dbh}). - DBIx::Simple->error can now be used as a class method. - New: $db->last_insert_id. - New: $db->keep_statements and statement caching. - New: $db->dbh. !! - New: $db->lc_columns, enabled by default. Affects $result->columns, $result->hash, $result->hashes, and $result->map_hashes. - New: $result->columns. - New: $result->bind, $result->fetch, $result->into. - New: $result->func. (Suggested by Sean McMurray ) - New: $result->attr. (Suggested by Sean McMurray ) - $result->array now returns a copy instead of the same arrayref over and over. If you need maximum efficiency, use $result->fetch instead. - Removed dependency on Attribute::Property to fix bugs with $db->emulate_subqueries and $db->omniholder in Perl 5.8.x. !! - As a result, archaic property assignment style no longer works. Instead of "$foo->bar($new_value)", use "$foo->bar = $new_value". - Improved error reporting. - As a result, DBIx::Simple now depends on Data::Swap. - Moved examples to a separate document: DBIx::Simple::Examples. - More conditions in DESTROY methods, to handle random destruction order during global destruction better. - Rebuilt distribution with h2xs to get lib/ and t/. 1.11 2003-03-26 19:05 - Documentation updates. !! - list() now returns the *last* element in scalar context (was: first). - hashes() and arrays() now return array references in scalar context. - Migrated two properties to Attribute::Properties. (new dependency) - $VERSION++. 0.10 2003-01-09 10:03 - Documentation rewrite! - New: $db->error(). In an upcoming release, $db->{reason} will be removed. - New: $db->func(). - Removed some unused variables. - prepare() and execute() are now wrapped in eval { } to rewrite filename and line number if you use RaiseError - $result->map_hashes(), $result->map_arrays() and $result->map() now return a list in list context. In scalar context, they still return a hash reference - Dummy objects in boolean context now evaluate to false, so you can write "$db->query(...) or die $db->error;" but still be able to write "$db->query(...)->something()". - Dummy object's methods now return an empty list in list context instead of undef. - PrintError now defaults to 0 0.09 2002-12-08 05:59 - $dbh->disconnect() only if the object's still there. This works around perl bug #18951. Something is killing objects during (or just before) global destruction. This bug was first found by Gerard Oskamp . 0.08 2002-12-02 21:16 - Added $result->finish() method - The documentation was wrong: "undef $result" did nothing useful, as DBIx::Simple kept a copy internally, for garbage cleaning purposes. An in-between class DBIx::Simple::Statement was added to work around this. - $db->disconnect() now destroys active statements - When finish() or disconnect() is used, attempts to use the database connection or statement handle now result in a verbose error message. 0.07 2002-09-30 07:48 - Removed TraceLevel thing that caused DBI to output debugging info - Very minor documentation update (removed 2 characters) 0.06 2002-09-20 10:55 - Oops: forgot to update the README file; nothing serious 0.05 2002-09-19 14:32 - Added $db->begin_work - No longer expanding the (??) omniholder inside quoted SQL - Subquery emulation! Have subqueries in MySQL! YAY! (Not enabled by default. Use $db->esq(1) to enable) - This module now requires Perl >= 5.6 0.04 2002-09-17 15:46 - Documentation updates only 0.03 2002-06-13 09:50 - New: "(??)" and $db->omniholder() (like EZDBI's ??L placeholder) - Documentation updates - Code updates (now uses $_[0] directly for speed in many methods) - $result->list() in scalar context returns first value only 0.02 2002-03-30 14:00 - New: $db->commit() and rollback(). Suggested by tradez (perlmonks.org) - New: $result->map_hashes(), map_arrays(), map(). Suggested by mattr (perlmonks.org) - New: $result->flat(), a plural form of list() 0.01 2002-03-28 18:04 - Initial CPAN release DBIx-Simple-1.37/t/0000755000175000017500000000000013212613525012730 5ustar juerdjuerdDBIx-Simple-1.37/t/pod.t0000644000175000017500000000020110703264432013671 0ustar juerdjuerduse Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); DBIx-Simple-1.37/t/swap.t0000644000175000017500000000065110703264432014072 0ustar juerdjuerduse Test::More tests => 5; my $hash1orig = bless { qw(a b c d) }, 'Foo'; my $hash1swap = bless { qw(a b c d) }, 'Foo'; my $hash2orig = bless { qw(e f g h) }, 'Bar'; my $hash2swap = bless { qw(e f g h) }, 'Bar'; use_ok('DBIx::Simple'); DBIx::Simple::_swap($hash1swap, $hash2swap); is_deeply($hash1orig, $hash2swap); is_deeply($hash2orig, $hash1swap); is(ref $hash1orig, ref $hash2swap); is(ref $hash2orig, ref $hash1swap); DBIx-Simple-1.37/t/DBIx-Simple.t0000644000175000017500000000007510703264432015135 0ustar juerdjuerduse Test::More tests => 1; BEGIN { use_ok('DBIx::Simple') }; DBIx-Simple-1.37/t/sqlite.t0000644000175000017500000001221013212564477014425 0ustar juerdjuerduse Test::More; use strict; BEGIN { eval { require DBD::SQLite; 1 } or plan skip_all => 'DBD::SQLite required'; eval { DBD::SQLite->VERSION >= 1 } or plan skip_all => 'DBD::SQLite >= 1.00 required'; plan tests => 60; use_ok('DBIx::Simple'); } # In memory database! No file permission troubles, no I/O slowness. # http://use.perl.org/~tomhukins/journal/31457 ++ my $db = DBIx::Simple->connect('dbi:SQLite:dbname=:memory:'); my $q = 'SELECT FOO, bar, baz FROM xyzzy ORDER BY foo'; ok($db); eval { $db->query('SYNTAX ERR0R !@#!@#') }; like($@, qr/prepare failed/); # test RaiseError ok($db->query('CREATE TABLE xyzzy (FOO, bar, baz)')); ok($db->query('INSERT INTO xyzzy (FOO, bar, baz) VALUES (?, ?, ?)', qw(a b c))); is_deeply([ $db->query($q)->flat ], [ qw(a b c) ]); ok($db->query('INSERT INTO xyzzy VALUES (??)', qw(d e f))); is_deeply([ $db->query($q)->flat ], [ qw(a b c d e f) ]); ok($db->query("INSERT INTO xyzzy VALUES (?, '(??)', ?)", qw(g h))); is_deeply([ $db->query($q)->flat ], [ qw(a b c d e f g (??) h) ]); is_deeply(scalar $db->query($q)->list, 'c'); is_deeply([ $db->query($q)->list ], [ qw(a b c) ]); is_deeply($db->query($q)->array, [ qw(a b c) ]); is_deeply(scalar $db->query($q)->arrays, [ [ qw(a b c) ], [ qw(d e f) ], [ qw(g (??) h) ] ]); is_deeply($db->query($q)->hash, { qw(foo a bar b baz c) }); is_deeply(scalar $db->query($q)->hashes, [ { qw(foo a bar b baz c) }, { qw(foo d bar e baz f) }, { qw(foo g bar (??) baz h) } ]); is_deeply([ $db->query($q)->kv_list ], [ qw(foo a bar b baz c) ]); is_deeply(scalar $db->query($q)->kv_list, [ qw(foo a bar b baz c) ]); is_deeply( $db->query($q)->kv_array , [ qw(foo a bar b baz c) ]); is_deeply(scalar $db->query($q)->kv_arrays, [ [ qw(foo a bar b baz c) ], [ qw(foo d bar e baz f) ], [ qw(foo g bar (??) baz h) ] ]); is_deeply(scalar $db->query($q)->kv_flat, [ qw( foo a bar b baz c foo d bar e baz f foo g bar (??) baz h) ]); is_deeply(scalar $db->query($q)->columns, [ qw(foo bar baz) ]); is_deeply([ $db->query($q)->arrays ], scalar $db->query($q)->arrays); is_deeply([ $db->query($q)->hashes ], scalar $db->query($q)->hashes); is_deeply([ $db->query($q)->kv_flat ], scalar $db->query($q)->kv_flat); is_deeply([ $db->query($q)->kv_arrays ], scalar $db->query($q)->kv_arrays); is_deeply([ $db->query($q)->columns ], scalar $db->query($q)->columns); is_deeply(scalar $db->query($q)->map_arrays(2), { c => [ qw(a b) ], f => [ qw(d e) ], h => [ qw(g (??)) ] }); is_deeply(scalar $db->query($q)->map_hashes('baz'), { c => { qw(foo a bar b) }, f => { qw(foo d bar e) }, h => { qw(foo g bar (??)) } }); is_deeply(scalar $db->query('SELECT foo, bar FROM xyzzy ORDER BY foo')->map, { qw(a b d e g (??)) }); $db->lc_columns = 0; is_deeply($db->query($q)->hash, { qw(FOO a bar b baz c) }); is_deeply(scalar $db->query($q)->hashes, [ { qw(FOO a bar b baz c) }, { qw(FOO d bar e baz f) }, { qw(FOO g bar (??) baz h) } ]); is_deeply(scalar $db->query($q)->columns, [ qw(FOO bar baz) ]); is_deeply(scalar $db->query($q)->map_hashes('baz'), { c => { qw(FOO a bar b) }, f => { qw(FOO d bar e) }, h => { qw(FOO g bar (??)) } }); $db->lc_columns = 1; SKIP: { eval { require SQL::Interp } or skip "SQL::Interp required", 1; my $c = 'c'; is_deeply(scalar $db->iquery('SELECT * FROM xyzzy WHERE baz =', \$c)->array, [ qw(a b c) ]); } SKIP: { eval { require Object::Accessor } or skip "Object::Accessor required", 21; my $object = $db->query($q)->object; isa_ok($object, "DBIx::Simple::Result::RowObject"); is($object->foo, 'a'); is($object->bar, 'b', 'bar is b'); is($object->baz, 'c'); my @objects = $db->query($q)->objects; isa_ok($objects[0], "DBIx::Simple::Result::RowObject"); is($objects[0]->foo, 'a'); is($objects[0]->bar, 'b'); is($objects[0]->baz, 'c'); isa_ok($objects[1], "DBIx::Simple::Result::RowObject"); is($objects[1]->foo, 'd'); is($objects[1]->bar, 'e'); is($objects[1]->baz, 'f'); sub Mock::new_from_dbix_simple { my ($class, $result, @foo) = @_; isa_ok($result, "DBIx::Simple::Result"); is_deeply(\@foo, [ 42, 21 ]); return wantarray; } ok(! $db->query($q)->object('Mock', 42, 21)); # wantarray false is_deeply( [ $db->query($q)->objects('Mock', 42, 21) ], [ 1 ]); # wantarray true is_deeply(scalar $db->query($q)->objects('Mock', 42, 21), [ 1 ]); # wantarray true } $db->query('INSERT INTO xyzzy (foo, bar, baz) VALUES (??)', 33, 66, 'c'); $db->query('INSERT INTO xyzzy (foo, bar, baz) VALUES (??)', 44, 77, 'f'); $db->query('INSERT INTO xyzzy (foo, bar, baz) VALUES (??)', 55, 88, 'h'); is_deeply(scalar $db->query($q)->group_arrays(2), { c => [ [ qw(33 66) ], [ qw(a b) ] ], f => [ [ qw(44 77) ], [ qw(d e) ] ], h => [ [ qw(55 88) ], [ qw(g (??)) ] ] }); is_deeply(scalar $db->query($q)->group_hashes('baz'), { c => [ { qw(foo 33 bar 66) }, { qw(foo a bar b) } ], f => [ { qw(foo 44 bar 77) }, { qw(foo d bar e) } ], h => [ { qw(foo 55 bar 88) }, { qw(foo g bar (??)) } ] }); is_deeply(scalar $db->query('SELECT baz, foo FROM xyzzy ORDER BY foo')->group, { c => [ qw(33 a) ], f => [ qw(44 d) ], h => [ qw(55 g) ] }); ok($db->disconnect); DBIx-Simple-1.37/MANIFEST0000644000175000017500000000054613212613525013623 0ustar juerdjuerdChanges Makefile.PL MANIFEST README t/DBIx-Simple.t t/pod.t t/sqlite.t t/swap.t lib/DBIx/Simple.pm lib/DBIx/Simple/Examples.pod lib/DBIx/Simple/Comparison.pod lib/DBIx/Simple/Result/RowObject.pm META.yml Module meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) DBIx-Simple-1.37/lib/0000755000175000017500000000000013212613525013233 5ustar juerdjuerdDBIx-Simple-1.37/lib/DBIx/0000755000175000017500000000000013212613525014021 5ustar juerdjuerdDBIx-Simple-1.37/lib/DBIx/Simple/0000755000175000017500000000000013212613525015252 5ustar juerdjuerdDBIx-Simple-1.37/lib/DBIx/Simple/Result/0000755000175000017500000000000013212613525016530 5ustar juerdjuerdDBIx-Simple-1.37/lib/DBIx/Simple/Result/RowObject.pm0000644000175000017500000000351611477253055021002 0ustar juerdjuerdpackage DBIx::Simple::Result::RowObject; use base 'Object::Accessor'; sub new { my ($class, %args) = @_; my $self = $class->SUPER::new; $self->mk_accessors(keys %args); $self->$_( $args{$_} ) for keys %args; return $self; } 1; =head1 NAME DBIx::Simple::Result::RowObject - Simple result row object class =head1 DESCRIPTION This class is the default for the C and C result object methods. Mainly, it provides syntactic sugar at the expense of performance. Instead of writing my $r = $db->query('SELECT foo, bar FROM baz')->hash; do_something_with $r->{foo}, $r->{bar}; you may write my $r = $db->query('SELECT foo, bar FROM baz')->object; do_something_with $r->foo, $r->bar; This class is a subclass of Object::Accessor, which provides per-object (rather than per-class) accessors. Your records must not have columns names like these: * can * ls_accessors * ls_allow * mk_accessor * mk_clone * mk_flush * mk_verify * new * register_callback * ___autoload * ___callback * ___debug * ___error * ___get * ___set And of course DESTROY and AUTOLOAD, and anything that new versions of Object::Accessor might add. =head1 DBIx::Simple::OO DBIx::Simple::OO is a third party module by Jos Boumans that provided C and C to DBIx::Simple. Similar functionality is now built in, in part inspired by DBIx::Simple:OO. Using DBIx::Simple 1.33 or newer together with DBIx::Simple::OO 0.01 will result in method name clash. DBIx::Simple::Result::RowObject was written to be compatible with DBIx::Simple::OO::Item, except for the name, so C calls still need to be changed. In practice, DBIx::Simple 1.33 makes DBIx::Simple::OO obsolete. =head1 AUTHOR Juerd Waalboer =head1 SEE ALSO L DBIx-Simple-1.37/lib/DBIx/Simple/Examples.pod0000644000175000017500000002522013212572236017540 0ustar juerdjuerd=head1 NAME DBIx::Simple::Examples - Examples of how to use DBIx::Simple =head1 DESCRIPTION DBIx::Simple provides a simplified interface to DBI, Perl's powerful database module. =head1 EXAMPLES =head2 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') or die DBIx::Simple->error; # 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; =head2 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 =head2 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; Or, more efficiently: $db->query('SELECT 1 + 1')->into(my $two); $db->query('SELECT 3, 2 + 2')->into(my ($three, $four)); $db->query( 'SELECT name, email FROM people WHERE email = ? LIMIT 1', $mail )->into(my ($name, $email)); =head2 Fetching all rows in one go =head3 One big flattened list (primarily for single column queries) my @names = $db->query('SELECT name FROM people WHERE id > 5')->flat; =head3 Rows as array references for my $row ($db->query('SELECT name, email FROM people')->arrays) { print "Name: $row->[0], Email: $row->[1]\n"; } =head3 Rows as hash references for my $row ($db->query('SELECT name, email FROM people')->hashes) { print "Name: $row->{name}, Email: $row->{email}\n"; } =head2 Fetching one row at a time =head3 Rows into separate variables { my $result = $db->query('SELECT name, email FROM people'); $result->bind(my ($name, $email)); while ($result->fetch) { print "Name: $name, Email: $email\n"; } } or: { my $result = $db->query('SELECT name, email FROM people'); while ($result->into(my ($name, $email))) { print "Name: $name, Email: $email\n"; } } =head3 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"; } } =head3 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"; } } =head3 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"; } } =head2 Building maps (also fetching all rows in one go) =head3 map =head4 A hash of hashes my $customers = $db -> query('SELECT id, name, location FROM people') -> map_hashes('id'); # $customers = { $id => { name => $name, location => $location }, ... } =head4 A hash of arrays my $customers = $db -> query('SELECT id, name, location FROM people') -> map_arrays(0); # $customers = { $id => [ $name, $location ], ... } =head4 A hash of values (two-column queries) my $names = $db -> query('SELECT id, name FROM people') -> map; # $names = { $id => $name, ... } =head3 group =head4 A hash of arrays of hashes my $customers = $db -> query('SELECT id, name, location FROM people') -> group_hashes('location'); # $customers = { $location => [ { id => $id, name => $name }, ... ], ... } =head4 A hash of arrays of arrays my $customers = $db -> query('SELECT id, name, location FROM people') -> group_arrays(2); # $customers = { $location => [ [ $id, $name ], ... ], ... } =head4 A hash of arrays of values (two-column queries) my $names = $db -> query('SELECT location, name FROM people') -> group; # $names = { $location => [ $name, $name, ... ], ... } =head1 EXAMPLES WITH SQL::Interp If you have SQL::Interp installed, you can use the semi-abstracting method C. This works just like C, but with parts of the query interleaved with the bind arguments, passed as references. You should read L. These examples are not enough to fully understand all the possibilities. The following examples are based on the documentation of SQL::Interp. my $result = $db->iquery('INSERT INTO table', \%item); my $result = $db->iquery('UPDATE table SET', \%item, 'WHERE y <> ', \2); my $result = $db->iquery('DELETE FROM table WHERE y = ', \2); # These two select syntax produce the same result my $result = $db->iquery('SELECT * FROM table WHERE x = ', \$s, 'AND y IN', \@v); my $result = $db->iquery('SELECT * FROM table WHERE', {x => $s, y => \@v}); for ($result->hashes) { ... } Use a syntax highlighting editor for good visual distinction. If you need the helper functions C and C, you can import them with C =head1 EXAMPLES WITH SQL::Abstract If you have SQL::Abstract installed, you can use the abstracting methods C would be: print $db->select('foo', '*')->html; A DBIx::XHTML_Table object can be generated with the C (BHTML_Bable Bbject) method: my $table = $db->query($query)->xto; =head2 Passing attributes DBIx::Simple sends the attributes you pass to C both to the constructor and the output method. This allows you to specify both HTML attributes (like C) and options for XHTML_Table (like C and C) all at once: print $result->html( tr => { bgcolor => [ qw/silver white/ ] }, no_ucfirst => 1 ); =head2 Using an XHTML_Table object Not everything can be controlled by passing attributes. For full flexibility, the XHTML_Table object can be used directly: my $table = $db->query($query)->xto( tr => { bgcolor => [ qw/silver white/ ] } ); $table->set_group('client', 1); $table->calc_totals('credit', '%.2f'); print $table->output({ no_ucfirst => 1 }); # note the {}! =head1 EXAMPLES WITH Text::Table =over 8 =item C<< $result->text("neat") >> Neither neat nor pretty, but useful for debugging. Uses DBI's C method. Doesn't display column names. '1', 'Camel', 'mammal' '2', 'Llama', 'mammal' '3', 'Owl', 'bird' '4', 'Juerd', undef =item C<< $result->text("table") >> Displays a simple table using ASCII lines. id | animal | type ---+--------+------- 1 | Camel | mammal 2 | Llama | mammal 3 | Owl | bird 4 | Juerd | =item C<< $result->text("box") >> Displays a simple table using ASCII lines, with an outside border. +----+--------+--------+ | id | animal | type | +----+--------+--------+ | 1 | Camel | mammal | | 2 | Llama | mammal | | 3 | Owl | bird | | 4 | Juerd | | +----+--------+--------+ =back For C and C, you need Anno Siegel's Text::Table module installed. =head1 AUTHOR Juerd Waalboer =head1 SEE ALSO L, L =cut DBIx-Simple-1.37/lib/DBIx/Simple/Comparison.pod0000644000175000017500000000600711476276334020110 0ustar juerdjuerd=head1 NAME DBIx::Simple::Comparison - DBIx::Simple in DBI jargon =head1 DESCRIPTION This is just a simple and B overview of what DBI things the DBIx::Simple things represent, or the other way around. This document can be useful to find the foo equivalent of bar. C means that DBI doesn't have an equivalent or that I couldn't find one. C<=> means that DBIx::Simple provides a direct wrapper to the DBI function. C<~> means that DBIx::Simple's method does more or less the same, but usually in a more high level way: context sensitive, combining things, automatically taking care of something. Note that DBIx::Simple is a wrapper around DBI. It is not "better" than DBI. In fact, DBIx::Simple cannot work without DBI. Using DBI directly is always faster than using DBIx::Simple's equivalents. (For the computer, that is. For you, DBIx::Simple is supposed to be faster.) =head2 Classes, common names use DBI ~ use DBIx::Simple $DBI::errstr = DBIx::Simple->error DBI::db ~ DBIx::Simple $dbh ~ $db $dbh->errstr = $db->error connect ~ connect connect ~ new DBI::st ~ DBIx::Simple::Result ~ DBIx::Simple::Dummy $sth ~ $result =head2 Queries DBI my $sth = $dbh->prepare_cached($query); $sth->execute(@values); ~ DBIx::Simple my $result = $db->query($query, $values); =head2 Results DBI DBIx::Simple bind_columns ~ bind fetchrow_arrayref/fetch = fetch fetchrow_array ~ list *1 ~ flat [@{fetchrow_arrayref}] = array fetchall_arrayref ~ arrays fetchrow_hashref() *2*3 = hash fetchall_arrayref({}) *4 ~ hashes fetchall_hashref *2 = map_hashes ? ? map_arrays fetchall_hashref(1) *2 = map $sth->{NAME_lc/NAME} = $result->columns *1 There's no fetch variant, but you can do C<< { @{ $dbh->selectcol_arrayref('SELECT ...', { Slice => [] }) } } >>. *2 To receive the keys (column names) lowercased, use C<< $db->{FetchHashKeyName} = 'NAME_lc' >>. DBIx::Simple lower cases them by default. *3 Or supply an argument, C<'NAME_lc'>. *4 No, arrayref isn't a typo. When supplied an empty hash reference, DBI's fetchall_arrayref actually returns hashrefs. This DBI method does not support lower casing of keys, DBIx::Simple does. =head2 Direct access DBI DBIx::Simple $dbh = $db->dbh $sth->{$foo} = $result->attr($foo) func = func begin_work = begin_work commit = commit rollback = rollback last_insert_id = last_insert_id rows = rows disconnect ~ disconnect finish ~ finish =head2 DBIx::Simple specific (?) keep_statements lc_columns iquery (via SQL::Interp) select, insert, update, delete (via SQL::Abstract) abstract (via SQL::Abstract) flat hashes map_arrays map =head1 AUTHOR Juerd Waalboer =head1 SEE ALSO L, L =cut DBIx-Simple-1.37/lib/DBIx/Simple.pm0000644000175000017500000007621413212613416015621 0ustar juerdjuerduse 5.006; use strict; use DBI; use Carp (); $DBIx::Simple::VERSION = '1.37'; $Carp::Internal{$_} = 1 for qw(DBIx::Simple DBIx::Simple::Result DBIx::Simple::DeadObject); my $no_raiseerror = $ENV{PERL_DBIX_SIMPLE_NO_RAISEERROR}; my $quoted = qr/(?:'[^']*'|"[^"]*")*/; # 'foo''bar' simply matches the (?:) twice my $quoted_mysql = qr/(?:(?:[^\\']*(?:\\.[^\\']*)*)'|"(?:[^\\"]*(?:\\.[^\\"]*)*)")*/; my %statements; # "$db" => { "$st" => $st, ... } my %old_statements; # "$db" => [ [ $query, $st ], ... ] my %keep_statements; # "$db" => $int my $err_message = '%s no longer usable (because of %%s)'; my $err_cause = '%s at %s line %d'; package DBIx::Simple; ### private helper subs sub _dummy { bless \my $dummy, 'DBIx::Simple::Dummy' } sub _swap { my ($hash1, $hash2) = @_; my $tempref = ref $hash1; my $temphash = { %$hash1 }; %$hash1 = %$hash2; bless $hash1, ref $hash2; %$hash2 = %$temphash; bless $hash2, $tempref; } ### constructor sub connect { my ($class, @arguments) = @_; my $self = { lc_columns => 1, result_class => 'DBIx::Simple::Result' }; if (defined $arguments[0] and UNIVERSAL::isa($arguments[0], 'DBI::db')) { $self->{dont_disconnect} = 1; $self->{dbh} = shift @arguments; Carp::carp("Additional arguments for $class->connect are ignored") if @arguments; } else { $arguments[3]->{PrintError} = 0 unless defined $arguments[3] and exists $arguments[3]{PrintError}; $arguments[3]->{RaiseError} = 1 unless $no_raiseerror or defined $arguments[3] and exists $arguments[3]{RaiseError}; $self->{dbh} = DBI->connect(@arguments); } return undef unless $self->{dbh}; $self->{dbd} = $self->{dbh}->{Driver}->{Name}; bless $self, $class; $statements{$self} = {}; $old_statements{$self} = []; $keep_statements{$self} = 16; return $self; } sub new { my ($class) = shift; $class->connect(@_); } ### properties sub keep_statements : lvalue { $keep_statements{ $_[0] } } sub lc_columns : lvalue { $_[0]->{lc_columns} } sub result_class : lvalue { $_[0]->{result_class} } sub abstract : lvalue { require SQL::Abstract; $_[0]->{abstract} ||= SQL::Abstract->new; } sub error { my ($self) = @_; return 'DBI error: ' . (ref $self ? $self->{dbh}->errstr : $DBI::errstr); } sub dbh { $_[0]->{dbh} } ### private methods # Replace (??) with (?, ?, ?, ...) sub _replace_omniholder { my ($self, $query, $binds) = @_; return if $$query !~ /\(\?\?\)/; my $omniholders = 0; my $q = $self->{dbd} =~ /mysql/ ? $quoted_mysql : $quoted; $$query =~ s[($q|\(\?\?\))] { $1 eq '(??)' ? do { Carp::croak('There can be only one omniholder') if $omniholders++; '(' . join(', ', ('?') x @$binds) . ')' } : $1 }eg; } # Invalidate and clean up sub _die { my ($self, $cause) = @_; defined and $_->_die($cause, 0) for values %{ $statements{$self} }, map $$_[1], @{ $old_statements{$self} }; delete $statements{$self}; delete $old_statements{$self}; delete $keep_statements{$self}; unless ($self->{dont_disconnect}) { # Conditional, because destruction order is not guaranteed # during global destruction. $self->{dbh}->disconnect() if defined $self->{dbh}; } _swap( $self, bless { what => 'Database object', cause => $cause }, 'DBIx::Simple::DeadObject' ) unless $cause =~ /DESTROY/; # Let's not cause infinite loops :) } ### public methods sub query { my ($self, $query, @binds) = @_; $self->{success} = 0; $self->_replace_omniholder(\$query, \@binds); my $st; my $sth; my $old = $old_statements{$self}; if (defined( my $i = (grep $old->[$_][0] eq $query, 0..$#$old)[0] )) { $st = splice(@$old, $i, 1)->[1]; $sth = $st->{sth}; } else { eval { $sth = $self->{dbh}->prepare($query) } or do { if ($@) { $@ =~ s/ at \S+ line \d+\.\n\z//; Carp::croak($@); } $self->{reason} = "Prepare failed ($DBI::errstr)"; return _dummy; }; # $self is quoted on purpose, to pass along the stringified version, # and avoid increasing reference count. $st = bless { db => "$self", sth => $sth, query => $query }, 'DBIx::Simple::Statement'; $statements{$self}{$st} = $st; } eval { $sth->execute(@binds) } or do { if ($@) { $@ =~ s/ at \S+ line \d+\.\n\z//; Carp::croak($@); } $self->{reason} = "Execute failed ($DBI::errstr)"; return _dummy; }; $self->{success} = 1; return bless { st => $st, lc_columns => $self->{lc_columns} }, $self->{result_class}; } sub begin_work { $_[0]->{dbh}->begin_work } sub begin { $_[0]->begin_work } sub commit { $_[0]->{dbh}->commit } sub rollback { $_[0]->{dbh}->rollback } sub func { shift->{dbh}->func(@_) } sub last_insert_id { my ($self) = @_; ($self->{dbi_version} ||= DBI->VERSION) >= 1.38 or Carp::croak( "DBI v1.38 required for last_insert_id" . "--this is only $self->{dbi_version}, stopped" ); return shift->{dbh}->last_insert_id(@_); } sub disconnect { my ($self) = @_; $self->_die(sprintf($err_cause, "$self->disconnect", (caller)[1, 2])); return 1; } sub DESTROY { my ($self) = @_; $self->_die(sprintf($err_cause, "$self->DESTROY", (caller)[1, 2])); } ### public methods wrapping SQL::Abstract for my $method (qw/select insert update delete/) { no strict 'refs'; *$method = sub { my $self = shift; return $self->query($self->abstract->$method(@_)); } } ### public method wrapping SQL::Interp sub iquery { require SQL::Interp; my $self = shift; return $self->query( SQL::Interp::sql_interp(@_) ); } package DBIx::Simple::Dummy; use overload '""' => sub { shift }, bool => sub { 0 }; sub new { bless \my $dummy, shift } sub AUTOLOAD { return } package DBIx::Simple::DeadObject; sub _die { my ($self) = @_; Carp::croak( sprintf( "(This should NEVER happen!) " . sprintf($err_message, $self->{what}), $self->{cause} ) ); } sub AUTOLOAD { my ($self) = @_; Carp::croak( sprintf( sprintf($err_message, $self->{what}), $self->{cause} ) ); } sub DESTROY { } package DBIx::Simple::Statement; sub _die { my ($self, $cause, $save) = @_; $self->{sth}->finish() if defined $self->{sth}; $self->{dead} = 1; my $stringy_db = "$self->{db}"; my $stringy_self = "$self"; my $foo = bless { what => 'Statement object', cause => $cause }, 'DBIx::Simple::DeadObject'; DBIx::Simple::_swap($self, $foo); my $old = $old_statements{ $foo->{db} }; my $keep = $keep_statements{ $foo->{db} }; if ($save and $keep) { $foo->{dead} = 0; shift @$old until @$old + 1 <= $keep; push @$old, [ $foo->{query}, $foo ]; } delete $statements{ $stringy_db }{ $stringy_self }; } sub DESTROY { # This better only happen during global destruction... return if $_[0]->{dead}; $_[0]->_die('Ehm', 0); } package DBIx::Simple::Result; sub _die { my ($self, $cause) = @_; if ($cause) { $self->{st}->_die($cause, 1); DBIx::Simple::_swap( $self, bless { what => 'Result object', cause => $cause, }, 'DBIx::Simple::DeadObject' ); } else { $cause = $self->{st}->{cause}; DBIx::Simple::_swap( $self, bless { what => 'Result object', cause => $cause }, 'DBIx::Simple::DeadObject' ); Carp::croak( sprintf( sprintf($err_message, $self->{what}), $cause ) ); } } sub func { shift->{st}->{sth}->func(@_) } sub attr { my $dummy = $_[0]->{st}->{sth}->{$_[1]} } sub columns { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my $c = $_[0]->{st}->{sth}->{ $_[0]->{lc_columns} ? 'NAME_lc' : 'NAME' }; return wantarray ? @$c : $c; } sub bind { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; $_[0]->{st}->{sth}->bind_columns(\@_[1..$#_]); } ### Single sub fetch { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; return $_[0]->{st}->{sth}->fetch; } sub into { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my $sth = $_[0]->{st}->{sth}; $sth->bind_columns(\@_[1..$#_]) if @_ > 1; return $sth->fetch; } sub list { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; return $_[0]->{st}->{sth}->fetchrow_array if wantarray; return($_[0]->{st}->{sth}->fetchrow_array)[-1]; } sub array { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my $row = $_[0]->{st}->{sth}->fetchrow_arrayref or return; return [ @$row ]; } sub hash { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; return $_[0]->{st}->{sth}->fetchrow_hashref( $_[0]->{lc_columns} ? 'NAME_lc' : 'NAME' ); } sub kv_list { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my @keys = $_[0]->columns; my $values = $_[0]->array or return; Carp::croak("Different numbers of column names and values") if @keys != @$values; return map { $keys[$_], $values->[$_] } 0 .. $#keys if wantarray; return [ map { $keys[$_], $values->[$_] } 0 .. $#keys ]; } sub kv_array { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; scalar shift->kv_list(@_); } sub object { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my $self = shift; my $class = shift || ':RowObject'; $class =~ s/^:/DBIx::Simple::Result::/; if (not $class->can('new_from_dbix_simple') || $class->can('new')) { (my $filename = "$class.pm") =~ s[::][/]g; require $filename; } if ($class->can('new_from_dbix_simple')) { return scalar $class->new_from_dbix_simple($self, @_); } if ($class->can('new')) { return $class->new( $self->kv_list ); } Carp::croak( qq(Can't locate object method "new_from_dbix_simple" or "new" ) . qq(via package "$class".) ); } ### Slurp sub flat { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; return map @$_, $_[0]->arrays if wantarray; return [ map @$_, $_[0]->arrays ]; } sub arrays { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; return @{ $_[0]->{st}->{sth}->fetchall_arrayref } if wantarray; return $_[0]->{st}->{sth}->fetchall_arrayref; } sub hashes { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my @return; my $dummy; push @return, $dummy while $dummy = $_[0]->hash; return wantarray ? @return : \@return; } sub kv_flat { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; return map @$_, $_[0]->kv_arrays if wantarray; return [ map @$_, $_[0]->kv_arrays ]; } sub kv_arrays { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my @return; my $dummy; push @return, $dummy while $dummy = $_[0]->kv_array; return wantarray ? @return : \@return; } sub objects { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my $self = shift; my $class = shift || ':RowObject'; $class =~ s/^:/DBIx::Simple::Result::/; if (not $class->can('new_from_dbix_simple') || $class->can('new')) { (my $package = "$class.pm") =~ s[::][/]g; require $package; } if ($class->can('new_from_dbix_simple')) { return $class->new_from_dbix_simple($self, @_) if wantarray; return [ $class->new_from_dbix_simple($self, @_) ]; } if ($class->can('new')) { return map { $class->new( @$_ ) } $self->kv_arrays if wantarray; return [ map { $class->new( @$_ ) } $self->kv_arrays ]; } Carp::croak( qq(Can't locate object method "new_from_dbix_simple" or "new" ) . qq(via package "$class" (perhaps you forgot to load "$class"?)) ); } sub _map { my ($keys, $values) = @_; my %return; @return{@$keys} = @$values; return wantarray ? %return : \%return; } sub _group { my ($keys, $values) = @_; my %return; push @{ $return{shift @$keys} }, shift @$values while @$values; return wantarray ? %return : \%return; } sub _keys_and_hashes { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my ($self, $keyname) = @_; Carp::croak('Key column name not optional') if not defined $keyname; my @rows = $self->hashes; my @keys; push @keys, delete $_->{$keyname} for @rows; return \@keys, \@rows; } sub _keys_and_arrays { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my ($self, $keyindex) = @_; $keyindex += 0; my @rows = $self->arrays; my @keys; push @keys, splice @$_, $keyindex, 1 for @rows; return \@keys, \@rows; } sub group_hashes { return _group shift->_keys_and_hashes(@_) } sub map_hashes { return _map shift->_keys_and_hashes(@_) } sub group_arrays { return _group shift->_keys_and_arrays(@_) } sub map_arrays { return _map shift->_keys_and_arrays(@_) } sub map { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; return map @$_, @{ $_[0]->{st}->{sth}->fetchall_arrayref } if wantarray; return { map @$_, @{ $_[0]->{st}->{sth}->fetchall_arrayref } }; } sub group { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my %return; while (my $row = $_[0]->fetch) { push @{ $return{ $row->[0] } }, $row->[1]; } return wantarray ? %return : \%return; } sub rows { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; $_[0]->{st}->{sth}->rows; } sub xto { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; require DBIx::XHTML_Table; my $self = shift; my $attr = ref $_[0] ? $_[0] : { @_ }; # Old DBD::SQLite (.29) spits out garbage if done *after* fetching. my $columns = $self->{st}->{sth}->{NAME}; return DBIx::XHTML_Table->new( scalar $self->arrays, $columns, $attr ); } sub html { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my $self = shift; my $attr = ref $_[0] ? $_[0] : { @_ }; return $self->xto($attr)->output($attr); } sub text { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my ($self, $type) = @_; my $text_table = defined $type && length $type ? 0 : eval { require Text::Table; $type = 'table'; 1 }; $type ||= 'neat'; if ($type eq 'box' or $type eq 'table') { my $box = $type eq 'box'; $text_table or require Text::Table; my @columns = map +{ title => $_, align_title => 'center' }, @{ $self->{st}->{sth}->{NAME} }; my $c = 0; splice @columns, $_ + $c++, 0, \' | ' for 1 .. $#columns; my $table = Text::Table->new( ($box ? \'| ' : ()), @columns, ($box ? \' |' : ()) ); $table->load($self->arrays); my $rule = $table->rule(qw/- +/); return join '', ($box ? $rule : ()), $table->title, $rule, $table->body, ($box ? $rule : ()); } Carp::carp("Unknown type '$type'; using 'neat'") if $type ne 'neat'; return join '', map DBI::neat_list($_) . "\n", $self->arrays; } sub finish { $_[0]->_die if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my ($self) = @_; $self->_die( sprintf($err_cause, "$self->finish", (caller)[1, 2]) ); } sub DESTROY { return if ref $_[0]->{st} eq 'DBIx::Simple::DeadObject'; my ($self) = @_; $self->_die( sprintf($err_cause, "$self->DESTROY", (caller)[1, 2]) ); } 1; __END__ =head1 NAME DBIx::Simple - Very complete easy-to-use OO interface to DBI =head1 SYNOPSIS =head2 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(...) =head2 DBIx::SImple + SQL::Interp $result = $db->iquery(...) =head2 DBIx::Simple + SQL::Abstract $db->abstract = SQL::Abstract->new(...) $result = $db->select(...) $result = $db->insert(...) $result = $db->update(...) $result = $db->delete(...) =head2 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 =head2 DBIx::Simple::Result + DBIx::XHTML_Table $html = $result->html(...) $table_object = $result->xto(...) =head2 Examples Please read L for code examples. =head1 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 C 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 simply C<< $db->query(...) or die $db->error >>. =head2 DBIx::Simple methods =head3 Class methods =over 14 =item C, C =item C, C The C or C class method takes either an existing DBI object ($dbh), or a list of arguments to pass to C<< DBI->connect >>. See L 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. For new connections, PrintError is disabled by default. If you enable it, beware that it will report line numbers in DBIx/Simple.pm. For new connections, B unless the environment variable C is set to a non-empty non-0 value. This method is the constructor and returns a DBIx::Simple object on success. On failure, it returns undef. =back =head3 Object methods =over 14 =item C Prepares and executes the query and returns a result object. If the string C<(??)> is present in the query, it is replaced with a list of as many question marks as @values. 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. On success, returns a DBIx::Simple::Result object. On failure, returns a DBIx::Simple::Dummy object. =item C Uses SQL::Interp to interpolate values into a query, and uses the resulting generated query and bind arguments with C. 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. =item C, C, C and C methods. 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 C method. =back =head2 DBIx::Simple::Dummy The C 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. =head2 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. =over 14 =item C Returns a list of column names. Affected by C. =item C Binds the given LIST of variables to the columns. Unlike with DBI's C, passing references is not needed. Bound variables are very efficient. Binding a tied variable doesn't work. =item C Returns a copy of an sth attribute (property). See L for details. =item C This calls the C method on the sth of DBI. See L for details. =item C 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 L for a detailed explanation. =item C 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. =back =head3 Fetching a single row at a time =over 14 =item C 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. =item C Combines C with C. Returns what C returns. =item C Returns a list of values, or (in scalar context), only the last value. =item C Returns a reference to an array. =item C Returns a reference to a hash, keyed by column name. Affected by C. =item C Returns an ordered list of interleaved keys and values. Affected by C. =item C Returns a reference to an array of interleaved column names and values. Like kv, but returns an array reference even in list context. Affected by C. =item C Returns an instance of $class. See "Object construction". Possibly affected by C. =back =head3 Fetching all remaining rows =over 14 =item C Returns a flattened list. =item C Returns a list of references to arrays =item C Returns a list of references to hashes, keyed by column name. Affected by C. =item C Returns an flattened list of interleaved column names and values. Affected by C. =item C Returns a list of references to arrays of interleaved column names and values. Affected by C. =item C Returns a list of instances of $class. See "Object construction". Possibly affected by C. =item C =item C Constructs a simple hash, using the two columns as key/value pairs. Should only be used with queries that return two columns. Returns a list of interleaved keys and values, or (in scalar context), a reference to a hash. With unique keys, use C. With non-unique keys, use C, which gives an array of values per key. =item C =item C Constructs 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 by C. With unique keys, use C, which gives a single hash per key. With non-unique keys, use C, which gives an array of hashes per key. =item C =item C Constructs 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 C, which gives a single array per key. With non-unique keys, use C, which gives an array of arrays per key. =item C Returns a DBIx::XHTML_Table object, passing the constructor a reference to C<%attr>. Requires Jeffrey Hayes Anderson's DBIx::XHTML_Table, which is available from CPAN. In general, using the C method (described below) is much easier. C is available in case you need more flexibility. Not affected by C. =item C Returns an (X)HTML formatted table, using the DBIx::XHTML_Table module. Passes a reference to C<%attr> to both the constructor and the C method. 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 ); =item C Returns a string with a simple text representation of the data. C<$type> can be any of: C, C
, C. It defaults to C
if Text::Table is installed, to C if it isn't. C
and C require Anno Siegel's Text::Table, which is available from CPAN. =back =head2 Object construction DBIx::Simple has basic support for returning results as objects. The actual construction method has to be provided by the chosen class, making this functionality rather advanced and perhaps unsuited for beginning programmers. When the C or C method is called on the result object returned by one of the query methods, two approaches are tried. In either case, pass the name of a class as the first argument. A prefix of a single colon can be used as an alias for C, e.g. C<":Example"> is short for C<"DBIx::Simple::Result::Example">. Modules are loaded on demand. The default class when no class is given, is C<:RowObject>. It requires Jos Boumans' Object::Accessor, which is available from CPAN. =head3 Simple object construction When C is given a class that provides a C method, but not a C method, C is called with a list of interleaved column names and values, like a flattened hash, but ordered. C causes C 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(); =head3 Advanced object construction When C or C is given a class that provides a C method, any C is ignored, and C is called with a list of the DBIx::Simple::Result object and any arguments passed to C or C. C is called in scalar context for C, and in list context for C. In scalar context, it should fetch I, and in list context, it should fetch I. 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(); =head1 MISCELLANEOUS The mapping methods do not check whether the keys are unique. Rows that are fetched later overwrite earlier ones. =head1 LICENSE Pick your favourite OSI approved license :) http://www.opensource.org/licenses/alphabetical =head1 AUTHOR Juerd Waalboer <#####@juerd.nl> =head1 SEE ALSO L, L L, L, L, L =cut DBIx-Simple-1.37/README0000644000175000017500000000111211477253153013350 0ustar juerdjuerdDBIx::Simple INSTALLATION To install this module type the following: perl Makefile.PL make make test make install Or use CPANPLUS to automate the process. PREREQUISITES DBI Optionally, SQL::Interp can be used for added functionality. Optionally, SQL::Abstract can be used for added functionality. Optionally, DBIx::XHTML_Table can be used for added functionality. Optionally, Text::Table can be used for added functionality. Optionally, Object::Accessor can be used for added functionality. These modules are available from CPAN, . # # DBIx-Simple-1.37/Makefile.PL0000644000175000017500000000042210703264433014437 0ustar juerdjuerduse 5.006; use ExtUtils::MakeMaker; WriteMakefile( NAME => 'DBIx::Simple', VERSION_FROM => 'lib/DBIx/Simple.pm', PREREQ_PM => { 'DBI' => '1.21' }, ABSTRACT_FROM => 'lib/DBIx/Simple.pm', AUTHOR => 'Juerd Waalboer ' );