Bugzilla::DB - Database access routines, using DBI
# Obtain db handle use Bugzilla::DB; my $dbh = Bugzilla->dbh; # prepare a query using DB methods my $sth = $dbh->prepare("SELECT " . $dbh->sql_date_format("creation_ts", "%Y%m%d") . " FROM bugs WHERE bug_status != 'RESOLVED' " . $dbh->sql_limit(1)); # Execute the query $sth->execute; # Get the results my @result = $sth->fetchrow_array; # Schema Modification $dbh->bz_add_column($table, $name, \%definition, $init_value); $dbh->bz_add_index($table, $name, $definition); $dbh->bz_add_table($name); $dbh->bz_drop_index($table, $name); $dbh->bz_drop_table($name); $dbh->bz_alter_column($table, $name, \%new_def, $set_nulls_to); $dbh->bz_drop_column($table, $column); $dbh->bz_rename_column($table, $old_name, $new_name); # Schema Information my $column = $dbh->bz_column_info($table, $column); my $index = $dbh->bz_index_info($table, $index);
Functions in this module allows creation of a database handle to connect to the Bugzilla database. This should never be done directly; all users should use the Bugzilla module to access the current dbh
instead.
This module also contains methods extending the returned handle with functionality which is different between databases allowing for easy customization for particular database via inheritance. These methods should be always preffered over hard-coding SQL commands.
Subclasses of Bugzilla::DB are required to define certain constants. These constants are required to be subroutines or "use constant" variables.
BLOB_TYPE
The \%attr
argument that must be passed to bind_param in order to correctly escape a LONGBLOB
type.
ISOLATION_LEVEL
The argument that this database should send to SET TRANSACTION ISOLATION LEVEL
when starting a transaction. If you override this in a subclass, the isolation level you choose should be as strict as or more strict than the default isolation level defined in Bugzilla::DB.
A new database handle to the required database can be created using this module. This is normally done by the Bugzilla module, and so these routines should not be called from anywhere else.
connect_main
Function to connect to the main database, returning a new database handle.
$no_db_name
(optional) - If true, connect to the database server, but don't connect to a specific database. This is only used when creating a database. After you create the database, you should re-create a new Bugzilla::DB object without using this parameter.New instance of the DB class
connect_shadow
Function to connect to the shadow database, returning a new database handle. This routine die
s if no shadow database is configured.
A new instance of the DB class
bz_check_requirements
Checks to make sure that you have the correct DBD and database version installed for the database that Bugzilla will be using. Prints a message and exits if you don't pass the requirements.
If $db_check
is false (from localconfig), we won't check the database version.
$output
- true
if the function should display informational output about what it's doing, such as versions found.bz_create_database
Creates an empty database with the name $db_name
, if that database doesn't already exist. Prints an error message and exits if we can't create the database.
_connect
Internal function, creates and returns a new, connected instance of the correct DB class. This routine die
s if no driver is specified.
$driver
- name of the database driver to use$host
- host running the database we are connecting to$dbname
- name of the database to connect to$port
- port the database is listening on$sock
- socket the database is listening on$user
- username used to log in to the database$pass
- password used to log in to the databaseA new instance of the DB class
_handle_error
Function passed to the DBI::connect call for error handling. It shortens the error for printing.
import
Overrides the standard import method to check that derived class implements all required abstract methods. Also calls original implementation in its super class.
Note: Methods which can be implemented generically for all DBs are implemented in this module. If needed, they can be overridden with DB specific code. Methods which do not have standard implementation are abstract and must be implemented for all supported databases separately. To avoid confusion with standard DBI methods, all methods returning string with formatted SQL command have prefix sql_
. All other methods have prefix bz_
.
new
Constructor. Abstract method, should be overridden by database specific code.
$user
- username used to log in to the database$pass
- password used to log in to the database$host
- host running the database we are connecting to$dbname
- name of the database to connect to$port
- port the database is listening on$sock
- socket the database is listening onA new instance of the DB class
The constructor should create a DSN from the parameters provided and then call db_new()
method of its super class to create a new class instance. See db_new description in this module. As per DBI documentation, all class variables must be prefixed with "private_". See DBI.
sql_regexp
Outputs SQL regular expression operator for POSIX regex searches (case insensitive) in format suitable for a given database.
Abstract method, should be overridden by database specific code.
$expr
- SQL expression for the text to be searched (scalar)$pattern
- the regular expression to search for (scalar)$nocheck
- true if the pattern should not be tested; false otherwise (boolean)$real_pattern
- the real regular expression to search for. This argument is used when $pattern
is a placeholder ('?').Formatted SQL for regular expression search (e.g. REGEXP) (scalar)
sql_not_regexp
Outputs SQL regular expression operator for negative POSIX regex searches (case insensitive) in format suitable for a given database.
Abstract method, should be overridden by database specific code.
Same as "sql_regexp".
Formatted SQL for negative regular expression search (e.g. NOT REGEXP) (scalar)
sql_limit
Returns SQL syntax for limiting results to some number of rows with optional offset if not starting from the begining.
Abstract method, should be overridden by database specific code.
$limit
- number of rows to return from query (scalar)$offset
- number of rows to skip before counting (scalar)Formatted SQL for limiting number of rows returned from query with optional offset (e.g. LIMIT 1, 1) (scalar)
sql_from_days
Outputs SQL syntax for converting Julian days to date.
Abstract method, should be overridden by database specific code.
$days
- days to convert to dateFormatted SQL for returning Julian days in dates. (scalar)
sql_to_days
Outputs SQL syntax for converting date to Julian days.
Abstract method, should be overridden by database specific code.
$date
- date to convert to daysFormatted SQL for returning date fields in Julian days. (scalar)
sql_date_format
Outputs SQL syntax for formatting dates.
Abstract method, should be overridden by database specific code.
$date
- date or name of date type column (scalar)$format
- format string for date output (scalar) (%Y
= year, four digits, %y
= year, two digits, %m
= month, %d
= day, %a
= weekday name, 3 letters, %H
= hour 00-23, %i
= minute, %s
= second)Formatted SQL for date formatting (scalar)
sql_date_math
Outputs proper SQL syntax for adding some amount of time to a date.
Abstract method, should be overridden by database specific code.
$date
string
The date being added to or subtracted from.
$operator
string
Either -
or +
, depending on whether you're subtracting or adding.
$interval
integer
The time interval you're adding or subtracting (e.g. 30
)
$units
string
the units the interval is in (e.g. 'MINUTE')
Formatted SQL for adding or subtracting a date and some amount of time (scalar)
sql_position
Outputs proper SQL syntax determining position of a substring (fragment) withing a string (text). Note: if the substring or text are string constants, they must be properly quoted (e.g. "'pattern'").
It searches for the string in a case-sensitive manner. If you want to do a case-insensitive search, use "sql_iposition".
$fragment
- the string fragment we are searching for (scalar)$text
- the text to search (scalar)Formatted SQL for substring search (scalar)
sql_iposition
Just like "sql_position", but case-insensitive.
sql_like
Outputs SQL to search for an instance of a string (fragment) in a table column (column).
Note that the fragment must not be quoted. "sql_like" will quote the fragment itself.
This is a case sensitive search.
Note: This does not necessarily generate an ANSI LIKE statement, but could be overridden to do so in a database subclass if required.
$fragment
- the string fragment that we are searching for (scalar)$column
- the column to searchFormatted SQL to return results from columns that contain the fragment.
sql_ilike
Just like "sql_like", but case-insensitive.
sql_not_ilike
Outputs SQL to search for columns (column) that do not contain instances of the string (fragment).
Note that the fragment must not be quoted. "sql_not_ilike" will quote the fragment itself.
This is a case insensitive search.
$fragment
- the string fragment that we are searching for (scalar)$column
- the column to searchFormated sql to return results from columns that do not contain the fragment
sql_group_by
Outputs proper SQL syntax for grouping the result of a query.
For ANSI SQL databases, we need to group by all columns we are querying for (except for columns used in aggregate functions). Some databases require (or even allow) to specify only one or few columns if the result is uniquely defined. For those databases, the default implementation needs to be overloaded.
$needed_columns
- string with comma separated list of columns we need to group by to get expected result (scalar)$optional_columns
- string with comma separated list of all other columns we are querying for, but which are not in the required list.Formatted SQL for row grouping (scalar)
sql_string_concat
Returns SQL syntax for concatenating multiple strings (constants or values from table columns) together.
@params
- array of column names or strings to concatenateFormatted SQL for concatenating specified strings
sql_string_until
Returns SQL for truncating a string at the first occurrence of a certain substring.
Note that both parameters need to be sql-quoted.
$string
The string we're truncating$substring
The substring we're truncating at.sql_fulltext_search
Returns one or two SQL expressions for performing a full text search for specified text on a given column.
If one value is returned, it is a numeric expression that indicates a match with a positive value and a non-match with zero. In this case, the DB must support casting numeric expresions to booleans.
If two values are returned, then the first value is a boolean expression that indicates the presence of a match, and the second value is a numeric expression that can be used for ranking.
There is a ANSI SQL version of this method implemented using LIKE operator, but it's not a real full text search. DB specific modules should override this, as this generic implementation will be always much slower. This generic implementation returns 'relevance' as 0 for no match, or 1 for a match.
$column
- name of column to search (scalar)$text
- text to search for (scalar)Formatted SQL for full text search
sql_istrcmp
Returns SQL for a case-insensitive string comparison.
$left
- What should be on the left-hand-side of the operation.$right
- What should be on the right-hand-side of the operation.$op
(optional) - What the operation is. Should be a valid ANSI SQL comparison operator, such as =
, <
, LIKE
, etc. Defaults to =
if not specified.A SQL statement that will run the comparison in a case-insensitive fashion.
Uses "sql_istring", so it has the same performance concerns. Try to avoid using this function unless absolutely necessary.
Subclass Implementors: Override sql_istring instead of this function, most of the time (this function uses sql_istring).
sql_istring
Returns SQL syntax "preparing" a string or text column for case-insensitive comparison.
$string
- string to convert (scalar)Formatted SQL making the string case insensitive.
The default implementation simply calls LOWER on the parameter. If this is used to search on a text column with index, the index will not be usually used unless it was created as LOWER(column).
sql_in
Returns SQL syntax for the IN ()
operator.
Only necessary where an IN
clause can have more than 1000 items.
$column_name
- Column name (e.g. bug_id
)$in_list_ref
- an arrayref containing values for IN ()
Formatted SQL for the IN
operator.
These methods are implemented in Bugzilla::DB, and only need to be implemented in subclasses if you need to override them for database-compatibility reasons.
These methods return information about data in the database.
bz_last_key
Returns the last serial number, usually from a previous INSERT.
Must be executed directly following the relevant INSERT. This base implementation uses DBI's last_insert_id. If the DBD supports it, it is the preffered way to obtain the last serial index. If it is not supported, the DB-specific code needs to override this function.
$table
- name of table containing serial column (scalar)$column
- name of column containing serial data type (scalar)Last inserted ID (scalar)
These methods are used by the Bugzilla installation programs to set up the database.
bz_populate_enum_tables
For an upgrade or an initial installation, populates the tables that hold the legal values for the old "enum" fields: bug_severity
, resolution
, etc. Prints out information if it inserts anything into the DB.
These methods modify the current Bugzilla Schema.
Where a parameter says "Abstract index/column definition", it returns/takes information in the formats defined for indexes and columns in Bugzilla::DB::Schema::ABSTRACT_SCHEMA
.
bz_add_column
Adds a new column to a table in the database. Prints out a brief statement that it did so, to stdout. Note that you cannot add a NOT NULL column that has no default -- the database won't know what to set all the NULL values to.
$table
- the table where the column is being added$name
- the name of the new column\%definition
- Abstract column definition for the new column$init_value
(optional) - An initial value to set the column to. Required if your column is NOT NULL and has no DEFAULT set.bz_add_index
Adds a new index to a table in the database. Prints out a brief statement that it did so, to stdout. If the index already exists, we will do nothing.
$table
- The table the new index is on.$name
- A name for the new index.$definition
- An abstract index definition. Either a hashref or an arrayref.bz_add_table
Creates a new table in the database, based on the definition for that table in the abstract schema.
Note that unlike the other 'add' functions, this does not take a definition, but always creates the table as it exists in "ABSTRACT_SCHEMA" in Bugzilla::DB::Schema.
If a table with that name already exists, then this function returns silently.
$name
- The name of the table you want to create.bz_drop_index
Removes an index from the database. Prints out a brief statement that it did so, to stdout. If the index doesn't exist, we do nothing.
$table
- The table that the index is on.$name
- The name of the index that you want to drop.bz_drop_table
Drops a table from the database. If the table doesn't exist, we just return silently.
$name
- The name of the table to drop.bz_alter_column
Changes the data type of a column in a table. Prints out the changes being made to stdout. If the new type is the same as the old type, the function returns without changing anything.
$table
- the table where the column is$name
- the name of the column you want to change\%new_def
- An abstract column definition for the new data type of the columm$set_nulls_to
(Optional) - If you are changing the column to be NOT NULL, you probably also want to set any existing NULL columns to a particular value. Specify that value here. NOTE: The value should not already be SQL-quoted.bz_drop_column
Removes a column from a database table. If the column doesn't exist, we return without doing anything. If we do anything, we print a short message to stdout
about the change.
$table
- The table where the column is$column
- The name of the column you want to dropbz_rename_column
Renames a column in a database table. If the $old_name
column doesn't exist, we return without doing anything. If $old_name
and $new_name
both already exist in the table specified, we fail.
$table
- The name of the table containing the column that you want to rename$old_name
- The current name of the column that you want to rename$new_name
- The new name of the columnbz_rename_table
Renames a table in the database. Does nothing if the table doesn't exist.
Throws an error if the old table exists and there is already a table with the new name.
$old_name
- The current name of the table.$new_name
- What you're renaming the table to.These methods return information about the current Bugzilla database schema, as it currently exists on the disk.
Where a parameter says "Abstract index/column definition", it returns/takes information in the formats defined for indexes and columns for "ABSTRACT_SCHEMA" in Bugzilla::DB::Schema.
bz_column_info
Get abstract column definition.
$table
- The name of the table the column is in.$column
- The name of the column.An abstract column definition for that column. If the table or column does not exist, we return undef
.
bz_index_info
Get abstract index definition.
$table
- The table the index is on.$index
- The name of the index.An abstract index definition for that index, always in hashref format. The hashref will always contain the TYPE
element, but it will be an empty string if it's just a normal index.
If the index does not exist, we return undef
.
These methods deal with the starting and stopping of transactions in the database.
bz_in_transaction
Returns 1
if we are currently in the middle of an uncommitted transaction, 0
otherwise.
bz_start_transaction
Starts a transaction.
It is OK to call bz_start_transaction
when you are already inside of a transaction. However, you must call "bz_commit_transaction" as many times as you called bz_start_transaction
, in order for your transaction to actually commit.
Bugzilla uses REPEATABLE READ
transactions.
Returns nothing and takes no parameters.
bz_commit_transaction
Ends a transaction, commiting all changes. Returns nothing and takes no parameters.
bz_rollback_transaction
Ends a transaction, rolling back all changes. Returns nothing and takes no parameters.
Methods in this class are intended to be used by subclasses to help them with their functions.
db_new
Constructor
$dsn
- database connection string$user
- username used to log in to the database$pass
- password used to log in to the database\%override_attrs
- set of attributes for DB connection (optional). You only have to set attributes that you want to be different from the default attributes set inside of db_new
.A new instance of the DB class
The name of this constructor is not new
, as that would make our check for implementation of new
by derived class useless.
"DB_MODULE" in Bugzilla::Constants