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); # General Information my @fields = $dbh->bz_get_field_defs();
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.
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)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.
$expr
- SQL expression for the text to be searched (scalar)
$pattern
- the regular expression to search for (scalar)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 prior 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_interval
Outputs proper SQL syntax for a time interval function.
Abstract method, should be overridden by database specific code.
$interval
- the time interval requested (e.g. '30') (integer)
$units
- the units the interval is in (e.g. 'MINUTE') (string)Formatted SQL for interval function (scalar)
sql_position
Outputs proper SQL syntax determinig 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'").
$fragment
- the string fragment we are searching for (scalar)
$text
- the text to search (scalar)Formatted SQL for substring search (scalar)
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_fulltext_search
Returns SQL syntax for performing a full text search for specified text on a given column.
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).
bz_lock_tables
Performs a table lock operation on specified tables. If the underlying database supports transactions, it should also implicitly start a new transaction.
Abstract method, should be overridden by database specific code.
@tables
- list of names of tables to lock in MySQL notation (ex. 'bugs AS bugs2 READ', 'logincookies WRITE')bz_unlock_tables
Performs a table unlock operation.
If the underlying database supports transactions, it should also implicitly commit or rollback the transaction.
Also, this function should allow to be called with the abort flag set even without locking tables first without raising an error to simplify error handling.
Abstract method, should be overridden by database specific code.
$abort
- UNLOCK_ABORT
if the operation on locked tables failed (if transactions are supported, the action will be rolled back). No param if the operation succeeded. This is only used by "throw_error" in Bugzilla::Error.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 "last_insert_id" in DBI. 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)
bz_get_field_defs
Returns a list of all the "bug" fields in Bugzilla. The list contains hashes, with a name
key and a description
key.
List of all the "bug" fields
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_start_transaction
Starts a transaction if supported by the database being used. Returns nothing and takes no parameters.
bz_commit_transaction
Ends a transaction, commiting all changes, if supported by the database being used. Returns nothing and takes no parameters.
bz_rollback_transaction
Ends a transaction, rolling back all changes, if supported by the database being used. 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
\%attributes
- set of attributes for DB connection (optional)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.