GT::SQL::Table - a perl interface to manipulate a single SQL table.
my $sth = $table->select(Column3 => { Column => $value, Column2 => $value2 }); $table->delete({ Column => $value }); $table->insert({ Column1 => $val, Column2 => $value2 }); $table->update({ SetCol => $val }, { WhereCol => $val2 });
GT::SQL::Table provides methods to add, modify, delete and search over a single SQL table.
The following methods are provided.
query
provides a simple and powerful method to search a table. It takes as
input either a hash, hash ref or CGI object making it especially useful
searching from web forms.
my $results = $db->query($in);
The return of query
is an arrayref of arrayrefs. query_sth
returns an STH
that you can fetch rows from.
Typical usage to go through the results is:
my $results = $db->query({ Title => 'foobar' }); if ($results) { for my $result (@$results) { ... } }
To specify what to search, you simply pass in column => search value. However, you can also pass in a lot of options to enhance your search:
Find all rows with field_name = value:
field_name => value
Find all rows with field_name > value:
field_name => ">value"
Find all rows with field_name < value:
field_name => "<value"
Find all rows with field_name > value:
field_name-gt => value
Find all rows with field_name < value:
field_name-lt => value
Find all rows where any field_name = value:
keyword => value
Find all rows using indexed search (see weights):
query => value
Set to 1, use '=' comparison, 0/unspecified use 'LIKE '%val%' comparision:
ww => 1
Search using LIKE for column 'Title' (valid opts are '=', '>', '<' or 'LIKE'):
Title-opt => 'LIKE'
Set to 1, OR match results, 0/unspecified AND match results:
ma => 1
Return a max of n results, defaults to 25:
mh => n
Return page n of results:
nh => n
Sort by 'Title' column:
sb => 'Title'
Sort in ascending (ASC) or descending (DESC) order:
so => 'ASC'
Select provides a way to implement almost any sql SELECT statement.
An executed statement handle is returned that you can call the normal fetchrow, fetchrow_array, fetchrow_hashref, etc on.
my $sth = $obj->select;
is equivalant to ``SELECT * FROM Table''
my $sth = $obj->select({ Col => Val });
is equivalant to ``SELECT * FROM Table WHERE Col = 'Val'''.
my $sth = $obj->select('Col2', 'Col3', { Col => "Val" });
is equivalant to ``SELECT Col2,Col3 FROM Table WHERE Col => 'Val'''.
So you can pass in a hash reference which represents the where clause, and an array reference where represents what you want to select on.
If you need more complex where clauses, you should use a condition object instead of a hash reference. See the GT::SQL::Condition manpage for more information.
Notes:
my $sth = $obj->select({ Col => \"NOW()" });
which turns into ``SELECT * FROM Table WHERE Col = NOW()''.
my $sth = $obj->select('COUNT(*)');
which turns into ``SELECT COUNT(*)
FROM Table''.
To specify LIMIT, or GROUP BY, or ORDER BY or other SELECT clauses that come after the WHERE, you should use select_options below.
This method provides a way for you to specify select options such as LIMIT and SORT_BY.
$obj->select_options(@OPTIONS);
@OPTIONS should be a list of options you want appended to your next select.
For example,
$obj->select_options('ORDER BY Foo', 'LIMIT 50'); $obj->select;
would turn into ``SELECT * FROM Table ORDER BY Foo LIMIT 50''. To perform a LIMIT with an OFFSET, you should specify something like:
$obj->select_options('LIMIT 25 OFFSET 75');
You can alternatively use the equivelant MySQL-specific syntax:
$obj->select_options('LIMIT 75, 25');
Both will be handled correctly regardless of the database type.
This method will allow you to count records based on a where clause.
my $count = $obj->count($condition);
count()
takes either a condition or a hash reference. If no argument is
provided, it is equivalant to ``SELECT COUNT(*)
FROM Table'', or total number of
rows.
This method returns the number of hits from that last select query without the limit clause if there was one.
$hits = $obj->hits;
For example, to get rows 20-30 of a query result, use:
$obj->select_options("LIMIT 10 OFFSET 20"); $obj->select({ Column => 'Foo' });
this translates into (in MySQL):
SELECT * FROM Table WHERE Column = 'Foo' LIMIT 20, 10
To see the total number of results that the query would have retrieved without any limit, you call:
$hits = $obj->hits;
If the number of hits can be calculated, it will be returned to you without any additional query. Otherwise, the following query will be performed automatically, and the hit count returned to you:
SELECT COUNT(*) FROM Table WHERE Column = 'Foo'
NOTE: The hits()
method _only_ applies to select queries. Most databases do
not provide enough information to get counts of rows affected for other types
of queries.
This method allows for a simple interface to retrieving records from the table(s).
my $rec_hash_ref = $obj->get($val); my $rec_hash_ref = $obj->get($val, 'HASH', ['col1', 'col2']); my $rec_array_ref = $obj->get($val, 'ARRAY');
The first argument is the primary key value of the record you want to retrieve.
The second argument is a format option. It can be either 'ARRAY' or 'HASH' and determines whether you are returned a HASH reference or an ARRAY reference. The default is 'HASH', and it is optional.
The last argument is a list of column names you want retrieved. get
defaults
to returning the entire record, but if you only need specific columns, you can
ask for the ones you want.
For example:
my $employee = $emp_db->get('Alex');
would return a hash ref of the record whose primary key is equal to 'Alex'.
my $emp_addr = $emp_db->get('Alex', 'HASH', ['City', 'State', 'ZipCode']);
would return a hash ref of only the three fields City, State, ZipCode for the record whose primary key equals Alex.
Method to add an entry into the database. This method can take it's arguments one of three ways.
$obj->add($CGI_OBJECT);
-or-
$obj->add({ col1 => $val1, col2 => $val2, ... });
-or-
$obj->add( col1 => $val1, col2 => $val2, ... );
This method can take a cgi object, a hash reference or a hash. The keys of the hash should be the names of the column and the values should be the values to insert into the fields. The CGI Object is not different. If the table has an auto_increment field, the value of the last inserted record will be returned.
add
returns undef on failure. If successful, and the table has an
auto-increment field, the auto increment value is returned. If there is no
auto increment value, then 1 is returned. Any errors will be in
$GT::SQL::error.
Passing in GT_SQL_SKIP_CHECK => 1 will have the table module skip any error checking it should perform.
Passing in GT_SQL_SKIP_INDEX => 1 will not index the fields. You can also use
the indexing
method to do this.
insert
is a lower level add. The main differences between add
and
insert
are that add performs a not null check, and add returns the id of the
just inserted value.
insert
does not perform a not null check. Also, insert returns the statement
handle used to do the insert (so you can call $sth->insert_id to get the auto
increment).
insert_multiple
will try to optimize the insertion of multiple rows with
simple values. Under MySQL, this uses MySQL's extended insert syntax:
INSERT INTO Table (col1, col2, col3) VALUES ('val1', 'val2', 'val3'), ('val4', 'val5', 'val6'), ...
On other databases, it attempts to perform all insertions in a single
transaction, which will also usually yield performance benefits. Note,
however, that insert_multiple
should not be used for anything more complex
than basic column values - for example, inserting NULL to set the current date,
or using raw SQL by passing scalar references for values.
It takes at least two arguments - the first argument is an array ref of column names, and the rest are array references of values. For example, to produce the above example SQL code, you would call:
$table->insert_multiple( ['col1', 'col2', 'col3'], ['val1', 'val2', 'val3'], ['val4', 'val5', 'val6'], ... );
This method is designed for modifying a single entry in the table. It takes as input a hash, hash ref or CGI object, which is assumed to represent a single row with all fields intact.
modify
will then look for the primary key in the input and set all fields
for that row equal to what was passed in.
You need to pass in a complete record! If you just want to update one column,
you probably want to use update
instead, as doing:
my $result = $obj->modify(column1 => 'Foo');
will blank out all the other fields and set just column1 to Foo.
modify
returns undef on failure, 1 on success. The error message will be
available in $GT::SQL::error.
This method provides a more robust way to update multiple entries in the table.
my $result = $obj->update( { col1 => $val1, col2 => $val2, ... }, $condition );
-or-
my $result = $obj->update( { col1 => $val1, col2 => $val2, ... }, { col1 => $val1, col2 => $val2, ... } );
In both these cases the first argument is a hash reference with the column names as the keys and the new values you want the columns to hold as the values. The second argument can either be a condition object or a hash reference. If it is a hash reference the keys will be used as the column names and the values will be taken as the current column values for the where clause to update the table.
$obj->update({ Setme => 'NewValue'}, { WhereCol => 5 });
would set the column 'Setme' to 'NewValue' where the column 'WhereCol' is 5. This translates to:
UPDATE Table SET SetMe='NewValue' WHERE WhereCol = 5
If the second argument is a GT::SQL::Condition object the condition object will be used to build the where clause with. Please see the GT::SQL::Condition manpage for a description of what you can do with a where clause.
my $condition = GT::SQL::Condition->new('WhereCol', 'LIKE', 'Foo%'); $obj->update({ Setme => 'Newvalue' }, $condition);
would translate to:
UPDATE Table SET Setme = 'Newvalue' WHERE WhereCol LIKE 'Foo%'
The condition can now much more complex where clauses though.
update
returns undef on failure and the a the GT::SQL::Driver manpage statement
handle on success. The error message will be available in $GT::SQL::error.
Passing in GT_SQL_SKIP_CHECK => 1 as a third option to update
will have the
table module skip any error checking it should perform.
Passing in GT_SQL_SKIP_INDEX => 1 will not index the fields. You can also use
the indexing
method to do this.
This method provides a robust interface to delete entries from your table(s)
using join and or foreign key relations.
my $result = $obj->delete($condition);
You can pass into delete
either a condition object to delete multiple
entries, or a scalar value to delete the row whose primary key equals the
value. If you have a multiple primary key, then you can pass in an array ref to
delete that row.
my $result = $obj->delete({ col1 => $val1, col2 => $val2, ... );
-or-
$obj->delete($val);
-or-
$obj->delete([$val1, $val2]);
delete
returns undef on failure, 1 on success. The error message will be
available in $GT::SQL::error.
This method takes no arguments and will erase all entries from a table.
Table provides a lot of methods to access information about the table:
array(ref)
of primary key column names.
hash(ref)
of column name => column definition
hash(ref)
of column name => default value.
hash(ref)
of column name => size of column in SQL.
hash(ref)
of column name => type of column in SQL.
hash(ref)
of column name => name to display on auto generated forms
(think pretty name).
hash(ref)
of column name => size of html form to generate.
hash(ref)
of column name => type of html form to generate (checkbox,
select, text, etc).
hash(ref)
of column name => array ref of form names. This is used for
multi option form elements like checkboxes and multi selects. The name is what
is displayed to the user and not entered in the database.
hash(ref)
of column name => array ref of form values. Same as above,
but this is the value that actually gets entered.
hash(ref)
of column name => time check on or off. If set
hash(ref)
of column name => regular expression that all input must
pass before being inserted.
hash(ref)
of column name => position in table.
hash(ref)
of column name => not null (whether the field is allowed to
be null or not).
Copyright (c) 2004 Gossamer Threads Inc. All Rights Reserved. http://www.gossamer-threads.com/
Revision: $Id: Table.pm,v 1.251 2005/02/28 20:37:41 jagerman Exp $