Sql
Allows the use of different database servers, while provides unified code base and error handling.
The sql module uses php pdo extension,
thus your php have to the PDO installed.
The main functions of sql module is:
- Manage of sql connect/disconnect
- Execute sql commands
- Manage transactions
- Sql error handling
- Manage sql schema/other module requirements
Sql database settings
In order to connect an sql database you have to place the appropriate
connection settings to site settings in _settings.php
global $db;
//mandatory to connect:
$db->servertype = "mysql";
$db->host = "127.0.0.1";
$db->name = "web_example_db";
$db->user = "web_db_user";
$db->password = "secretpass1";
//optional settings:
$db->sqlencoding = "utf8";
$db->schema_editor_password = "secretpass2"; //empty means disabled!
$db->schema_editor_allowed_for_admin = true;
//$db->schema_editor_allowed_only_for_login = 'superadmin';
Mandatory settings
$db->servertype
- Specifies the server type. Possible values:
- "mysql" - to connect mysql or mariadb
- "pgsql" - to connect postgresql
- "none" - to disable sql connection
- Specifies the server type. Possible values:
$db->host
- The hostname or IP address where the sql database is available
$db->name
- The name of the database on the sql server
$db->user
- The username to connect
$db->password
- The password for the specified user
Optional settings
$db->sqlencoding
- Runs
SET NAMES sqlencoding;
sql command to set the connection encoding immediately after database connect. - If not set the default is empty string, which bypass running of
SET NAMES
.
- Runs
$db->schema_editor_password
- Specifies a password for the schema editor page. Empty string will disable of accessing this page with password. (See next setting)
$db->schema_editor_allowed_for_admin
- If this value is set true an authenticated admin user can access the schema editor page without any further password.
$db->schema_editor_allowed_only_for_login
- If this value is set, only the user with the specified login can access the schema editor page without any further password. (Have to enable the
$db->schema_editor_allowed_for_admin
)
- If this value is set, only the user with the specified login can access the schema editor page without any further password. (Have to enable the
Connect and disconnect
Before first time connect to an sql database please check your php have the appropriate sql driver available!
If your sql setting are correctly set in _settings.php
the CodKep will automatically connect
to the specified database. It means that usually does not need to explicit call connect and disconnect function!
Connect to the sql database
sql_connect()
Disconnects the current opened database
sql_disconnect()
The connect and disconnect functions does not have parameters. The connection is done according to the settings
(see above).
If the connection is failed the execution is automatically redirected to
the sql_connection_error
sql error handling
location, which print the sql error message by default.
An sql connection error as looks in a browser:
You can test if a database opened or by checking the value of $db->open
variable. Usually does not necessary to
check this, because all further sql related functions will done this, or do correct error handling.
Note: On successful sql connect the HOOK_sql_connected
hook is activated
Execute SQL commands
You can execute arbitrary sql command by the following functions in this section or you use the general database CRUD interface described later. These functions here are "low level" sql functions they almost directly pass the sql commands to the underlying driver interface.
sql_exec($sql,array $parameters = [],$errormsg = '')
$sql
parameter- The prepared sql statement to run. It can accept named placeholders.
$parameters
parameter- An array of values to substitute into the query. If the query uses placeholders, this is an associative array in any order.
$errormsg
parameter- An optional custom error message, which printed on sql error handling page when the execution failed by any reason.
This function returns an executed pdo object. See php pdo documentation
$r1 = sql_exec('SELECT name FROM users;');
$login = 'alice';
$r2 = sql_exec('SELECT name FROM users WHERE login=:login;' , [':login' => $login] );
$secret = 'secretpassword';
sql_exec('UPDATE users SET pwd=:password WHERE login=:login;',
[':login' => $login,
':password' => $secret],
'Cannot set the password');
In case of error occurred the function returns NULL. Usually does not need to do error handling because the function do automatically.
See error handling section to learn how to handle errors.
sql_exec_noredirect($sql,array $parameters = [])
Same function as sql_exec
but never do any redirection in case of error.
Useful when sql used in some special hooks where the redirection is not possible or would create a loop.
sql_exec_fetch($sql,array $parameters = [],$errormsg = '')
Executes and fetch an sql command. The parameters and the error handle works similar way as sql_exec the only difference is that this function calls fetch on the executed statement, consequently returns an array instead of pdo object.
It returns an executed and fetched php array. (An associative array of the first record of the result)
$arr = sql_exec_fetch('SELECT name FROM users WHERE login=:login;' , [':login' => $login] );
print "Name:".$arr['name'];
This function raise error when the result is empty. (In the example above, when the $login is not found
in users table the function will fail) If you would like to allow the empty result use the
sql_exec_fetchN
instead of this.
See error handling section to learn how to handle errors.
sql_exec_fetchN($sql,array $parameters = [],$errormsg = '')
Executes and fetch an sql command. The parameters and the error handle works similar way as sql_exec the only difference is that this function calls fetch on the executed statement, consequently returns an array instead of pdo object. Allows empty result. It returns an executed and fetched array.
$arr = sql_exec_fetch('SELECT name FROM users WHERE login=:login;' , [':login' => $login] );
print "Name:". (empty($arr) ? "Unknown" : $arr['name']);
See error handling section to learn how to handle errors.
sql_exec_single($sql,array $parameters = [],$errormsg = '')
Executes and fetch an sql command and returns the first field of the first received record. It returns a single value. This function is useful if a single value is queried from the database.
print "Time:";
print sql_exec_single('SELECT current_time;');
See error handling section to learn how to handle errors.
sql_exec_fetchAll($sql,array $parameters = [],$errormsg = '',$fetch_names_only = false)
Executes an sql command and call fetchAll()
on it.
It means that this function returns an array containing all of the result set rows.
In a nutshell the result is array of associative arrays of resulted records.
If $fetch_names_only
parameter is false the fetchAll
function called with fetch_style=PDO::FETCH_NAMED
otherwise the default mode PDO::FETCH_BOTH
is used.
To understand this see PDO fetchAll() documentation.
print "<ul>";
$allres = sql_exec_fetchAll('SELECT name FROM users;');
foreach($allres as $res)
print "<li>".$res['name']."</li>";
print "</ul>";
sql_exec_fetchAll_noredirect($sql,array $parameters = [],$fetch_names_only = false)
Same as sql_exec_fetchAll
except the automatic error redirection is disabled.
sql_getLastInsertId($tablename,$keyname,$specifiedname = '')
Try to get the value of the last inserted key. (Through the php lastInsertId() function).
On different SQL platform the required sequence name differs. Because of this the function requires the
sql table name in the $tablename
parameter and the name of the key field in the $keyname
parameter.
You can pass an optional $specifiedname
parameter which overrides the internal logic and (if given) the function
calls the lastInsertId() with this.
General database CRUD interface
The CodKep's sql module have a database Create/Read/Update/Delete interface which can generate the sql commands
dynamically. It makes easier to create polymorph/variable database actions, or simply creates cleaner look database operations.
This interface uses the CodKep's internal sql functions to execute so that the transaction and error handling
is same that you get in sql_exec_
* functions.
Demonstration exaples:
|
|
|
|
|
|
|
|
The interface has 4 starter function to create the four base operation.
- db_query($tablename,$alias = '',array $options = [])
- Usable for start database queries/reads.
- db_insert($tablename,array $options = [])
- Usable for start database inserts. (create)
- db_update($tablename,array $options = [])
- Usable for start database updates.
- db_delete($tablename,array $options = [])
- Usable for start database deletions.
All four function above returns a DatabaseQuery
descendant object which have many methods to customize/set the
features of the desired database operation.
Methods of DatabaseQuery
- get($fieldspec,$alias = '',array $options = [])
- Adds exactly one field to the queried fields list
- The
$fieldspec
parameter specify the field according to FIELDSPEC specification. - If the
$alias
parameter is not empty the field data will be available under this name. Otherwise the field name is usable. - The
$options
parameter is an optional associative array of the field options according to OPTIONS specification.
- get_a(array $fieldnames,$container = '',array $options = [])
- Adds an Array of fields to the queried fields list
$fieldnames
is an array of strings containing the needed field names.- If the
$container
parameter is not empty the specified fields will be assigned to this container (table). - The
$options
parameter is an optional associative array of the field options according to OPTIONS specification.
- get_clean()
- Erase every field from the queried fields list
- counting($fieldspec = '',$alias = '')
- Erase the queried fields list and add the specified field as COUNT field.
- The
$fieldspec
parameter specify the field according to FIELDSPEC specification. - If the
$alias
parameter is not empty the COUNT field data will be available under this name. - If no parameter passed the function will count the * fields under name "cnt". So it means: COUNT(*) AS cnt
- set_fv($fieldspec,$value,array $options = [])
- Set a Field-Value.
- Sets a single field's value according to the
$value
parameter. The value is set through the sql parameter system. - The
$fieldspec
parameter specify the field according to FIELDSPEC specification. - The
$options
parameter is an optional associative array of the field options according to OPTIONS specification.
- set_fv_a(array $field_value_array)
- Set a Field-Value Array.
- Sets an array of field's value according to the parameter passed associative array where the indexes are the field names and the values are the desired values to set.
- set_fe($fieldspec,$expression,array $options = [])
- Set a Field-Expression.
- Sets a single field's value according to the
$expression
parameter. The expression value is writed directly into the sql query. The parameter system is not used here. - The
$fieldspec
parameter specify the field according to FIELDSPEC specification. - The
$options
parameter is an optional associative array of the field options according to OPTIONS specification.
- set_clean()
- Erase every field settings from the set fields list. (Erase all effects of
set_
* functions.)
- Erase every field settings from the set fields list. (Erase all effects of
- join($container,$alias,DatabaseCond $conditions)
- Join a container/table to this query (INNER JOIN)
- The
$container
parameter is the name of the table to join. - If the
$alias
is not null the passed alias name will be used. - The
$conditions
parameter should be aDatabaseCond
object. This object have to describe the connection rules. See DatabaseCond class
- join_ffe($container,$alias,$field1,$field2)
- Join a container/table easy way when Field Field Equal condition is sufficient. (INNER JOIN)
- This is a easy to use variable of normal
join()
method. It is usable when only a field equal to field typed condition is used to join the tables. (INNER JOIN secondtable ON secondtable.idf=maintable.connf
) - The
$container
parameter is the name of the table to join. - If the
$alias
is not null the passed alias name will be used. - The
$field1
and$field2
parameters are specifies the equal fields according to FIELDSPEC specification.
- join_opt($container,$alias,DatabaseCond $conditions)
- Join a container/table optional way to this query (LEFT OUTER JOIN)
- The
$container
parameter is the name of the table to join. - If the
$alias
is not null the passed alias name will be used. - The
$conditions
parameter should be aDatabaseCond
object. This object have to describe the connection rules. See DatabaseCond class
- join_opt_ffe($container,$alias,$field1,$field2)
- Join a container/table optional and easy way when Field Field Equal condition is sufficient. (INNER JOIN)
- This is a easy to use variable of normal
join_opt()
method. It is usable when only a field equal to field typed condition is used to join the tables. - The
$container
parameter is the name of the table to join. - If the
$alias
is not null the passed alias name will be used. - The
$field1
and$field2
parameters are specifies the equal fields according to FIELDSPEC specification.
- join_auto($container,$join_to = '',$alias = '')
- Joins a container/table automatically according to pre defined field matches. (Works only on field equal to field join conditions)
- The
$join_to
parameter can specify the table to join. If empty the CodKep try to join to the main container first. If not success it walks through the joined tables (in the specification order) until it finds a matches. - See
db_register_autojoin()
function.
- join_opt_auto($container,$join_to = '',$alias = '')
- Joins a container/table optionally and automatically according to pre defined field matches. (Works only on field equal to field join conditions)
- The
$join_to
parameter can specify the table to join. If empty the CodKep try to join to the main container first. If not success it walks through the joined tables (in the specification order) until it finds a matches. - See
db_register_autojoin()
function.
- join_clean()
- Erase every connection/join settings from the query. (Erase all effects of
join_
* functions.)
- Erase every connection/join settings from the query. (Erase all effects of
- cond(DatabaseCond $cond)
- Adds a complex condition to the condition lists.
- The
$cond
parameter have to be aDatabaseCond
object. See DatabaseCond class
- cond_ff($fieldspec1,$fieldspec2,$op,array $options = [])
- Adds a Field to Field type toplevel condition to the condition list.
- This function calls the main condition object's
ff()
function. See DatabaseCond class - The
$fieldspec1
and$fieldspec2
parameters are specifies the equal fields according to FIELDSPEC specification.
- cond_fv($fieldspec,$value,$op,array $options = [])
- Adds a Field to Value type toplevel condition to the condition list.
- This function calls the main condition object's
fv()
function. See DatabaseCond class - The
$fieldspec
parameter specify the field according to FIELDSPEC specification.
- cond_fe($fieldspec,$expression,$op,array $options = [])
- Adds a Field to Expression type toplevel condition to the condition list.
- This function calls the main condition object's
fe()
function. See DatabaseCond class - The
$fieldspec
parameter specify the field according to FIELDSPEC specification.
- cond_fb($fieldspec,array $options = [])
- Adds a Field to Bool type toplevel condition to the condition list.
- This function calls the main condition object's
fb()
function. See DatabaseCond class - The
$fieldspec
parameter specify the field according to FIELDSPEC specification.
- cond_fnull($fieldspec,array $options = [])
- Adds a Field is null type toplevel condition to the condition list.
- This function calls the main condition object's
fnull()
function. See DatabaseCond class - The
$fieldspec
parameter specify the field according to FIELDSPEC specification.
- cond_sql($sqlpart)
- Adds a free textual SQL confition text to the condition list.
- This function calls the main condition object's
sql()
function. See DatabaseCond class
- cond_clean()
- Erase every condition settings from the query/update. (Erase all effects of
cond_
* functions.)
- Erase every condition settings from the query/update. (Erase all effects of
- sort($fieldspec,array $options = [])
- Adds a sorter field according to the field specified by
$fieldspec
parameter. - The
$options
parameter is an optional associative array of the field options according to OPTIONS specification. - You can call this function more time to makes secondary, third, etc. level sorting.
- Adds a sorter field according to the field specified by
- sort_clean()
- Erase every sort settings from the query (Erase all effects of
sort
* function.)
- Erase every sort settings from the query (Erase all effects of
- start($start)
- In case of database query this method set the starting offset of the results (Sql OFFSET)
- length($length)
- In case of database query this method set the numbers of results (Sql LIMIT)
- local_cmd()
- This method will returns the built sql command. This does not need to execute the command, it's only for information or debugging purposes.
- execute(array $eopts = [])
- Execute the database action and returns an executed pdo object.
- The
$options
parameter is an optional associative array of the field options according to OPTIONS specification.
- execute_and_fetch(array $eopts = [])
- Execute the database action and fetch the results (once). It returns an array resulted by the fetch.
- execute_to_single(array $eopts = [])
- Execute the database action and returns the first field of the first received record. It returns a single value. This function is useful if a single value is queried from the database.
- execute_to_row(array $eopts = [])
- Same as
execute_and_fetch()
.
- Same as
- execute_to_arrays(array $eopts = [])
- Executes the database query command and call fetchAll() on it. It means that this function returns an array containing all of the result set rows. Calls
sql_exec_fetchAll()
inside.
- Executes the database query command and call fetchAll() on it. It means that this function returns an array containing all of the result set rows. Calls
The recommended way to create new a condition object (which can be add to the DatabaseQuery cond_
* or
join_
* methods is to calling one of the following two function:
- cond($mainconn)
- Create a normal condition branch
- The
$mainconn
can be"and"
- Set the AND logical connection between the sub conditions added here."or"
- Set the OR logical connection between the sub conditions added here.
- not_cond($mainconn)
- Create a denial (opposite) condition branch
- The
$mainconn
can be"and"
- Set the AND logical connection between the sub conditions added here."or"
- Set the OR logical connection between the sub conditions added here.
Both function returns a DatabaseCond object. Every DatabaseCond object contains an array of conditions
(connected with the defined logical relation). You can add sub conditions with the methods of
DatabaseCond. This sub conditions can be stacked with the cond()
method which also receives a DatabaseCond object.
Methods of DatabaseCond
- cond(DatabaseCond $cond)
- add(DatabaseCond $cond)
- Adds a (different) completely new sub condition object to the current list.
- ff($fieldspec1,$fieldspec2,$op,array $options = [])
- Adds a Field to Field type condition to the condition list.
- Use this method when a field is compared to an another field. You can specify wrapping methods or more operations with the
$options
parameter, but in base concept field values are compared.- Example 1:
ff(['users','name'],['customer','name'],'=')
- In SQL 1:
users.name = customer.name
- Example 2:
ff('surname','lastname','>',['f1function'=>'LENGTH','f2function'=>'LENGTH'])
- In SQL 2:
LENGTH(surname) > LENGTH(lastname)
- Example 1:
- Usable operands are:
= , != , > , < , >= , <= , regex
- The
$options
is an optional associative array contains the options according to the OPTIONS specification
- fv($fieldspec,$value,$op,array $options = [])
- Adds a Field to Value type condition to the condition list.
- Use this method when a field is compared to an external value given from program side. You can specify wrapping methods or more operations with the
$options
parameter, but in base concept field value are compared to an user defined value.- Example 1:
fv(['users','name'],'John Doe','=')
- In SQL 1:
users.name = :placeholder
and[':placeholder' => 'John Doe']
- Example 2:
fv('surname','dave','=',['ffunction'=>'LOWER'])
- In SQL 2:
LOWER(surname) = :placeholder
and[':placeholder' => 'dave']
- Example 1:
- Usable operands are:
= , != , > , < , >= , <= , regex, in
- If the operand is "in" the value have to be an array.
- The
$options
is an optional associative array contains the options according to the OPTIONS specification
- fe($fieldspec,$expression,$op,array $options = [])
- Adds a Field to Expression type condition to the condition list.
- Use this method when a field is compared to an sql expression. You can specify wrapping methods or more operations with the
$options
parameter, but in base concept field value are compared to an database originated difficult expression.- Example:
fe('itemcount','(height-10)','>')
- In SQL:
itemcount > (height-10)
- Example:
- Usable operands are:
= , != , > , < , >= , <= , regex , in
- If the operand is "in" the expression have to contains an sql expression (eg. subquery) which returns an array.
- The
$options
is an optional associative array contains the options according to the OPTIONS specification
- fb($fieldspec,array $options = [])
- Adds a Field to Bool type condition to the condition list.
- Use this method when a field is tested to be TRUE or FALSE. You can specify wrapping methods around the field or do more operations with the
$options
parameter, but in base concept field value are tested to be logically true or false.- Example 1:
fb(['user','active'])
- In SQL 1:
user.active
- Example 2:
fb(['user','password'],['ffunction' => 'IS_VALID','opposite' => true])
- In SQL 2:
NOT IS_VALID(user.password)
- Example 1:
- The
$options
is an optional associative array contains the options according to the OPTIONS specification
- fnull($fieldspec,array $options = [])
- Adds a Field is null type condition to the condition list.
- Use this method when a field is tested to be NULL or NOT NULL. You can specify wrapping methods around the field or do more operations with the
$options
parameter, but in base concept field value are tested to be NULL or NOT NULL.- Example 1:
fnull(['user','password'])
- In SQL 1:
user.password IS NULL
- Example 2:
fnull(['user','password'],['opposite' => true])
- In SQL 2:
NOT user.password IS NULL
- Example 1:
- The
$options
is an optional associative array contains the options according to the OPTIONS specification
- sql($sqlpart,array $options = [])
- Adds an arbitrary sql command string as a condition. This string will be directly copied to the sql command. It is not recommend to use it except the condition is cannot described with methods above.
- The
$options
is an optional associative array contains the options according to the OPTIONS specification
Let's see a more complex condition example where more condition object is stacked each other:
/*
SELECT name FROM users
WHERE (gender = 'm' AND name REGEXP '^D') OR
(gender = 'f' AND NOT( name REGEXP '^A' OR name REGEXP '^B' ));
*/
db_query('users')
->get('name')
->cond(
cond('or')
->add( cond('and')
->fv('gender','m','=')
->fv('name','^D','regex')
)
->add( cond('and')
->fv('gender','f','=')
->add(not_cond('or')
->fv('name','^A','regex')
->fv('name','^B','regex'))
)
)
->execute_to_arrays()
Keep in mind that the built in top level condition object (which default exists in DatabaseQuery to make it possible to add more conditions top level) has always AND logic. It's means that you have to add one sub condition object with OR logic to achieve top level OR conditions between arguments. You can see this method in the example above.
Later the node module extends this interface to query nodes more easy way, see node_query() for more details.
The FIELDSPEC typed parameters
Most methods in DatabaseQuery
and DatabaseCond
can receive field specification. This can be done two way:
- A simple string
- This case the string contains the name of the field
- Example:
"name"
- Array of strings
- This case the array should contains two string where the first have to specify the container while the second specify the field by name
- Example:
["users","apple"]
Options available in methods
Available options in methods. (This options can be mixed together when available)
name | value | Description | Available here |
---|---|---|---|
"function" | string | Embrace the value in a function call | set_fv() , set_fe() , get() , get_a() , sort() |
"more_args" | string | Adds additional arguments to the function call | set_fv() , set_fe() , get() , get_a() , sort() |
"direction" | "REVERSE" | Reverse the sorting directions on this field | sort() |
"opposite" | true | Negate the condition's result where set | cond_ff() , cond_fv() , cond_fe() , cond_fb() , cond_fnull() , ff() , fv() , fe() , fb() , fnull() |
"f1function" | string | Embrace the field 1 in a function call | cond_ff() , ff() |
"f2function" | string | Embrace the field 2 in a function call | cond_ff() , ff() |
"ffunction" | string | Embrace the field in a function call | cond_fv() , cond_fe() , cond_fb() , cond_fnull() , fv() , fe() , fb() , fnull() |
"vfunction" | string | Embrace the value in a function call | cond_fv() , fv() |
"efunction" | string | Embrace the expression in a function call | cond_fe() , fe() |
"noredirect" | true | Disable automatic page redirection in case of error | execute() , execute_to_arrays() |
"errormsg" | string | Custom error message, which is passed to the underlying sql_exec_ * functions. See here | execute() , execute_and_fetch() , execute_to_row() , execute_to_single() , execute_to_arrays() |
"fetch_names_only" | true | This options is set the fetch_names_only parameter of sql_exec_fetchAll() . See here | execute_to_arrays() |
Auto join system
You can register table+field pairs in db query system which is usable to join tables with less code.
In a properly set environment you only have to tell which table to join, the system will do the field matches according
to the registrations done with the following function:
db_register_autojoin($join_this_container, $to_this_container, $this_fieldname, $to_fieldname, $mode = ONE_WAY)
Registers a new auto join hint in system.
- The
$join_this_container
parameter is the table A to join. - The
$to_this_container
parameter is the table B where to join. - The
$this_fieldname
parameter is the matching field of table A. - The
$to_fieldname
parameter is the matching field of table B. - If the
$mode
parameter is the defaultONE_WAY
the join hint is used only when A table joined to B. Other ways the$mode
isTWO_WAY
the hint is used both the A->B and B->A directions join.
Example:
function hook_mymodule_init()
{
db_register_autojoin('people','address', 'addr', 'a_id', TWO_WAY);
}
After you do this registration above you can use the join_auto()
and join_opt_auto()
function in db queries.
$r = db_query('people')
->get('name')
->join_auto('address')
->get('address_string')
->sort('name')
->execute_to_arrays();
// Here the join_auto('address') will be translated to
// join_ffe('address','',['people','addr'],['address','a_id])
print to_table($r);
Simple and easy database operations
There is a simplified database access interface for simple database manipulations based on DatabaseQuery (The Database CRUD interface described above) This operations is usable for simple insert/delete/update/list elements from a single sql table.
You can use the following helper function to use this simplified interface:
db_x($tablename)
This function above (means db eXecute) creates a SimpleDatabaseQuery instance which has the following methods:
- add(array $field_value_array)
- Inserts a new record to the
$tablename
table according to$field_value_array
, and executes the statement. - It's equivalent to call:
db_query($tablename)
->set_fv_a($field_value_array)
->execute();
- Inserts a new record to the
- update(array $fields_to_set,array $field_value_filters = [])
- Update records according to the filter array in the
$tablename
table to$field_value_array
, and executes the statement. Every key value pairs in the$field_value_filters
array is added as a separate condition, which resulting that all field index have to match with all values to update the record. - It's equivalent to call:
db_update($tablename)
->set_fv_a($field_value_array)
->cond_fv(...first key-value pair of $field_value_filters...)
->cond_fv(...second key-value pair of $field_value_filters...)
...
->execute();
- Update records according to the filter array in the
- del(array $field_value_filters)
- Deletes all record from the
$tablename
table according to$field_value_filters
, and executes the statement. Every key value pairs in the$field_value_filters
array is added as a separate condition, which resulting that all field index have to match with all values to delete a record. - It's equivalent to call:
db_delete($tablename)
->cond_fv(...first key-value pair of $field_value_filters...)
->cond_fv(...second key-value pair of $field_value_filters...)
...
->execute();
- Deletes all record from the
- get($showfield,array $field_value_filters = [])
- Returns an array of the first record matched to the filters of
$field_value_filters
. The returned field list consists of the columns specified by$showfield
. If the$showfield
parameter is an array of field names the return value will be an array. Otherwise the$showfield
is a simple string a simple value will be retuened. Every key value pairs in the$field_value_filters
array is added as a separate condition, which resulting that all field index have to match with all values to delete a record. - It's equivalent to call: (When
is_array($showfield) == true
)
db_query($tablename)
->get_a($showfield)
->cond_fv(...first key-value pair of $field_value_filters...)
->cond_fv(...second key-value pair of $field_value_filters...)
...
->execute_and_fetch();
- It's equivalent to call: (When
is_array($showfield) == false
)
db_query($tablename)
->get($showfield)
->cond_fv(...first key-value pair of $field_value_filters...)
->cond_fv(...second key-value pair of $field_value_filters...)
...
->execute_to_single();
- Returns an array of the first record matched to the filters of
- lst(array $showfields,array $field_value_filters = [],array $sort = [])
- Returns an array of arrays of all records matched to the filters of
$field_value_filters
. The returned field lists consists of the columns specified by$showfields
. Every key value pairs in the$field_value_filters
array is added as a separate condition, which resulting that all field index have to match with all values to delete a record. If you specify an array to the sort parameter, the result is sorted according to that fields, otherwise the result is sorted by the first value of$showfields
array. If a column name in$sort
is started with-
sign, the sorting by that field is reversed. - It's equivalent to call:
db_query($tablename)
->get_a($showfields)
->cond_fv(...first key-value pair of $field_value_filters...)
->cond_fv(...second key-value pair of $field_value_filters...)
...
->sort(...first value of $sort...)
->sort(...second value of $sort...)
->execute_to_arrays();
- Returns an array of arrays of all records matched to the filters of
In the functions above the $field_value_filters
array values can be the following "magic strings":
##NULL##
- the field is match when NULL##NOTNULL##
- the field is match when not NULL##TRUE##
- the field is match when TRUE##FALSE##
- the field is match when FALSE
Examples using of this simple database manipulation interface
//Inserts a new record to the "mysqltable" table
//with the describe:'Lorem ipsum' and height:150 values
db_x('mysqltable')->add(['describe' => 'Lorem ipsum','height' => 150]);
//Delete the id:123 record from the "mysqltable" table
db_x('mysqltable')->del(['id' => 123]);
//Change the name field value to "Dave" on "names" table id:112 record.
db_x('names')->update(['name' => 'Dave'],['id' => 112]);
//Get the following field values of the id:112 record from "names" table.
$a = db_x('names')->get(['name','id','age'],['id' => 112]);
print implode(', ',$a);
//List all employe from "names" sorted by name and descending to age with the specified fields.
$a = db_x('names')->lst(['name','id','age'],['employee' => '##TRUE##'],['name','-age']);
print to_table($a);
//Simply get the name of the id:88 from "names" table.
$n = db_x('names')->get('name',['id' => 88]);
print "The name is $n";
Sql transactions
It's possible to use sql transactions, the sql module have helper functions to do this. The transaction manage functions works on the current database connections.
Functions to manage transactions
sql_transaction()
Start a new sql transaction.sql_commit()
Commits the current transaction.sql_rollback()
Rollbacks the current transaction.sql_commit_if_needed()
Commits the current transaction if exists. Otherwise do nothing.sql_rollback_if_needed()
Rollbacks the current transaction if exists. Otherwise do nothing.
Every transaction should begin by calling sql_transaction()
. There is no way to nest sql transactions,
thus every sql_transaction()
should proceed some other function which rollback or commits the transaction.
Note: If you start a new transaction in another opened transaction the system will raise an error message
Example to use transactions
//Example to use transactions
sql_transaction();
sql_exec("UPDATE systable SET value=:val WHERE key=:key;",
[':key' => $key,
':val' => $value]);
//In case the update failed the execution is redirected to error handling page,
//thus the sql_commit won't executed
sql_commit();
Without automatic error redirection
$db->auto_error_page = false;
sql_transaction();
sql_exec("UPDATE systable SET value=:val WHERE key=:key;",
[':key' => $key,
':val' => $value]);
if($db->error)
{
sql_rollback();
//other error handling
return;
}
sql_commit();
If you have started transaction the $db->transaction
value is true
otherwise is false
.
Error handling
Most sql related function can failed by any reasons. Every time you call a functions of sql module the following processes will be done:
- Set
$db->error
tofalse
and$db->errormsg
to empty - Set the
$db->lastsql
value to the command will be executed - Do the sql related work
- In case of success, will normally exit
- In case of error
- Set
$db->error
totrue
- Fill the
$db->errormsg
with an available error message. - By default do an automatic redirection to an sql error page. It means that the execution won't continue after the failed function call.
- Set
In a nutshell usually you does not have to care about error handling because the site will automatically stop the execution in case of error, and will do a redirection to an sql error page and show an error message.
An example of an error:
In case of error the following sql error routes are used:
Functions | path |
---|---|
sql_connect(), sql_disconnect() | sql_connection_error |
sql_exec_*(), sql_transaction(), sql_commit(), sql_rollback(), etc... | sql_error |
You can disable the automatic error redirection by set the $db->auto_error_page
to false
.
If you do this way you should check the value of $db->error
after every sql command.
In case you disabled the automatic error redirection and you handle and error, you can always
find the available error message in $db->errormsg
and the last executed sql command in $db->lastsql
variables.
By default two default built in error handling route exists in CodKep the:
"sql_connection_error"
for connection errors"sql_error"
for other sql related errors
You can redefine this error targets in case you need a special kind of error handling. For example: In case you
create REST interfaces you need to send special HTTP response code and error message instead of built in methods.
(Which responds with http/html of course)
Redefining of this error targets can be done by
the $db->error_locations
global variable the following way:
global $db;
$db->error_locations['connection_error'] = 'my_sql_connection_error_route';
$db->error_locations['generic_error' ] = 'my_sql_generic_error_route';
Of course you need to define these routes above and associate with your callbacks as described here.
Schema editor
The CodKep core itself is not depend on sql, it means that the CodKep inner core does not have any sql schema requirements.
On the other hand further system and user modules can have some sql schema requirements, to achieve their functionality.
(Some system modules like user, node or file also have sql schema requirements)
The CodKep's sql module has a schema editor page, which can check the schema requirements of the active modules, and can update the schema if necessary. After a clean codkep install the schema editor can build the initial database structure for the codkep's sql related system modules.
The schema editor is available on sqlschema internal location.
- http://yoursite.com/index.php?q=sqlschema
- http://yoursite.com/sqlschema (if clean url's enabled)
A schema editor page looks like similar way:
In order to reach schema editor page, you should set the schema editor password or admin access.
See sql settings
Define sql schema requirements
The modules can define their sql schema requirements by implementing HOOK_required_sql_schema
hook.
This hook does not receive parameters, it returns an associative array which describe the required schema.
The structure of return array of the following
- "An identifier name" =
- "tablename" = "sql table name"
- "columns" =
- "column name 1" => "SQL type"
- "column name 2" => "SQL type"
- etc...
It looks like this way in a real example:
//Implemented "required_sql_schema" of meetroom module.
function hook_meetroom_required_sql_schema()
{
$t = [];
$t['meetroom_module_meetings_table'] =
[
"tablename" => 'meetings',
"columns" => [
'id' => 'SERIAL',
'room' => 'VARCHAR(3)',
'takeby' => 'VARCHAR(16)',
'title' => 'VARCHAR(256)',
'prior' => 'NUMERIC(3)',
'modd' => 'TIMESTAMP',
'mdate' => 'DATE',
'mstart' => 'VARCHAR(8)',
'mend' => 'VARCHAR(8)',
],
];
return $t;
}
If you implement the HOOK_required_sql_schema
hook with a correct return value,
the schema requirements will display in schema editor page and the
requirements can be met with some clicks.
Hooks
The following hooks can be implement to interact with sql module.
Hook | Description |
---|---|
HOOK_required_sql_schema() | Define SQL schema requirements of a module |
HOOK_before_sql_schema_collection() | Runs before the sqlschema code collects the sql requirements. Usable to include dynamic codes which contains definitions. |
HOOK_sql_connected() | Runs after the sql connection is established |
HOOK_execute_sql($sql,$parameters) | Runs before an sql command is executed. It received the sql command and parameters but cannot modify its. |
HOOK_begin_generate_sql($object) | Runs before an sql command is generated by DatabaseQuery descendant class. |
HOOK_end_generate_sql($object) | Runs after an sql command is generated by DatabaseQuery descendant class. |
HOOK_sql_show_builtin_connerror_page() | Runs immediately before the built in sql connection error page is delivered. |
HOOK_sql_show_builtin_error_page() | Runs immediately before the built in sql general error page is delivered. |