[%# # IMPORTANT NOTE # This documentation is generated automatically from source # templates. Any changes you make here may be lost. # # The 'docsrc' documentation source bundle is available for download # from http://www.template-toolkit.org/docs.html and contains all # the source templates, XML files, scripts, etc., from which the # documentation for the Template Toolkit is built. -%] [% META book = 'Modules' page = 'Plugin_DBI' %] [% WRAPPER toc; PROCESS tocitem title ="SYNOPSIS" subs = []; PROCESS tocitem title ="DESCRIPTION" subs = []; PROCESS tocitem title ="OBJECT METHODS" subs = [ "connect(\$database, \$username, \$password)", "query(\$sql)", "prepare(\$sql)", "execute(@args)", "do(\$sql)", "tie(\$table, \$key, \\%args)", "quote(\$value, \$type)", "dbh()", "disconnect()" ]; PROCESS tocitem title ="AUTHORS" subs = []; PROCESS tocitem title ="VERSION" subs = []; PROCESS tocitem title ="COPYRIGHT" subs = []; PROCESS tocitem title ="SEE ALSO" subs = []; END %] [% WRAPPER section title="SYNOPSIS" -%]

Making an implicit database connection:

        # ...using positional arguments
        [% tt_start_tag %] USE DBI('dbi:driver:dbname', 'user', 'pass') [% tt_end_tag %]

        # ...using named parameters
        [% tt_start_tag %] USE DBI( database = 'dbi:driver:dbname',
                    username = 'user',
                    password = 'pass' )
        [% tt_end_tag %]

        # ...using short named parameters (4 lzy ppl and bad typsits)
        [% tt_start_tag %] USE DBI( db   = 'driver:dbname',
                    user = 'user',
                    pass = 'pass' )
        [% tt_end_tag %]

        # ...or an existing DBI database handle
        [% tt_start_tag %] USE DBI( dbh = my_dbh_ref ) [% tt_end_tag %]

Making explicit database connections:

        [% tt_start_tag %] USE DBI [% tt_end_tag %]

        [% tt_start_tag %] DBI.connect(db, user, pass) [% tt_end_tag %]
           ...

        [% tt_start_tag %] DBI.connect(new_db, new_user, new_pass) [% tt_end_tag %]
           ...

        [% tt_start_tag %] DBI.disconnect [% tt_end_tag %]      # final disconnect is optional

Making an automagical database connection using DBI_DSN environment variable:

        [% tt_start_tag %] USE DBI [% tt_end_tag %]

Making database queries:

        # single step query
        [% tt_start_tag %] FOREACH user = DBI.query('SELECT * FROM users') [% tt_end_tag %]
           [% tt_start_tag %] user.uid [% tt_end_tag %] blah blah [% tt_start_tag %] user.name [% tt_end_tag %] etc. etc.
        [% tt_start_tag %] END [% tt_end_tag %]

        # two stage prepare/execute
        [% tt_start_tag %] query = DBI.prepare('SELECT * FROM users WHERE uid = ?') [% tt_end_tag %]

        [% tt_start_tag %] FOREACH user = query.execute('sam') [% tt_end_tag %]
           ...
        [% tt_start_tag %] END [% tt_end_tag %]

        [% tt_start_tag %] FOREACH user = query.execute('abw') [% tt_end_tag %]
           ...
        [% tt_start_tag %] END [% tt_end_tag %]

Making non-SELECT statements:

        [% tt_start_tag %] IF DBI.do("DELETE FROM users WHERE uid = '$uid'") [% tt_end_tag %]
           The user '[% tt_start_tag %] uid [% tt_end_tag %]' was successfully deleted.
        [% tt_start_tag %] END [% tt_end_tag %]

Using named DBI connections:

        [% tt_start_tag %] USE one = DBI(...) [% tt_end_tag %]
        [% tt_start_tag %] USE two = DBI(...) [% tt_end_tag %]

        [% tt_start_tag %] FOREACH item = one.query("SELECT ...etc...") [% tt_end_tag %]
           ...
        [% tt_start_tag %] END [% tt_end_tag %]

        [% tt_start_tag %] FOREACH item = two.query("SELECT ...etc...") [% tt_end_tag %]
           ...
        [% tt_start_tag %] END [% tt_end_tag %]

Tieing to a database table (via Tie::DBI):

        [% tt_start_tag %] people = DBI.tie('users', 'uid') [% tt_end_tag %]

        [% tt_start_tag %] me = people.abw [% tt_end_tag %]   # => SELECT * FROM users WHERE uid='abw'

        I am [% tt_start_tag %] me.name [% tt_end_tag %]

        # clobber option allows table updates (see Tie::DBI)
        [% tt_start_tag %] people = DBI.tie('users', 'uid', clobber=1) [% tt_end_tag %]

        [% tt_start_tag %] people.abw.name = 'not a number' [% tt_end_tag %]

        I am [% tt_start_tag %] people.abw.name [% tt_end_tag %]   # I am a free man!

[%- END %] [% WRAPPER section title="DESCRIPTION" -%]

This Template Toolkit plugin module provides an interface to the Perl DBI/DBD modules, allowing you to integrate SQL queries into your template documents. It also provides an interface via the Tie::DBI module (if installed on your system) so that you can access database records without having to embed any SQL in your templates.

A DBI plugin object can be created as follows:

        [% tt_start_tag %] USE DBI [% tt_end_tag %]

This creates an uninitialised DBI object. You can then open a connection to a database using the connect() method.

        [% tt_start_tag %] DBI.connect('dbi:driver:dbname', 'user', 'pass') [% tt_end_tag %]

The DBI connection can be opened when the plugin is created by passing arguments to the constructor, called from the USE directive.

        [% tt_start_tag %] USE DBI('dbi:driver:dbname', 'user', 'pass') [% tt_end_tag %]

You can also use named parameters to provide the data source connection string, user name and password.

        [% tt_start_tag %] USE DBI(database => 'dbi:driver:dbname',
                   username => 'user',
                   password => 'pass')  [% tt_end_tag %]

For backwards compatability with previous versions of this plugin, you can also spell 'database' as 'data_source'.

        [% tt_start_tag %] USE DBI(data_source => 'dbi:driver:dbname',
                   username    => 'user',
                   password    => 'pass')  [% tt_end_tag %]

Lazy Template hackers may prefer to use 'db', 'dsn' or 'connect' as a shorthand form of the 'database' parameter, and 'user' and 'pass' as shorthand forms of 'username' and 'password', respectively. You can also drop the 'dbi:' prefix from the database connect string because the plugin will add it on for you automagically.

        [% tt_start_tag %] USE DBI(db   => 'driver:dbname',
                   user => 'user',
                   pass => 'pass')  [% tt_end_tag %]

Any additional DBI attributes can be specified as named parameters. The 'PrintError' attribute defaults to 0 unless explicitly set true.

        [% tt_start_tag %] USE DBI(db, user, pass, ChopBlanks=1) [% tt_end_tag %]

An alternate variable name can be provided for the plugin as per regular Template Toolkit syntax:

        [% tt_start_tag %] USE mydb = DBI('dbi:driver:dbname', 'user', 'pass') [% tt_end_tag %]

        [% tt_start_tag %] FOREACH item = mydb.query('SELECT * FROM users') [% tt_end_tag %]
           ...
        [% tt_start_tag %] END [% tt_end_tag %]

You can also specify the DBI plugin name in lower case if you prefer:

        [% tt_start_tag %] USE dbi(dsn, user, pass) [% tt_end_tag %]

        [% tt_start_tag %] FOREACH item = dbi.query('SELECT * FROM users') [% tt_end_tag %]
           ...
        [% tt_start_tag %] END [% tt_end_tag %]

The disconnect() method can be called to explicitly disconnect the current database, but this generally shouldn't be necessary as it is called automatically when the plugin goes out of scope. You can call connect() at any time to open a connection to another database. The previous connection will be closed automatically.

Internally, the DBI connect_cached() method is used instead of the connect() method. This allows for connection caching in a server environment, such as when the Template Toolkit is used from an Apache mod_perl handler. In such a case, simply enable the mod_env module and put in a line such as:

        SetEnv DBI_DSN "dbi:mysql:dbname;host=dbhost;
                                  user=uname;password=pword"

(NOTE: the string shown here is split across 2 lines for the sake of reasonable page formatting, but you should specify it all as one long string with no spaces or newlines).

You can then use the DBI plugin without any parameters or the need to explicitly call connect().

Once you've loaded a DBI plugin and opened a database connection using one of the techniques shown above, you can then make queries on the database using the familiar dotted notation:

        [% tt_start_tag %] FOREACH user = DBI.query('SELECT * FROM users') [% tt_end_tag %]
           [% tt_start_tag %] user.uid [% tt_end_tag %] blah blah [% tt_start_tag %] user.name [% tt_end_tag %] etc. etc.
        [% tt_start_tag %] END [% tt_end_tag %]

The query() method prepares a query and executes it all in one go. If you want to repeat a query with different parameters then you can use a separate prepare/execute cycle.

        [% tt_start_tag %] query = DBI.prepare('SELECT * FROM users WHERE uid = ?') [% tt_end_tag %]

        [% tt_start_tag %] FOREACH user = query.execute('sam') [% tt_end_tag %]
           ...
        [% tt_start_tag %] END [% tt_end_tag %]

        [% tt_start_tag %] FOREACH user = query.execute('abw') [% tt_end_tag %]
           ...
        [% tt_start_tag %] END [% tt_end_tag %]

The query() and execute() methods return an iterator object which manages the result set returned. You can save a reference to the iterator and access methods like size() to determine the number of rows returned by a query.

        [% tt_start_tag %] users = DBI.query('SELECT * FROM users') [% tt_end_tag %]
        [% tt_start_tag %] users.size [% tt_end_tag %] records returned

or even

        [% tt_start_tag %] DBI.query('SELECT * FROM users').size [% tt_end_tag %]

When used within a FOREACH loop, the iterator is always aliased to the special `'loop'` variable. This makes it possible to do things like this:

        [% tt_start_tag %] FOREACH user = DBI.query('SELECT * FROM users') [% tt_end_tag %]
           [% tt_start_tag %] loop.count [% tt_end_tag %]/[% tt_start_tag %] loop.size [% tt_end_tag %]: [% tt_start_tag %] user.name [% tt_end_tag %]
        [% tt_start_tag %] END [% tt_end_tag %]

to generate a result set of the form:

        1/3: Jerry Garcia
        2/3: Kurt Cobain
        3/3: Freddie Mercury

See [% ttlink('Template::Iterator') -%] for further details on iterators and the methods that they implement.

The DBI plugin also provides the do() method to execute non-SELECT statements like this:

        [% tt_start_tag %] IF DBI.do("DELETE FROM users WHERE uid = '$uid'") [% tt_end_tag %]
           The user '[% tt_start_tag %] uid [% tt_end_tag %]' was successfully deleted.
        [% tt_start_tag %] END [% tt_end_tag %]

The plugin also allows you to create a tie to a table in the database using the Tie::DBI module. Simply call the tie() method, passing the name of the table and the primary key as arguments.

        [% tt_start_tag %] people = DBI.tie('person', 'uid') [% tt_end_tag %]

You can then access records in the database table as if they were entries in the 'people' hash.

        My name is [% tt_start_tag %] people.abw.name [% tt_end_tag %]

IMPORTANT NOTE: the XS Stash (Template::Stash::XS) does not currently support access to tied hashes. If you are using the XS stash and having problems then you should try enabling the regular stash instead. You can do this by setting $Template::Config::STASH to 'Template::Stash' before instantiating the Template object.

[%- END %] [% WRAPPER section title="OBJECT METHODS" -%][% WRAPPER subsection title = "connect(\$database, \$username, \$password)" -%]

Establishes a database connection. This method accepts both positional and named parameter syntax. e.g.

        [% tt_start_tag %] DBI.connect( 'dbi:driver:dbname', 'timmy', 'sk8D00Dz' ) [% tt_end_tag %]

        [% tt_start_tag %] DBI.connect( database = 'dbi:driver:dbname'
                        username = 'timmy'
                        password = 'sk8D00Dz' ) [% tt_end_tag %]

The connect method allows you to connect to a data source explicitly. It can also be used to reconnect an exisiting object to a different data source.

If you already have a database handle then you can instruct the plugin to reuse it by passing it as the 'dbh' parameter.

        [% tt_start_tag %] DBI.connect( dbh = my_dbh_ref ) [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = "query(\$sql)" -%]

This method submits an SQL query to the database and creates an iterator object to return the results. This may be used directly in a FOREACH directive as shown below. Data is automatically fetched a row at a time from the query result set as required for memory efficiency.

        [% tt_start_tag %] FOREACH user = DBI.query('SELECT * FROM users') [% tt_end_tag %]
           Each [% tt_start_tag %] user.field [% tt_end_tag %] can be printed here
        [% tt_start_tag %] END [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = "prepare(\$sql)" -%]

Prepare a query for later execution. This returns a compiled query object (of the Template::Plugin::DBI::Query class) on which the execute() method can subsequently be called.

        [% tt_start_tag %] query = DBI.prepare('SELECT * FROM users WHERE id = ?') [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = "execute(@args)" -%]

Execute a previously prepared query. This method should be called on the query object returned by the prepare() method. Returns an iterator object which can be used directly in a FOREACH directive.

        [% tt_start_tag %] query = DBI.prepare('SELECT * FROM users WHERE manager = ?') [% tt_end_tag %]

        [% tt_start_tag %] FOREACH minion = query.execute('abw') [% tt_end_tag %]
           [% tt_start_tag %] minion.name [% tt_end_tag %]
        [% tt_start_tag %] END [% tt_end_tag %]

        [% tt_start_tag %] FOREACH minion = query.execute('sam') [% tt_end_tag %]
           [% tt_start_tag %] minion.name [% tt_end_tag %]
        [% tt_start_tag %] END [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = "do(\$sql)" -%]

The do() method executes a sql statement from which no records are returned. It will return true if the statement was successful

        [% tt_start_tag %] IF DBI.do("DELETE FROM users WHERE uid = 'sam'") [% tt_end_tag %]
           The user was successfully deleted.
        [% tt_start_tag %] END [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = "tie(\$table, \$key, \\%args)" -%]

Returns a reference to a hash array tied to a table in the database, implemented using the Tie::DBI module. You should pass the name of the table and the key field as arguments.

        [% tt_start_tag %] people = DBI.tie('users', 'uid') [% tt_end_tag %]

Or if you prefer, you can use the 'table' and 'key' named parameters.

        [% tt_start_tag %] people = DBI.tie(table='users', key='uid') [% tt_end_tag %]

In this example, the Tie::DBI module will convert the accesses into the 'people' hash into SQL queries of the form:

        SELECT * FROM users WHERE uid=?

For example:

        [% tt_start_tag %] me = people.abw [% tt_end_tag %]

The record returned can then be accessed just like a normal hash.

        I am [% tt_start_tag %] me.name [% tt_end_tag %]

You can also do things like this to iterate through all the records in a table.

        [% tt_start_tag %] FOREACH uid = people.keys.sort;
                person = people.$uid
        [% tt_end_tag %]
            * [% tt_start_tag %] person.id [% tt_end_tag %] : [% tt_start_tag %] person.name [% tt_end_tag %]
        [% tt_start_tag %] END [% tt_end_tag %]

With the 'clobber' (or 'CLOBBER') option set you can update the record and have those changes automatically permeated back into the database.

        [% tt_start_tag %] people = DBI.tie('users', 'uid', clobber=1) [% tt_end_tag %]

        [% tt_start_tag %] people.abw.name = 'not a number' [% tt_end_tag %]

        I am [% tt_start_tag %] people.abw.name [% tt_end_tag %]  # I am a free man!

And you can also add new records. [% tt_start_tag %] people.newguy = { name = 'Nobby Newguy' ...other fields... } [% tt_end_tag %]

See [% ttlink('Tie::DBI') -%] for further information on the 'CLOBBER' option.

[%- END %] [% WRAPPER subsection title = "quote(\$value, \$type)" -%]

Calls the quote() method on the underlying DBI handle to quote the value specified in the appropriate manner for its type.

[%- END %] [% WRAPPER subsection title = "dbh()" -%]

Return the database handle currently in use by the plugin.

[%- END %] [% WRAPPER subsection title = "disconnect()" -%]

Disconnects the current database.

[%- END %] [%- END %] [% WRAPPER section title="AUTHORS" -%]

The DBI plugin was originally written by Simon A Matthews, and distributed as a separate module. It was integrated into the Template Toolkit distribution for version 2.00 and includes contributions from Andy Wardley, Craig Barratt, Dave Hodgkinson and Rafael Kitover.

[%- END %] [% WRAPPER section title="VERSION" -%]

2.48, distributed as part of the Template Toolkit version 2.08, released on 30 July 2002.

[%- END %] [% WRAPPER section title="COPYRIGHT" -%]

Copyright (C) 1999-2001 Simon Matthews. All Rights Reserved

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

[%- END %] [% WRAPPER section title="SEE ALSO" -%]

[% ttlink('Template::Plugin', 'Template::Plugin') -%], [% ttlink('DBI', 'DBI') -%], [% ttlink('Tie::DBI', 'Tie::DBI') -%]

[%- END %]