fDatabaseclassv1.0.0b22

Provides a common API for different databases - will automatically use any installed extension

This class is implemented to use the UTF-8 character encoding. Please see http://flourishlib.com/docs/UTF-8 for more information.

The following databases are supported:

The class will automatically use the first of the following extensions it finds:

Changes:
1.0.0b22Changed clearCache() to also clear the cache on the fSQLTranslation 3/9/10
1.0.0b21Added execute() for result-less SQL queries, prepare() and translatedPrepare() to create fStatement objects for prepared statements, support for prepared statements in query() and unbufferedQuery(), fixed default caching key for enableCaching() 3/2/10
1.0.0b20Added a parameter to enableCaching() to provide a key token that will allow cached values to be shared between multiple databases with the same schema 10/28/09
1.0.0b19Added support for escaping identifiers (column and table names) to escape(), added support for database schemas, rewrote internal SQL string spliting 10/22/09
1.0.0b18Updated the class for the new fResult and fUnbufferedResult APIs, fixed unescape() to not touch NULLs 8/12/09
1.0.0b17Added the ability to pass an array of all values as a single parameter to escape() instead of one value per parameter 8/11/09
1.0.0b16Fixed PostgreSQL and Oracle from trying to get auto-incrementing values on inserts when explicit values were given 8/6/09
1.0.0b15Fixed a bug where auto-incremented values would not be detected when table names were quoted 7/15/09
1.0.0b14Changed determineExtension() and determineCharacterSet() to be protected instead of private 7/8/09
1.0.0b13Updated escape() to accept arrays of values for insertion into full SQL strings 7/6/09
1.0.0b12Updates to unescape() to improve performance 6/15/09
1.0.0b11Changed replacement values in preg_replace() calls to be properly escaped 6/11/09
1.0.0b10Changed date/time/timestamp escaping from strtotime() to fDate/fTime/fTimestamp for better localization support 6/1/09
1.0.0b9Fixed a bug with escape() where floats that start with a . were encoded as NULL 5/9/09
1.0.0b8Added Oracle support, change PostgreSQL code to no longer cause lastval() warnings, added support for arrays of values to escape() 5/3/09
1.0.0b7Updated for new fCore API 2/16/09
1.0.0b6Fixed a bug with executing transaction queries when using the mysqli extension 2/12/09
1.0.0b5Changed @ error suppression operator to error_reporting() calls 1/26/09
1.0.0b4Added a few error suppression operators back in so that developers don't get errors and exceptions 1/14/09
1.0.0b3Removed some unnecessary error suppresion operators 12/11/08
1.0.0b2Fixed a bug with PostgreSQL when using the PDO extension and executing an INSERT statement 12/11/08
1.0.0bThe initial implementation 9/25/07

Variables

->extensionprotected

The extension to use for the database specified

Options include:

  • 'mssql'
  • 'mysql'
  • 'mysqli'
  • 'oci8'
  • 'odbc'
  • 'pgsql'
  • 'sqlite'
  • 'sqlsrv'
  • 'pdo'

Type

string

->schema_infoprotected

A cache of database-specific code

Type

array

Static Methods

::compose() protected

Composes text using fText if loaded

Signature

string compose( string $message, mixed $component )

Parameters

string $message The message to compose
mixed $component [, ... ] A string or number to insert into the message

Returns

The composed and possible translated message

Methods

->__construct() public

Configures the connection to a database - connection is not made until the first query is executed

Signature

fDatabase __construct( string $type, string $database, string $username=NULL, string $password=NULL, string $host=NULL, integer $port=NULL )

Parameters

string $type The type of the database: 'mssql', 'mysql', 'oracle', 'postgresql', 'sqlite'
string $database Name of the database. If an ODBC connection 'dsn:' concatenated with the DSN, if SQLite the path to the database file. MSSQL ODBC connections may also have a \database_name suffix of the database to initially switch to.
string $username Database username - not used for SQLite
string $password The password for the username specified - not used for SQLite
string $host Database server host or IP, defaults to localhost - not used for SQLite or ODBC connections. MySQL socket connection can be made by entering 'sock:' followed by the socket path. PostgreSQL socket connection can be made by passing just 'sock:'.
integer $port The port to connect to, defaults to the standard port for the database type specified - not used for SQLite or ODBC connections

->__destruct() internal public

Please note: this method is public, however it is primarily intended for internal use by Flourish and will normally not be useful in site/application code

Closes the open database connection

Signature

void __destruct( )

->__get() internal public

Please note: this method is public, however it is primarily intended for internal use by Flourish and will normally not be useful in site/application code

All requests that hit this method should be requests for callbacks

Signature

callback __get( string $method )

Parameters

string $method The method to create a callback for

Returns

The callback for the method requested

->clearCache() public

Clears all of the schema info out of the object and, if set, the fCache object

Signature

void clearCache( )

->determineCharacterSet() protected

Determines the character set of a SQL Server database

Signature

void determineCharacterSet( )

->determineExtension() protected

Figures out which extension to use for the database type selected

Signature

void determineExtension( )

->enableCaching() public

Sets the schema info to be cached to the fCache object specified

Signature

void enableCaching( fCache $cache, string $key_token=NULL )

Parameters

fCache $cache The cache to cache to
string $key_token Internal use only! (this will be used in the cache key to uniquely identify the cache for this fDatabase object)

->enableDebugging() public

Sets if debug messages should be shown

Signature

void enableDebugging( boolean $flag )

Parameters

boolean $flag If debugging messages should be shown

->enableSlowQueryWarnings() public

Sets a flag to trigger a PHP warning message whenever a query takes longer than the millisecond threshold specified

It is recommended to use the error handling features of fCore::enableErrorHandling() to log or email these warnings.

Signature

void enableSlowQueryWarnings( integer $threshold )

Parameters

integer $threshold The limit (in milliseconds) of how long an SQL query can take before a warning is triggered

->escape() public

Escapes a value for insertion into SQL

The valid data types are:

  • 'blob'
  • 'boolean'
  • 'date'
  • 'float'
  • 'identifier'
  • 'integer'
  • 'string' (also varchar, char or text)
  • 'varchar'
  • 'char'
  • 'text'
  • 'time'
  • 'timestamp'

In addition to being able to specify the data type, you can also pass in an SQL statement with data type placeholders in the following form:

  • %l for a blob
  • %b for a boolean
  • %d for a date
  • %f for a float
  • %r for an indentifier (table or column name)
  • %i for an integer
  • %s for a string
  • %t for a time
  • %p for a timestamp

Depending on what $sql_or_type and $value are, the output will be slightly different. If $sql_or_type is a data type or a single placeholder and $value is:

  • a scalar value - an escaped SQL string is returned
  • an array - an array of escaped SQL strings is returned

If $sql_or_type is a SQL string and $value is:

  • a scalar value - the escaped value is inserted into the SQL string
  • an array - the escaped values are inserted into the SQL string separated by commas

If $sql_or_type is a SQL string, it is also possible to pass an array of all values as a single parameter instead of one value per parameter. An example would look like the following:

$db->escape(
    "SELECT * FROM users WHERE status = %s AND authorization_level = %s",
    array('Active', 'Admin')
);

Signature

mixed escape( string $sql_or_type, mixed $value )

Parameters

string $sql_or_type This can either be the data type to escape or an SQL string with a data type placeholder - see method description
mixed $value [, ... ] The value to escape - both single values and arrays of values are supported, see method description for details

Returns

The escaped value/SQL or an array of the escaped values

->execute() public

Executes one or more SQL queries without returning any results

Signature

void execute( string|fStatement $statement, mixed $value )

Parameters

string|fStatement $statement One or more SQL statements in a string or an fStatement prepared statement
mixed $value [, ... ] The optional value(s) to place into any placeholders in the SQL - see escape() for details

->getConnection() public

Returns the database connection resource or object

Signature

mixed getConnection( )

Returns

The database connection

->getDatabase() public

Gets the name of the database currently connected to

Signature

string getDatabase( )

Returns

The name of the database currently connected to

->getExtension() internal public

Please note: this method is public, however it is primarily intended for internal use by Flourish and will normally not be useful in site/application code

Gets the php extension being used

Signature

string getExtension( )

Returns

The php extension used for database interaction

->getHost() public

Gets the host for this database

Signature

string getHost( )

Returns

The host

->getPort() public

Gets the port for this database

Signature

string getPort( )

Returns

The port

->getSQLTranslation() public

Gets the fSQLTranslation object used for translated queries

Signature

fSQLTranslation getSQLTranslation( )

Returns

The SQL translation object

->getType() public

Gets the database type

Signature

string getType( )

Returns

The database type: 'mssql', 'mysql', 'postgresql' or 'sqlite'

->getUsername() public

Gets the username for this database

Signature

string getUsername( )

Returns

The username

->handleError() internal public

Please note: this method is public, however it is primarily intended for internal use by Flourish and will normally not be useful in site/application code

Handles a PHP error to extract error information for the mssql extension

Signature

void handleError( integer $error_number, string $error_string, string $error_file=NULL, integer $error_line=NULL, array $error_context=NULL )

Parameters

integer $error_number The error type
string $error_string The message for the error
string $error_file The file the error occured in
integer $error_line The line the error occured on
array $error_context A references to all variables in scope at the occurence of the error

->inject() internal public

Please note: this method is public, however it is primarily intended for internal use by Flourish and will normally not be useful in site/application code

Injects an fSQLTranslation object to handle translation

Signature

void inject( fSQLTranslation $sql_translation )

Parameters

fSQLTranslation $sql_translation The SQL translation object

->isInsideTransaction() public

Will indicate if a transaction is currently in progress

Signature

boolean isInsideTransaction( )

Returns

If a transaction has been started and not yet rolled back or committed

->prepare() public

Prepares a single fStatement object to execute prepared statements

Identifier placeholders (%r) are not supported with prepared statements. In addition, multiple values can not be escaped by a placeholder - only a single value can be provided.

Signature

fStatement prepare( string $sql )

Parameters

string $sql The SQL to prepare

Returns

A prepared statement object that can be passed to query(), unbufferedQuery() or execute()

->query() public

Executes one or more SQL queries and returns the result(s)

Signature

fResult|array query( string|fStatement $statement, mixed $value )

Parameters

string|fStatement $statement One or more SQL statements in a string or a single fStatement prepared statement
mixed $value [, ... ] The optional value(s) to place into any placeholders in the SQL - see escape() for details

Returns

The fResult object(s) for the query

->translatedExecute() public

Translates one or more SQL statements using fSQLTranslation and executes them without returning any results

Signature

void translatedExecute( string $sql, mixed $value )

Parameters

string $sql One or more SQL statements
mixed $value [, ... ] The optional value(s) to place into any placeholders in the SQL - see escape() for details

->translatedPrepare() public

Translates a SQL statement and creates an fStatement object from it

Identifier placeholders (%r) are not supported with prepared statements. In addition, multiple values can not be escaped by a placeholder - only a single value can be provided.

Signature

fStatement translatedPrepare( string $sql )

Parameters

string $sql The SQL to prepare

Returns

A prepared statement object that can be passed to query(), unbufferedQuery() or execute()

->translatedQuery() public

Translates one or more SQL statements using fSQLTranslation and executes them

Signature

fResult|array translatedQuery( string $sql, mixed $value )

Parameters

string $sql One or more SQL statements
mixed $value [, ... ] The optional value(s) to place into any placeholders in the SQL - see escape() for details

Returns

The fResult object(s) for the query

->unbufferedQuery() public

Executes a single SQL statement in unbuffered mode. This is optimal for

large results sets since it does not load the whole result set into memory first. The gotcha is that only one unbuffered result can exist at one time. If another unbuffered query is executed, the old result will be deleted.

Signature

fUnbufferedResult unbufferedQuery( string|fStatement $statement, mixed $value )

Parameters

string|fStatement $statement A single SQL statement
mixed $value [, ... ] The optional value(s) to place into any placeholders in the SQL - see escape() for details

Returns

The result object for the unbuffered query

->unbufferedTranslatedQuery() public

Translates the SQL statement using fSQLTranslation and then executes it

in unbuffered mode. This is optimal for large results sets since it does not load the whole result set into memory first. The gotcha is that only one unbuffered result can exist at one time. If another unbuffered query is executed, the old result will be deleted.

Signature

fUnbufferedResult unbufferedTranslatedQuery( string $sql, mixed $value )

Parameters

string $sql A single SQL statement
mixed $value [, ... ] The optional value(s) to place into any placeholders in the SQL - see escape() for details

Returns

The result object for the unbuffered query

->unescape() public

Unescapes a value coming out of a database based on its data type

The valid data types are:

  • 'blob' (or '%l')
  • 'boolean' (or '%b')
  • 'date' (or '%d')
  • 'float' (or '%f')
  • 'integer' (or '%i')
  • 'string' (also '%s', 'varchar', 'char' or 'text')
  • 'time' (or '%t')
  • 'timestamp' (or '%p')

Signature

mixed unescape( string $data_type, mixed $value )

Parameters

string $data_type The data type being unescaped - see method description for valid values
mixed $value The value or array of values to unescape

Returns

The unescaped value