Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [Versions 402 and 403]

Abstract database driver class.

Copyright: 2008 Petr Skoda (http://skodak.org)
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 2906 lines (120 kb)
Included or required: 8 times
Referenced: 0 times
Includes or requires: 4 files
 lib/dml/moodle_recordset.php
 lib/dml/database_column_info.php
 lib/dml/moodle_transaction.php
 lib/testing/classes/util.php

Defines 1 class

moodle_database:: (118 methods):
  __construct()
  __destruct()
  get_prefix()
  get_driver_instance()
  get_dbvendor()
  get_configuration_hints()
  export_dbconfig()
  diagnose()
  store_settings()
  get_settings_hash()
  get_metacache()
  get_temp_tables_cache()
  create_database()
  get_transaction_start_backtrace()
  dispose()
  query_start()
  query_end()
  query_log()
  query_log_prevent()
  query_log_allow()
  query_time()
  print_debug()
  print_debug_time()
  where_clause()
  where_clause_list()
  get_in_or_equal()
  fix_table_names()
  fix_table_name()
  _fix_sql_params_dollar_callback()
  detect_objects()
  fix_sql_params()
  add_sql_debugging()
  normalise_limit_from_num()
  get_columns()
  reset_caches()
  get_manager()
  change_db_encoding()
  setup_is_unicodedb()
  set_debug()
  get_debug()
  set_logging()
  get_recordset()
  get_recordset_list()
  get_recordset_select()
  export_table_recordset()
  get_records()
  get_records_list()
  get_records_select()
  get_records_menu()
  get_records_select_menu()
  get_records_sql_menu()
  get_record()
  get_record_select()
  get_record_sql()
  get_field()
  get_field_select()
  get_field_sql()
  get_fieldset_select()
  insert_records()
  set_field()
  count_records()
  count_records_select()
  count_records_sql()
  record_exists()
  record_exists_select()
  record_exists_sql()
  delete_records()
  delete_records_list()
  delete_records_subquery()
  sql_null_from_clause()
  sql_bitand()
  sql_bitnot()
  sql_bitor()
  sql_bitxor()
  sql_modulo()
  sql_ceil()
  sql_cast_to_char()
  sql_cast_char2int()
  sql_cast_char2real()
  sql_cast_2signed()
  sql_compare_text()
  sql_equal()
  sql_like()
  sql_like_escape()
  sql_fullname()
  sql_order_by_text()
  sql_order_by_null()
  sql_length()
  sql_substr()
  sql_position()
  sql_empty()
  sql_isempty()
  sql_isnotempty()
  sql_regex_supported()
  sql_regex()
  sql_regex_get_word_beginning_boundary_marker()
  sql_regex_get_word_end_boundary_marker()
  sql_intersect()
  replace_all_text_supported()
  replace_all_text()
  update_temp_table_stats()
  transactions_supported()
  is_transaction_started()
  transactions_forbidden()
  start_delegated_transaction()
  commit_delegated_transaction()
  rollback_delegated_transaction()
  force_transaction_rollback()
  session_lock_supported()
  get_session_lock()
  release_session_lock()
  perf_get_reads()
  want_read_slave()
  perf_get_reads_slave()
  perf_get_writes()
  perf_get_queries()
  perf_get_queries_time()
  is_fulltext_search_supported()


Class: moodle_database  - X-Ref

Abstract class representing moodle database interface.

__construct($external=false)   X-Ref
Constructor - Instantiates the database, specifying if it's external (connect to other systems) or not (Moodle DB).
Note that this affects the decision of whether prefix checks must be performed or not.

param: bool $external True means that an external database is used.

__destruct()   X-Ref
Destructor - cleans up and flushes everything needed.


get_prefix()   X-Ref
Returns database table prefix
Note: can be used before connect()

return: string The prefix used in the database.

get_driver_instance($type, $library, $external = false)   X-Ref
Loads and returns a database instance with the specified type and library.

The loaded class is within lib/dml directory and of the form: $type.'_'.$library.'_moodle_database'

param: string $type Database driver's type. (eg: mysqli, pgsql, mssql, sqldrv, oci, etc.)
param: string $library Database driver's library (native, pdo, etc.)
param: bool $external True if this is an external database.
return: moodle_database driver object or null if error, for example of driver object see {@link mysqli_native_moodle_database}

get_dbvendor()   X-Ref
Returns the database vendor.
Note: can be used before connect()

return: string The db vendor name, usually the same as db family name.

get_configuration_hints()   X-Ref
Returns the localised database description
Note: can be used before connect()

return: string

export_dbconfig()   X-Ref
Returns the db related part of config.php

return: stdClass

diagnose()   X-Ref
Diagnose database and tables, this function is used
to verify database and driver settings, db engine types, etc.

return: string null means everything ok, string means problem found.

store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null)   X-Ref
Store various database settings

param: string $dbhost The database host.
param: string $dbuser The database user to connect as.
param: string $dbpass The password to use when connecting to the database.
param: string $dbname The name of the database being connected to.
param: mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
param: array $dboptions driver specific options
return: void

get_settings_hash()   X-Ref
Returns a hash for the settings used during connection.

If not already requested it is generated and stored in a private property.

return: string

get_metacache()   X-Ref
Handle the creation and caching of the databasemeta information for all databases.

return: cache_application The databasemeta cachestore to complete operations on.

get_temp_tables_cache()   X-Ref
Handle the creation and caching of the temporary tables.

return: cache_application The temp_tables cachestore to complete operations on.

create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null)   X-Ref
Attempt to create the database

param: string $dbhost The database host.
param: string $dbuser The database user to connect as.
param: string $dbpass The password to use when connecting to the database.
param: string $dbname The name of the database being connected to.
param: array $dboptions An array of optional database options (eg: dbport)
return: bool success True for successful connection. False otherwise.

get_transaction_start_backtrace()   X-Ref
Returns transaction trace for debugging purposes.

return: array or null if not in transaction.

dispose()   X-Ref
Closes the database connection and releases all resources
and memory (especially circular memory references).
Do NOT use connect() again, create a new instance if needed.

return: void

query_start($sql, ?array $params, $type, $extrainfo=null)   X-Ref
This should be called before each db query.

param: string $sql The query string.
param: array|null $params An array of parameters.
param: int $type The type of query ( SQL_QUERY_SELECT | SQL_QUERY_AUX_READONLY | SQL_QUERY_AUX |
param: mixed $extrainfo This is here for any driver specific extra information.
return: void

query_end($result)   X-Ref
This should be called immediately after each db query. It does a clean up of resources.
It also throws exceptions if the sql that ran produced errors.

param: mixed $result The db specific result obtained from running a query.
return: void

query_log($error=false)   X-Ref
This logs the last query based on 'logall', 'logslow' and 'logerrors' options configured via $CFG->dboptions .

param: string|bool $error or false if not error
return: void

query_log_prevent()   X-Ref
Disable logging temporarily.


query_log_allow()   X-Ref
Restore old logging behavior.


query_time()   X-Ref
Returns the time elapsed since the query started.

return: float Seconds with microseconds

print_debug($sql, array $params=null, $obj=null)   X-Ref
Prints sql debug info

param: string $sql The query which is being debugged.
param: array $params The query parameters. (optional)
param: mixed $obj The library specific object. (optional)
return: void

print_debug_time()   X-Ref
Prints the time a query took to run.

return: void

where_clause($table, array $conditions=null)   X-Ref
Returns the SQL WHERE conditions.

param: string $table The table name that these conditions will be validated against.
param: array $conditions The conditions to build the where clause. (must not contain numeric indexes)
return: array An array list containing sql 'where' part and 'params'.

where_clause_list($field, array $values)   X-Ref
Returns SQL WHERE conditions for the ..._list group of methods.

param: string $field the name of a field.
param: array $values the values field might take.
return: array An array containing sql 'where' part and 'params'

get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false)   X-Ref
Constructs 'IN()' or '=' sql fragment

param: mixed $items A single value or array of values for the expression.
param: int $type Parameter bounding type : SQL_PARAMS_QM or SQL_PARAMS_NAMED.
param: string $prefix Named parameter placeholder prefix (a unique counter value is appended to each parameter name).
param: bool $equal True means we want to equate to the constructed expression, false means we don't want to equate to it.
param: mixed $onemptyitems This defines the behavior when the array of items provided is empty. Defaults to false,
return: array A list containing the constructed sql fragment and an array of parameters.

fix_table_names($sql)   X-Ref
Converts short table name {tablename} to the real prefixed table name in given sql.

param: string $sql The sql to be operated on.
return: string The sql with tablenames being prefixed with $CFG->prefix

fix_table_name($tablename)   X-Ref
No description

_fix_sql_params_dollar_callback($match)   X-Ref
Internal private utitlity function used to fix parameters.
Used with {@link preg_replace_callback()}

param: array $match Refer to preg_replace_callback usage for description.
return: string

detect_objects($value)   X-Ref
Detects object parameters and throws exception if found

param: mixed $value
return: void

fix_sql_params($sql, array $params=null)   X-Ref
Normalizes sql query parameters and verifies parameters.

param: string $sql The query or part of it.
param: array $params The query parameters.
return: array (sql, params, type of params)

add_sql_debugging(string $sql)   X-Ref
Add an SQL comment to trace all sql calls back to the calling php code

param: string $sql Original sql
return: string Instrumented sql

normalise_limit_from_num($limitfrom, $limitnum)   X-Ref
Ensures that limit params are numeric and positive integers, to be passed to the database.
We explicitly treat null, '' and -1 as 0 in order to provide compatibility with how limit
values have been passed historically.

param: int $limitfrom Where to start results from
param: int $limitnum How many results to return
return: array Normalised limit params in array($limitfrom, $limitnum)

get_columns($table, $usecache = true)   X-Ref
Returns detailed information about columns in table. This information is cached internally.

param: string $table The table's name.
param: bool $usecache Flag to use internal cacheing. The default is true.
return: database_column_info[] of database_column_info objects indexed with column names

reset_caches($tablenames = null)   X-Ref
Resets the internal column details cache

param: array|null $tablenames an array of xmldb table names affected by this request.
return: void

get_manager()   X-Ref
Returns the sql generator used for db manipulation.
Used mostly in upgrade.php scripts.

return: database_manager The instance used to perform ddl operations.

change_db_encoding()   X-Ref
Attempts to change db encoding to UTF-8 encoding if possible.

return: bool True is successful.

setup_is_unicodedb()   X-Ref
Checks to see if the database is in unicode mode?

return: bool

set_debug($state)   X-Ref
Enable/disable very detailed debugging.

param: bool $state
return: void

get_debug()   X-Ref
Returns debug status

return: bool $state

set_logging($state)   X-Ref
Enable/disable detailed sql logging


get_recordset($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)   X-Ref
Get a number of records as a moodle_recordset where all the given conditions met.

Selects records from the table $table.

If specified, only records meeting $conditions.

If specified, the results will be sorted as specified by $sort. This
is added to the SQL as "ORDER BY $sort". Example values of $sort
might be "time ASC" or "time DESC".

If $fields is specified, only those fields are returned.

Since this method is a little less readable, use of it should be restricted to
code where it's possible there might be large datasets being returned.  For known
small datasets use get_records - it leads to simpler code.

If you only want some of the records, specify $limitfrom and $limitnum.
The query will skip the first $limitfrom records (according to the sort
order) and then return the next $limitnum records. If either of $limitfrom
or $limitnum is specified, both must be present.

The return value is a moodle_recordset
if the query succeeds. If an error occurs, false is returned.

param: string $table the table to query.
param: array $conditions optional array $fieldname=>requestedvalue with AND in between
param: string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
param: string $fields a comma separated list of fields to return (optional, by default all fields are returned).
param: int $limitfrom return a subset of records, starting at this point (optional).
param: int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
return: moodle_recordset A moodle_recordset instance

get_recordset_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0)   X-Ref
Get a number of records as a moodle_recordset where one field match one list of values.

Only records where $field takes one of the values $values are returned.
$values must be an array of values.

Other arguments and the return type are like {@link function get_recordset}.

param: string $table the table to query.
param: string $field a field to check (optional).
param: array $values array of values the field must have
param: string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
param: string $fields a comma separated list of fields to return (optional, by default all fields are returned).
param: int $limitfrom return a subset of records, starting at this point (optional).
param: int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
return: moodle_recordset A moodle_recordset instance.

get_recordset_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)   X-Ref
Get a number of records as a moodle_recordset which match a particular WHERE clause.

If given, $select is used as the SELECT parameter in the SQL query,
otherwise all records from the table are returned.

Other arguments and the return type are like {@link function get_recordset}.

param: string $table the table to query.
param: string $select A fragment of SQL to be used in a where clause in the SQL call.
param: array $params array of sql parameters
param: string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
param: string $fields a comma separated list of fields to return (optional, by default all fields are returned).
param: int $limitfrom return a subset of records, starting at this point (optional).
param: int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
return: moodle_recordset A moodle_recordset instance.

export_table_recordset($table)   X-Ref
Get all records from a table.

This method works around potential memory problems and may improve performance,
this method may block access to table until the recordset is closed.

param: string $table Name of database table.
return: moodle_recordset A moodle_recordset instance {@link function get_recordset}.

get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)   X-Ref
Get a number of records as an array of objects where all the given conditions met.

If the query succeeds and returns at least one record, the
return value is an array of objects, one object for each
record found. The array key is the value from the first
column of the result set. The object associated with that key
has a member variable for each column of the results.

param: string $table the table to query.
param: array $conditions optional array $fieldname=>requestedvalue with AND in between
param: string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
param: string $fields a comma separated list of fields to return (optional, by default
param: int $limitfrom return a subset of records, starting at this point (optional).
param: int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
return: array An array of Objects indexed by first column.

get_records_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0)   X-Ref
Get a number of records as an array of objects where one field match one list of values.

Return value is like {@link function get_records}.

param: string $table The database table to be checked against.
param: string $field The field to search
param: array $values An array of values
param: string $sort Sort order (as valid SQL sort parameter)
param: string $fields A comma separated list of fields to be returned from the chosen table. If specified,
param: int $limitfrom return a subset of records, starting at this point (optional).
param: int $limitnum return a subset comprising this many records in total (optional).
return: array An array of objects indexed by first column

get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)   X-Ref
Get a number of records as an array of objects which match a particular WHERE clause.

Return value is like {@link function get_records}.

param: string $table The table to query.
param: string $select A fragment of SQL to be used in a where clause in the SQL call.
param: array $params An array of sql parameters
param: string $sort An order to sort the results in (optional, a valid SQL ORDER BY parameter).
param: string $fields A comma separated list of fields to return
param: int $limitfrom return a subset of records, starting at this point (optional).
param: int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
return: array of objects indexed by first column

get_records_menu($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)   X-Ref
Get the first two columns from a number of records as an associative array where all the given conditions met.

Arguments are like {@link function get_recordset}.

If no errors occur the return value
is an associative whose keys come from the first field of each record,
and whose values are the corresponding second fields.
False is returned if an error occurs.

param: string $table the table to query.
param: array $conditions optional array $fieldname=>requestedvalue with AND in between
param: string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
param: string $fields a comma separated list of fields to return - the number of fields should be 2!
param: int $limitfrom return a subset of records, starting at this point (optional).
param: int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
return: array an associative array

get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)   X-Ref
Get the first two columns from a number of records as an associative array which match a particular WHERE clause.

Arguments are like {@link function get_recordset_select}.
Return value is like {@link function get_records_menu}.

param: string $table The database table to be checked against.
param: string $select A fragment of SQL to be used in a where clause in the SQL call.
param: array $params array of sql parameters
param: string $sort Sort order (optional) - a valid SQL order parameter
param: string $fields A comma separated list of fields to be returned from the chosen table - the number of fields should be 2!
param: int $limitfrom return a subset of records, starting at this point (optional).
param: int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
return: array an associative array

get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0)   X-Ref
Get the first two columns from a number of records as an associative array using a SQL statement.

Arguments are like {@link function get_recordset_sql}.
Return value is like {@link function get_records_menu}.

param: string $sql The SQL string you wish to be executed.
param: array $params array of sql parameters
param: int $limitfrom return a subset of records, starting at this point (optional).
param: int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
return: array an associative array

get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING)   X-Ref
Get a single database record as an object where all the given conditions met.

param: string $table The table to select from.
param: array $conditions optional array $fieldname=>requestedvalue with AND in between
param: string $fields A comma separated list of fields to be returned from the chosen table.
param: int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
return: mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode

get_record_select($table, $select, array $params=null, $fields='*', $strictness=IGNORE_MISSING)   X-Ref
Get a single database record as an object which match a particular WHERE clause.

param: string $table The database table to be checked against.
param: string $select A fragment of SQL to be used in a where clause in the SQL call.
param: array $params array of sql parameters
param: string $fields A comma separated list of fields to be returned from the chosen table.
param: int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
return: stdClass|false a fieldset object containing the first matching record, false or exception if error not found depending on mode

get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING)   X-Ref
Get a single database record as an object using a SQL statement.

The SQL statement should normally only return one record.
It is recommended to use get_records_sql() if more matches possible!

param: string $sql The SQL string you wish to be executed, should normally only return one record.
param: array $params array of sql parameters
param: int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
return: mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode

get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING)   X-Ref
Get a single field value from a table record where all the given conditions met.

param: string $table the table to query.
param: string $return the field to return the value of.
param: array $conditions optional array $fieldname=>requestedvalue with AND in between
param: int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
return: mixed the specified value false if not found

get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING)   X-Ref
Get a single field value from a table record which match a particular WHERE clause.

param: string $table the table to query.
param: string $return the field to return the value of.
param: string $select A fragment of SQL to be used in a where clause returning one row with one column
param: array $params array of sql parameters
param: int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
return: mixed the specified value false if not found

get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING)   X-Ref
Get a single field value (first field) using a SQL statement.

param: string $sql The SQL query returning one row with one column
param: array $params array of sql parameters
param: int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
return: mixed the specified value false if not found

get_fieldset_select($table, $return, $select, array $params=null)   X-Ref
Selects records and return values of chosen field as an array which match a particular WHERE clause.

param: string $table the table to query.
param: string $return the field we are intered in
param: string $select A fragment of SQL to be used in a where clause in the SQL call.
param: array $params array of sql parameters
return: array of values

insert_records($table, $dataobjects)   X-Ref
Insert multiple records into database as fast as possible.

Order of inserts is maintained, but the operation is not atomic,
use transactions if necessary.

This method is intended for inserting of large number of small objects,
do not use for huge objects with text or binary fields.

param: string $table  The database table to be inserted into
param: array|Traversable $dataobjects list of objects to be inserted, must be compatible with foreach
return: void does not return new record ids

set_field($table, $newfield, $newvalue, array $conditions=null)   X-Ref
Set a single field in every table record where all the given conditions met.

param: string $table The database table to be checked against.
param: string $newfield the field to set.
param: mixed $newvalue the value to set the field to.
param: array $conditions optional array $fieldname=>requestedvalue with AND in between
return: bool true

count_records($table, array $conditions=null)   X-Ref
Count the records in a table where all the given conditions met.

param: string $table The table to query.
param: array $conditions optional array $fieldname=>requestedvalue with AND in between
return: int The count of records returned from the specified criteria.

count_records_select($table, $select, array $params=null, $countitem="COUNT('x')   X-Ref
Count the records in a table which match a particular WHERE clause.

param: string $table The database table to be checked against.
param: string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
param: array $params array of sql parameters
param: string $countitem The count string to be used in the SQL call. Default is COUNT('x').
return: int The count of records returned from the specified criteria.

count_records_sql($sql, array $params=null)   X-Ref
Get the result of a SQL SELECT COUNT(...) query.

Given a query that counts rows, return that count. (In fact,
given any query, return the first field of the first record
returned. However, this method should only be used for the
intended purpose.) If an error occurs, 0 is returned.

param: string $sql The SQL string you wish to be executed.
param: array $params array of sql parameters
return: int the count

record_exists($table, array $conditions)   X-Ref
Test whether a record exists in a table where all the given conditions met.

param: string $table The table to check.
param: array $conditions optional array $fieldname=>requestedvalue with AND in between
return: bool true if a matching record exists, else false.

record_exists_select($table, $select, array $params=null)   X-Ref
Test whether any records exists in a table which match a particular WHERE clause.

param: string $table The database table to be checked against.
param: string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
param: array $params array of sql parameters
return: bool true if a matching record exists, else false.

record_exists_sql($sql, array $params=null)   X-Ref
Test whether a SQL SELECT statement returns any records.

This function returns true if the SQL statement executes
without any errors and returns at least one record.

param: string $sql The SQL statement to execute.
param: array $params array of sql parameters
return: bool true if the SQL executes without errors and returns at least one record.

delete_records($table, array $conditions=null)   X-Ref
Delete the records from a table where all the given conditions met.
If conditions not specified, table is truncated.

param: string $table the table to delete from.
param: array $conditions optional array $fieldname=>requestedvalue with AND in between
return: bool true.

delete_records_list($table, $field, array $values)   X-Ref
Delete the records from a table where one field match one list of values.

param: string $table the table to delete from.
param: string $field The field to search
param: array $values array of values
return: bool true.

delete_records_subquery(string $table, string $field, string $alias,string $subquery, array $params = [])   X-Ref
Deletes records from a table using a subquery. The subquery should return a list of values
in a single column, which match one field from the table being deleted.

The $alias parameter must be set to the name of the single column in your subquery result
(e.g. if the subquery is 'SELECT id FROM whatever', then it should be 'id'). This is not
needed on most databases, but MySQL requires it.

(On database where the subquery is inefficient, it is implemented differently.)

param: string $table Table to delete from
param: string $field Field in table to match
param: string $alias Name of single column in subquery e.g. 'id'
param: string $subquery Subquery that will return values of the field to delete
param: array $params Parameters for subquery

sql_null_from_clause()   X-Ref
Returns the FROM clause required by some DBs in all SELECT statements.

To be used in queries not having FROM clause to provide cross_db
Most DBs don't need it, hence the default is ''
return: string

sql_bitand($int1, $int2)   X-Ref
Returns the SQL text to be used in order to perform one bitwise AND operation
between 2 integers.

NOTE: The SQL result is a number and can not be used directly in
SQL condition, please compare it to some number to get a bool!!

param: string $int1 SQL for the first integer in the operation.
param: string $int2 SQL for the second integer in the operation.
return: string The piece of SQL code to be used in your statement.

sql_bitnot($int1)   X-Ref
Returns the SQL text to be used in order to perform one bitwise NOT operation
with 1 integer.

param: int $int1 The operand integer in the operation.
return: string The piece of SQL code to be used in your statement.

sql_bitor($int1, $int2)   X-Ref
Returns the SQL text to be used in order to perform one bitwise OR operation
between 2 integers.

NOTE: The SQL result is a number and can not be used directly in
SQL condition, please compare it to some number to get a bool!!

param: int $int1 The first operand integer in the operation.
param: int $int2 The second operand integer in the operation.
return: string The piece of SQL code to be used in your statement.

sql_bitxor($int1, $int2)   X-Ref
Returns the SQL text to be used in order to perform one bitwise XOR operation
between 2 integers.

NOTE: The SQL result is a number and can not be used directly in
SQL condition, please compare it to some number to get a bool!!

param: int $int1 The first operand integer in the operation.
param: int $int2 The second operand integer in the operation.
return: string The piece of SQL code to be used in your statement.

sql_modulo($int1, $int2)   X-Ref
Returns the SQL text to be used in order to perform module '%'
operation - remainder after division

param: int $int1 The first operand integer in the operation.
param: int $int2 The second operand integer in the operation.
return: string The piece of SQL code to be used in your statement.

sql_ceil($fieldname)   X-Ref
Returns the cross db correct CEIL (ceiling) expression applied to fieldname.
note: Most DBs use CEIL(), hence it's the default here.

param: string $fieldname The field (or expression) we are going to ceil.
return: string The piece of SQL code to be used in your ceiling statement.

sql_cast_to_char(string $field)   X-Ref
Return SQL for casting to char of given field/expression. Default implementation performs implicit cast using
concatenation with an empty string

param: string $field Table field or SQL expression to be cast
return: string

sql_cast_char2int($fieldname, $text=false)   X-Ref
Returns the SQL to be used in order to CAST one CHAR column to INTEGER.

Be aware that the CHAR column you're trying to cast contains really
int values or the RDBMS will throw an error!

param: string $fieldname The name of the field to be casted.
param: bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
return: string The piece of SQL code to be used in your statement.

sql_cast_char2real($fieldname, $text=false)   X-Ref
Returns the SQL to be used in order to CAST one CHAR column to REAL number.

Be aware that the CHAR column you're trying to cast contains really
numbers or the RDBMS will throw an error!

param: string $fieldname The name of the field to be casted.
param: bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
return: string The piece of SQL code to be used in your statement.

sql_cast_2signed($fieldname)   X-Ref
Returns the SQL to be used in order to an UNSIGNED INTEGER column to SIGNED.

(Only MySQL needs this. MySQL things that 1 * -1 = 18446744073709551615
if the 1 comes from an unsigned column).

param: string $fieldname The name of the field to be cast
return: string The piece of SQL code to be used in your statement.

sql_compare_text($fieldname, $numchars=32)   X-Ref
Returns the SQL text to be used to compare one TEXT (clob) column with
one varchar column, because some RDBMS doesn't support such direct
comparisons.

param: string $fieldname The name of the TEXT field we need to order by
param: int $numchars Number of chars to use for the ordering (defaults to 32).
return: string The piece of SQL code to be used in your statement.

sql_equal($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notequal = false)   X-Ref
Returns an equal (=) or not equal (<>) part of a query.

Note the use of this method may lead to slower queries (full scans) so
use it only when needed and against already reduced data sets.

param: string $fieldname Usually the name of the table column.
param: string $param Usually the bound query parameter (?, :named).
param: bool $casesensitive Use case sensitive search when set to true (default).
param: bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
param: bool $notequal True means not equal (<>)
return: string The SQL code fragment.

sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\')   X-Ref
Returns 'LIKE' part of a query.

param: string $fieldname Usually the name of the table column.
param: string $param Usually the bound query parameter (?, :named).
param: bool $casesensitive Use case sensitive search when set to true (default).
param: bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
param: bool $notlike True means "NOT LIKE".
param: string $escapechar The escape char for '%' and '_'.
return: string The SQL code fragment.

sql_like_escape($text, $escapechar = '\\')   X-Ref
Escape sql LIKE special characters like '_' or '%'.

param: string $text The string containing characters needing escaping.
param: string $escapechar The desired escape character, defaults to '\\'.
return: string The escaped sql LIKE string.

sql_fullname($first='firstname', $last='lastname')   X-Ref
Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname

param: string $first User's first name (default:'firstname').
param: string $last User's last name (default:'lastname').
return: string The SQL to concatenate strings.

sql_order_by_text($fieldname, $numchars=32)   X-Ref
Returns the SQL text to be used to order by one TEXT (clob) column, because
some RDBMS doesn't support direct ordering of such fields.

Note that the use or queries being ordered by TEXT columns must be minimised,
because it's really slooooooow.

param: string $fieldname The name of the TEXT field we need to order by.
param: int $numchars The number of chars to use for the ordering (defaults to 32).
return: string The piece of SQL code to be used in your statement.

sql_order_by_null(string $fieldname, int $sort = SORT_ASC)   X-Ref
Returns the SQL text to be used to order by columns, standardising the return
pattern of null values across database types to sort nulls first when ascending
and last when descending.

param: string $fieldname The name of the field we need to sort by.
param: int $sort An order to sort the results in.
return: string The piece of SQL code to be used in your statement.

sql_length($fieldname)   X-Ref
Returns the SQL text to be used to calculate the length in characters of one expression.

param: string $fieldname The fieldname/expression to calculate its length in characters.
return: string the piece of SQL code to be used in the statement.

sql_substr($expr, $start, $length=false)   X-Ref
Returns the proper substr() SQL text used to extract substrings from DB
NOTE: this was originally returning only function name

param: string $expr Some string field, no aggregates.
param: mixed $start Integer or expression evaluating to integer (1 based value; first char has index 1)
param: mixed $length Optional integer or expression evaluating to integer.
return: string The sql substring extraction fragment.

sql_position($needle, $haystack)   X-Ref
Returns the SQL for returning searching one string for the location of another.

Note, there is no guarantee which order $needle, $haystack will be in
the resulting SQL so when using this method, and both arguments contain
placeholders, you should use named placeholders.

param: string $needle the SQL expression that will be searched for.
param: string $haystack the SQL expression that will be searched in.
return: string The required searching SQL part.

sql_empty()   X-Ref
This used to return empty string replacement character.

return: string An empty string.

sql_isempty($tablename, $fieldname, $nullablefield, $textfield)   X-Ref
Returns the proper SQL to know if one field is empty.

Note that the function behavior strongly relies on the
parameters passed describing the field so, please,  be accurate
when specifying them.

Also, note that this function is not suitable to look for
fields having NULL contents at all. It's all for empty values!

This function should be applied in all the places where conditions of
the type:

... AND fieldname = '';

are being used. Final result for text fields should be:

... AND ' . sql_isempty('tablename', 'fieldname', true/false, true);

and for varchar fields result should be:

... AND fieldname = :empty; "; $params['empty'] = '';

(see parameters description below)

param: string $tablename Name of the table (without prefix). Not used for now but can be
param: string $fieldname Name of the field we are going to check
param: bool $nullablefield For specifying if the field is nullable (true) or no (false) in the DB.
param: bool $textfield For specifying if it is a text (also called clob) field (true) or a varchar one (false)
return: string the sql code to be added to check for empty values

sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield)   X-Ref
Returns the proper SQL to know if one field is not empty.

Note that the function behavior strongly relies on the
parameters passed describing the field so, please,  be accurate
when specifying them.

This function should be applied in all the places where conditions of
the type:

... AND fieldname != '';

are being used. Final result for text fields should be:

... AND ' . sql_isnotempty('tablename', 'fieldname', true/false, true/false);

and for varchar fields result should be:

... AND fieldname != :empty; "; $params['empty'] = '';

(see parameters description below)

param: string $tablename Name of the table (without prefix). This is not used for now but can be
param: string $fieldname The name of the field we are going to check.
param: bool $nullablefield Specifies if the field is nullable (true) or not (false) in the DB.
param: bool $textfield Specifies if it is a text (also called clob) field (true) or a varchar one (false).
return: string The sql code to be added to check for non empty values.

sql_regex_supported()   X-Ref
Returns true if this database driver supports regex syntax when searching.

return: bool True if supported.

sql_regex($positivematch = true, $casesensitive = false)   X-Ref
Returns the driver specific syntax (SQL part) for matching regex positively or negatively (inverted matching).
Eg: 'REGEXP':'NOT REGEXP' or '~*' : '!~*'

param: bool $positivematch
param: bool $casesensitive
return: string or empty if not supported

sql_regex_get_word_beginning_boundary_marker()   X-Ref
Returns the word-beginning boundary marker if this database driver supports regex syntax when searching.

return: string The word-beginning boundary marker. Otherwise, an empty string.

sql_regex_get_word_end_boundary_marker()   X-Ref
Returns the word-end boundary marker if this database driver supports regex syntax when searching.

return: string The word-end boundary marker. Otherwise, an empty string.

sql_intersect($selects, $fields)   X-Ref
Returns the SQL that allows to find intersection of two or more queries

param: array $selects array of SQL select queries, each of them only returns fields with the names from $fields
param: string $fields comma-separated list of fields (used only by some DB engines)
return: string SQL query that will return only values that are present in each of selects

replace_all_text_supported()   X-Ref
Does this driver support tool_replace?

return: bool

replace_all_text($table, database_column_info $column, $search, $replace)   X-Ref
Replace given text in all rows of column.

param: string $table name of the table
param: database_column_info $column
param: string $search
param: string $replace

update_temp_table_stats()   X-Ref
Analyze the data in temporary tables to force statistics collection after bulk data loads.

return: void

transactions_supported()   X-Ref
Checks and returns true if transactions are supported.

It is not responsible to run productions servers
on databases without transaction support ;-)

Override in driver if needed.

return: bool

is_transaction_started()   X-Ref
Returns true if a transaction is in progress.

return: bool

transactions_forbidden()   X-Ref
This is a test that throws an exception if transaction in progress.
This test does not force rollback of active transactions.

return: void

start_delegated_transaction()   X-Ref
On DBs that support it, switch to transaction mode and begin a transaction
you'll need to ensure you call allow_commit() on the returned object
or your changes *will* be lost.

this is _very_ useful for massive updates

Delegated database transactions can be nested, but only one actual database
transaction is used for the outer-most delegated transaction. This method
returns a transaction object which you should keep until the end of the
delegated transaction. The actual database transaction will
only be committed if all the nested delegated transactions commit
successfully. If any part of the transaction rolls back then the whole
thing is rolled back.

return: moodle_transaction

commit_delegated_transaction(moodle_transaction $transaction)   X-Ref
Indicates delegated transaction finished successfully.
The real database transaction is committed only if
all delegated transactions committed.

param: moodle_transaction $transaction The transaction to commit
return: void

rollback_delegated_transaction(moodle_transaction $transaction, $e)   X-Ref
Call when delegated transaction failed, this rolls back
all delegated transactions up to the top most level.

In many cases you do not need to call this method manually,
because all open delegated transactions are rolled back
automatically if exceptions not caught.

param: moodle_transaction $transaction An instance of a moodle_transaction.
param: Exception|Throwable $e The related exception/throwable to this transaction rollback.
return: void This does not return, instead the exception passed in will be rethrown.

force_transaction_rollback()   X-Ref
Force rollback of all delegated transaction.
Does not throw any exceptions and does not log anything.

This method should be used only from default exception handlers and other
core code.

return: void

session_lock_supported()   X-Ref
Is session lock supported in this driver?

return: bool

get_session_lock($rowid, $timeout)   X-Ref
Obtains the session lock.

param: int $rowid The id of the row with session record.
param: int $timeout The maximum allowed time to wait for the lock in seconds.
return: void

release_session_lock($rowid)   X-Ref
Releases the session lock.

param: int $rowid The id of the row with session record.
return: void

perf_get_reads()   X-Ref
Returns the number of reads done by this database.

return: int Number of reads.

want_read_slave()   X-Ref
Returns whether we want to connect to slave database for read queries.

return: bool Want read only connection

perf_get_reads_slave()   X-Ref
Returns the number of reads before first write done by this database.

return: int Number of reads.

perf_get_writes()   X-Ref
Returns the number of writes done by this database.

return: int Number of writes.

perf_get_queries()   X-Ref
Returns the number of queries done by this database.

return: int Number of queries.

perf_get_queries_time()   X-Ref
Time waiting for the database engine to finish running all queries.

return: float Number of seconds with microseconds

is_fulltext_search_supported()   X-Ref
Whether the database is able to support full-text search or not.

return: bool