Database
class Database
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.
Traits
Methods
Validate integer, optionally include range check.
URL-encode and escape a query string for use in a URL.
Check that a string is comprised solely of alphanumeric characters.
Check that a string is comprised solely of alphanumeric characters and underscores.
Check that a string is comprised solely of alphabetical characters.
Cast to string, check UTF-8 encoding and strip trailing whitespace and control characters.
Enclose table and column identifiers in backticks to escape them.
Close the connection to the database.
Establish a connection to the database.
Create an SQLite database with random prefix and creates a language constant for it.
Create a table in the database.
Delete single row from table based on its ID.
Escape delimiters for identifiers (table and column names).
Insert a single row into the database within a transaction.
Retrieves the ID of the last row inserted into the database.
Return a \PDO statement object.
Count the number of rows matching a set of conditions.
Select results from the database but remove duplicate rows.
Toggle the online status of a column between 0 and 1, use for columns representing booleans.
Increment a content object counter field by one.
Update a single row in the database.
Helper method to set appropriate \PDO predefined constants in bindValue() and bindParam().
Validates the properties of a Criteria object to be used in constructing a query.
Validate and escape column names to be used in constructing a database query.
Validates and sanitises an ID to be used in constructing a database query.
Validate and escapes keys to be used in constructing a database query.
Validate and escape a table name to be used in constructing a database query.
Details
in IntegerCheck at line 39
bool
isInt(int $int, int $min = null, int $max = null)
Validate integer, optionally include range check.
in ValidateString at line 41
string
encodeEscapeUrl(string $url)
URL-encode and escape a query string for use in a URL.
Trims, checks for UTF-8 compliance, rawurlencodes and then escapes with htmlspecialchars(). If you wish to use the data on a landing page you must decode it with htmlspecialchars_decode() followed by rawurldecode() in that order. But really, if you are using any characters that need to be encoded in the first place you should probably just stop.
in ValidateString at line 59
bool
isAlnum(string $alnum)
Check that a string is comprised solely of alphanumeric characters.
Accented regional characters are rejected. This method is designed to be used to check database identifiers or object property names.
in ValidateString at line 77
bool
isAlnumUnderscore(string $alnumUnderscore)
Check that a string is comprised solely of alphanumeric characters and underscores.
Accented regional characters are rejected. This method is designed to be used to check database identifiers or object property names.
in ValidateString at line 95
bool
isAlpha(string $alpha)
Check that a string is comprised solely of alphabetical characters.
Tolerates vanilla ASCII only. Accented regional characters are rejected. This method is designed to be used to check database identifiers or object property names.
in ValidateString at line 113
bool
isUtf8(string $text)
Check if the character encoding of text is UTF-8.
All strings received from external sources must be passed through this function, particularly prior to storage in the database.
in ValidateString at line 131
string
trimString(mixed $text)
Cast to string, check UTF-8 encoding and strip trailing whitespace and control characters.
Removes trailing whitespace and control characters (ASCII <= 32 / UTF-8 points 0-32 inclusive), checks for UTF-8 character set and casts input to a string. Note that the data returned by this function still requires escaping at the point of use; it is not database or XSS safe.
As the input is cast to a string do NOT apply this function to non-string types (int, float, bool, object, resource, null, array, etc).
at line 52
__construct(Logger $logger, FileHandler $fileHandler)
Constructor.
at line 74
string
addBackticks(string $identifier)
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.
at line 84
bool
close()
Close the connection to the database.
at line 98
bool
connect()
Establish a connection to the database.
Connection is deliberately non-persistent (persistence can break things if scripts terminate unexpectedly).
at line 120
string|bool
create(string $dbName)
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
at line 169
bool
createTable(string $table, array $columns, string $primaryKey = null)
Create a table in the database.
Table names may only be alphanumeric characters. Column names are also alphanumeric but may also contain underscores.
at line 258
bool
delete(string $table, int $id)
Delete single row from table based on its ID.
at line 293
bool
deleteAll(string $table, Criteria $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.
at line 362
string
escapeIdentifier(string $identifier)
Escape delimiters for identifiers (table and column names).
SQLite supports three styles of identifier delimitation:
- Standard SQL double quotes: "
- MySQL style grave accents: `
- 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.
at line 384
bool
executeTransaction(PDOStatement $statement)
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).
at line 406
bool
insert(string $table, array $keyValues)
Insert a single row into the database within a transaction.
at line 450
int|bool
lastInsertId()
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.
at line 468
PDOStatement
preparedStatement(string $sql)
Return a \PDO statement object.
Statement object can be used to bind values or parameters and execute queries, thereby mitigating direct SQL injection attacks.
at line 736
PDOStatement
select(string $table, Criteria $criteria = null, array $columns = null)
Prepare and execute a select query.
Returns a \PDO statement object, from which results can be extracted with standard \PDO calls.
at line 832
int|object
selectCount(string $table, Criteria $criteria = null, string $column = '')
Count the number of rows matching a set of conditions.
at line 926
PDOStatement
selectDistinct(string $table, Criteria $criteria = null, array $columns)
Select results from the database but remove duplicate rows.
Use the $columns array to specify which fields you want to filter the results by.
at line 1016
bool
toggleBoolean(int $id, string $table, string $column)
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.
at line 1054
bool
updateCounter(int $id, string $table, string $column)
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.
at line 1088
bool
update(string $table, int $id, array $keyValues)
Update a single row in the database.
at line 1140
updateAll(string $table, array $keyValues, Criteria $criteria = null)
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.
at line 1209
int
setType(mixed $data)
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.
at line 1260
Criteria
validateCriteriaObject(Criteria $criteria)
Validates the properties of a Criteria object to be used in constructing a query.
at line 1355
array
validateColumns(array $columns)
Validate and escape column names to be used in constructing a database query.
at line 1386
int
validateId(int $id)
Validates and sanitises an ID to be used in constructing a database query.
at line 1406
array
validateKeys(array $keyValues)
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.
at line 1437
string
validateTableName(string $tableName)
Validate and escape a table name to be used in constructing a database query.