Tuskfish API V1.1.1
  • Package
  • Class

Packages

  • content
  • core
  • database
  • installation
  • security
  • user
  • utilities

Classes

  • TfCriteria
  • TfCriteriaFactory
  • TfCriteriaItem
  • TfDatabase

Class TfDatabase

Tuskfish database handler class, implements PDO and exclusively uses prepared statements.

Prepared statements with bound values are used to mitigate SQL injection attacks. Table and column identifiers are also escaped. However, you should have thoroughly validated and range checked data before it reaches this class.

Package: database
Copyright: Simon Wilkinson 2013+ (https://tuskfish.biz)
License: GNU General Public License (GPL) V2
Author: Simon Wilkinson simon@isengard.biz
Version: Release: 1.0
Since: 1.0
Var: PDO $_db Instance of the PDO base class.
Var: TfValidator $validator Instance of the Tuskfish data validator.
Var: TfFileHandler $fileHandler Instance of the Tuskfish file handler.
Var: TfLogger $logger Instance of the Tuskfish error logger.
Located at trust_path/libraries/tuskfish/class/TfDatabase.php

Methods summary

public
# __construct( TfValidator $validator, TfLogger $logger, TfFileHandler $fileHandler )

Parameters

$validator
An instance of the Tuskfish data validator class.
$logger
An instance of the Tuskfish error logger class.
$fileHandler
An instance of the Tuskfish file handler class.
public string
# addBackticks( string $identifier )

Enclose table and column identifiers in backticks to escape them.

Enclose table and column identifiers in backticks to escape them.

This method must only be used on TABLE and COLUMN names. Column values must be escaped through the use of bound parameters.

Parameters

$identifier
Table or column name.

Returns

string
Identifier encapsulated in backticks.
public boolean
# close( )

Close the connection to the database.

Close the connection to the database.

Returns

boolean
True on success false on failure.
public boolean
# connect( )

Establish a connection to the database.

Establish a connection to the database.

Connection is deliberately non-persistent (persistence can break things if scripts terminate unexpectedly).

Returns

boolean
True on success, false on failure.
public string|boolean
# create( string $dbName )

Create an SQLite database with random prefix and creates a language constant for it.

Create an SQLite database with random prefix and creates a language constant for it.

Database name must be alphanumeric and underscore characters only. The database will automatically be appended with the suffix .db

Parameters

$dbName
Database name.

Returns

string|boolean
Path to database file on success, false on failure.
public boolean
# createTable( string $table, array $columns, string $primaryKey = null )

Create a table in the database.

Create a table in the database.

Table names may only be alphanumeric characters. Column names are also alphanumeric but may also contain underscores.

Parameters

$table
Table name (alphanumeric characters only).
$columns
Array of column names (keys) and types (values).
$primaryKey
Name of field to be used as primary key.

Returns

boolean
True on success, false on failure.
public boolean
# delete( string $table, integer $id )

Delete single row from table based on its ID.

Delete single row from table based on its ID.

Parameters

$table
Name of table.
$id
ID of row to be deleted.

Returns

boolean
True on success false on failure.
public boolean
# deleteAll( string $table, TfCriteria $criteria )

Delete multiple rows from a table according to criteria.

Delete multiple rows from a table according to criteria.

For safety reasons criteria are required; the function will not unconditionally empty table. Note that SQLite does not support DELETE with INNER JOIN or table alias. Therefore, you cannot use tags as a criteria in deleteAll() (they will simply be ignored). It may be possible to get around this restriction with a loop or subquery.

Parameters

$table
Name of table.
$criteria
TfCriteria object used to build conditional database query.

Returns

boolean
True on success, false on failure.
public string
# escapeIdentifier( string $identifier )

Escape delimiters for identifiers (table and column names).

Escape delimiters for identifiers (table and column names).

SQLite supports three styles of identifier delimitation:

  1. Standard SQL double quotes: "
  2. MySQL style grave accents: `
  3. MS SQL style square brackets: []

Escaping of delimiters where they are used as part of a table or column name is done by doubling them, eg ` becomes ``. In order to safely escape table and column names ALL three delimiter types must be escaped.

Tuskfish policy is that table names can only contain alphanumeric characters (and column names can only contain alphanumeric plus underscore characters) so delimiters should never get into a query as part of an identifier. But just because we are paranoid they are escaped here anyway.

Parameters

$identifier
Name of table or column.

Returns

string
Escaped table or column name.
public boolean
# executeTransaction( object $statement )

Execute a prepared statement within a transaction.

Execute a prepared statement within a transaction.

The $statement parameter should be a prepared statement obtained via preparedStatement($sql). Note that statement execution is within a transaction and rollback will occur if it fails. This method should be used with database write operations (INSERT, UPDATE, DELETE).

Parameters

$statement
Prepared statement.

Returns

boolean
True on success, false on failure.
public boolean
# insert( string $table, array $keyValues )

Insert a single row into the database within a transaction.

Insert a single row into the database within a transaction.

Parameters

$table
Name of table.
$keyValues
Column names and values to be inserted.

Returns

boolean
True on success, false on failure.
public integer|boolean
# lastInsertId( )

Retrieves the ID of the last row inserted into the database.

Retrieves the ID of the last row inserted into the database.

Used primarily to grab the ID of newly created content objects so that their accompanying taglinks can be correctly associated to them.

Returns

integer|boolean
Row ID on success, false on failure.
public object
# preparedStatement( string $sql )

Return a PDO statement object.

Return a PDO statement object.

Statement object can be used to bind values or parameters and execute queries, thereby mitigating direct SQL injection attacks.

Parameters

$sql
SQL statement.

Returns

object
PDOStatement object on success PDOException object on failure.
public object
# select( string $table, TfCriteria $criteria = null, array $columns = null )

Prepare and execute a select query.

Prepare and execute a select query.

Returns a PDO statement object, from which results can be extracted with standard PDO calls.

Parameters

$table
Name of table.
$criteria
Query composer object used to build conditional database query.
$columns
Names of database columns to be selected.

Returns

object
PDOStatement object on success PDOException on failure.
public integer|object
# selectCount( string $table, TfCriteria $criteria = null, string $column = '' )

Count the number of rows matching a set of conditions.

Count the number of rows matching a set of conditions.

Parameters

$table
Name of table.
$criteria
Query composer object used to build conditional database query.
$column
Name of column.

Returns

integer|object
Row count on success, PDOException object on failure.
public object
# selectDistinct( string $table, TfCriteria $criteria, array $columns )

Select results from the database but remove duplicate rows.

Select results from the database but remove duplicate rows.

Use the $columns array to specify which fields you want to filter the results by.

Parameters

$table
Name of table.
$criteria
Query composer object used to build conditional database query.
$columns
Name of columns to filter results by.

Returns

object
PDOStatement on success, PDOException on failure.
public boolean
# toggleBoolean( integer $id, string $table, string $column )

Toggle the online status of a column between 0 and 1, use for columns representing booleans.

Toggle the online status of a column between 0 and 1, use for columns representing booleans.

Note that the $id MUST represent a column called ID for whatever table you want to run it on.

Parameters

$id
ID of the row to update.
$table
Name of table.
$column
Name of column to update.

Returns

boolean
True on success, false on failure.
public boolean
# updateCounter( integer $id, string $table, string $column )

Increment a content object counter field by one.

Increment a content object counter field by one.

Call this method when the full description of an individual content object is viewed, or when a related media file is downloaded.

Parameters

$id
ID of content object.
$table
Name of table.
$column
Name of column.

Returns

boolean
True on success false on failure.
public boolean
# update( string $table, integer $id, array $keyValues )

Update a single row in the database.

Update a single row in the database.

Parameters

$table
Name of table.
$id
ID of row to update.
$keyValues
Array of column names and values to update.

Returns

boolean
True on success, false on failure.
public
# updateAll( string $table, array $keyValues, TfCriteria $criteria = null )

Update multiple rows in a table according to criteria.

Update multiple rows in a table according to criteria.

Note that SQLite does not support INNER JOIN or table aliases in UPDATE; therefore it is not possible to use tags as a criteria in updateAll() at present. It may be possible to get around this limitation with a subquery. But given that the use case would be unusual / marginal it is probably just easier to work around it.

Parameters

$table
Name of table.
$keyValues
Array of column names and values to update.
$criteria
Query composer object used to build conditional database query.
public integer
# setType( mixed $data )

Helper method to set appropriate PDO predefined constants in bindValue() and bindParam().

Helper method to set appropriate PDO predefined constants in bindValue() and bindParam().

Do not use this method for arrays, objects or resources. Note that if you pass in an unexpected data type (ie. one that clashes with a column type definition) PDO will throw an error.

Parameters

$data
Input data to be type set.

Returns

integer
PDO data type constant.
public TfCriteria
# validateCriteriaObject( TfCriteria $criteria )

Validates the properties of a TfCriteria object to be used in constructing a query.

Validates the properties of a TfCriteria object to be used in constructing a query.

Parameters

$criteria
Query composer object.

Returns

TfCriteria
Validated TfCriteria object.
public array
# validateColumns( array $columns )

Validate and escape column names to be used in constructing a database query.

Validate and escape column names to be used in constructing a database query.

Parameters

$columns
Array of unescaped column names.

Returns

array
Array of valid, escaped column names
public integer
# validateId( integer $id )

Validates and sanitises an ID to be used in constructing a database query.

Validates and sanitises an ID to be used in constructing a database query.

Parameters

$id
Input ID to be tested.

Returns

integer
$id Validated ID.
public array
# validateKeys( array $keyValues )

Validate and escapes keys to be used in constructing a database query.

Validate and escapes keys to be used in constructing a database query.

Keys may only consist of alphanumeric and underscore characters. SQLite identifier delimiters are escaped.

Parameters

$keyValues
Array of unescaped keys.

Returns

array
Array of valid and escaped keys.
public string
# validateTableName( string $tableName )

Validate and escape a table name to be used in constructing a database query.

Validate and escape a table name to be used in constructing a database query.

Parameters

$tableName
Table name to be checked.

Returns

string
Valid and escaped table name.
Tuskfish API V1.1.1 API documentation generated by ApiGen