86 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
107 public function connect($return_false_for_error =
false)
116 $this->error_code = $e->getCode();
117 if ($return_false_for_error) {
123 return ($this->pdo->errorCode() == PDO::ERR_NONE);
189 return $this->
query($this->manager->getQueryUtils()->createDatabase($a_name, $a_charset, $a_collation));
190 }
catch (PDOException
$e) {
201 if ($this->pdo instanceof PDO) {
202 return $this->pdo->errorCode();
216 if ($tmpClientIniFile instanceof
ilIniFile) {
217 $clientIniFile = $tmpClientIniFile;
219 $ilClientIniFile = null;
220 if ($DIC->offsetExists(
'ilClientIniFile')) {
221 $clientIniFile = $DIC[
'ilClientIniFile'];
227 $this->
setUsername($clientIniFile->readVariable(
"db",
"user"));
228 $this->
setHost($clientIniFile->readVariable(
"db",
"host"));
229 $this->
setPort((
int) $clientIniFile->readVariable(
"db",
"port"));
230 $this->
setPassword($clientIniFile->readVariable(
"db",
"pass"));
231 $this->
setDbname($clientIniFile->readVariable(
"db",
"name"));
232 $this->
setDBType($clientIniFile->readVariable(
"db",
"type"));
254 return '`' . $identifier .
'`';
263 abstract public function nextId($table_name);
274 public function createTable($table_name, $fields, $drop_table =
false, $ignore_erros =
false)
290 return $this->manager->createTable($table_name, $fields, array());
300 foreach ($a_cols as $col => $def) {
336 return $this->field_definition->checkColumnDefinition($a_def);
346 return $this->field_definition->checkColumnName($a_name);
358 assert(is_array($primary_keys));
361 foreach ($primary_keys as
$f) {
362 $fields[
$f] = array();
382 foreach ($this->manager->listTableIndexes($table_name) as $idx_name) {
383 $def = $this->reverse->getTableIndexDefinition($table_name, $idx_name);
384 $idx_fields = array_keys((array) $def[
'fields']);
386 if ($idx_fields === $fields) {
387 return $this->
dropIndex($table_name, $idx_name);
410 $this->manager->createSequence($table_name, $start);
421 $result = $this->pdo->prepare(
"SHOW TABLES LIKE :table_name");
422 $result->execute(array(
'table_name' => $table_name));
440 $in_array = in_array($column_name, $fields);
456 throw new ilDatabaseException(
"ilDB Error: addTableColumn(" . $table_name .
", " . $column_name .
")");
459 throw new ilDatabaseException(
"ilDB Error: addTableColumn(" . $table_name .
", " . $column_name .
")");
468 return $this->manager->alterTable($table_name, $changes,
false);
478 public function dropTable($table_name, $error_if_not_existing =
true)
481 $tables = $ilDBPdoManager->listTables();
482 $table_exists = in_array($table_name, $tables);
483 if (!$table_exists && $error_if_not_existing) {
488 $sequences = $ilDBPdoManager->listSequences();
489 if (in_array($table_name, $sequences)) {
490 $ilDBPdoManager->dropSequence($table_name);
495 $ilDBPdoManager->dropTable($table_name);
520 if (
$ilBench instanceof ilBenchmark) {
523 }
catch (PDOException
$e) {
527 $err = $this->pdo->errorCode();
528 if ($err != PDO::ERR_NONE) {
529 $info = $this->pdo->errorInfo();
530 $info_message = $info[2];
549 while (
$data = $query_result->fetch($fetch_mode)) {
562 $this->manager->dropSequence($table_name);
576 $column_name => array(),
580 return $this->manager->alterTable($table_name, $changes,
false);
595 throw new ilDatabaseException(
"ilDB Error: renameTableColumn(" . $table_name .
"," . $column_old_name .
"," . $column_new_name .
")");
598 $def = $this->reverse->getTableFieldDefinition($table_name, $column_old_name);
601 $best_alt = $analyzer->getBestDefinitionAlternative($def);
602 $def = $def[$best_alt];
603 unset($def[
"nativetype"]);
604 unset($def[
"mdb2type"]);
606 $f[
"definition"] = $def;
607 $f[
"name"] = $column_new_name;
611 $column_old_name =>
$f,
615 return $this->manager->alterTable($table_name, $changes,
false);
624 public function insert($table_name, $values)
628 foreach ($values as $key => $val) {
629 $real[] = $this->
quote($val[1], $val[0]);
632 $values = implode(
",", $real);
633 $fields = implode(
",", $fields);
634 $query =
"INSERT INTO " . $this->
quoteIdentifier($table_name) .
" (" . $fields .
") VALUES (" . $values .
")";
638 return $this->pdo->exec(
$query);
649 $res = $query_result->fetchObject();
651 $query_result->closeCursor();
669 $field_values = array();
670 $placeholders = array();
671 $placeholders_full = array();
677 $field_value = $col[1];
679 $placeholders[] =
"%s";
680 $placeholders_full[] =
":$k";
683 if ($col[0] ==
"blob" || $col[0] ==
"clob" || $col[0] ==
'text') {
688 if ($col[0] ==
'integer' && !is_null($field_value)) {
689 $field_value = (int) $field_value;
692 $values[] = $field_value;
693 $field_values[$k] = $field_value;
694 if ($col[0] ==
"blob" || $col[0] ==
"clob") {
703 foreach ($fields as $k => $field) {
704 $q .= $lim . $this->
quoteIdentifier($field) .
" = " . $placeholders_full[$k];
709 foreach ($where as $k => $col) {
715 $this->
execute($r, $field_values);
718 foreach ($where as $k => $col) {
721 $field_values[$k] = $col;
725 foreach ($fields as $k => $field) {
726 $q .= $lim . $this->
quoteIdentifier($field) .
" = " . $placeholders[$k];
731 foreach ($where as $k => $col) {
758 $r = $this->pdo->exec(
$query);
759 if (
$ilBench instanceof ilBenchmark) {
762 }
catch (PDOException
$e) {
777 $res = $query_result->fetch(PDO::FETCH_ASSOC);
779 $query_result->closeCursor();
795 return $query_result->rowCount();
807 if ($value === null) {
811 $pdo_type = PDO::PARAM_STR;
819 if ($value === $this->
now()) {
824 $value = (int) $value;
829 $pdo_type = PDO::PARAM_INT;
833 $pdo_type = PDO::PARAM_STR;
837 return $this->pdo->quote($value, $pdo_type);
849 foreach ($this->manager->listTableIndexes($table_name) as $idx_name) {
850 $def = $this->reverse->getTableIndexDefinition($table_name, $idx_name);
851 $idx_fields = array_keys((array) $def[
'fields']);
853 if ($idx_fields === $fields) {
868 public function addIndex($table_name, $fields, $index_name =
'', $fulltext =
false)
870 assert(is_array($fields));
871 $this->field_definition->checkIndexName($index_name);
873 $definition_fields = array();
874 foreach ($fields as
$f) {
875 $definition_fields[
$f] = array();
878 'fields' => $definition_fields,
882 $this->manager->createIndex($table_name, $this->
constraintName($table_name, $index_name), $definition);
903 $f_str = implode(
",", $a_fields);
904 $q =
"ALTER TABLE $a_table ADD FULLTEXT $i_name ($f_str)";
915 $this->
query(
"ALTER TABLE $a_table DROP FULLTEXT $i_name");
924 $set = $this->
query(
"SHOW INDEX FROM " . $a_table);
926 if ($rec[
"Key_name"] == $a_name && $rec[
"Index_type"] ==
"FULLTEXT") {
961 return $a_constraint;
989 $this->db_type =
$type;
1000 $ilDB = $DIC->database();
1005 return $ilDB->getFieldDefinition()->getReservedMysql();
1015 assert(is_array($tables));
1017 $lock = $this->manager->getQueryUtils()->lock($tables);
1019 $ilLogger = $DIC->logger()->root();
1020 if ($ilLogger instanceof
ilLogger) {
1021 $ilLogger->log(
'ilDB::lockTables(): ' . $lock);
1024 $this->pdo->exec($lock);
1034 $this->pdo->exec($this->manager->getQueryUtils()->unlock());
1045 public function in($field, $values, $negate =
false,
$type =
"")
1047 return $this->manager->getQueryUtils()->in($field, $values, $negate,
$type);
1060 if (!is_array($types) || !is_array($values) || count($types) != count($values)) {
1061 throw new ilDatabaseException(
"ilDB::queryF: Types and values must be arrays of same size. ($query)");
1063 $quoted_values = array();
1064 foreach ($types as $k => $t) {
1065 $quoted_values[] = $this->
quote($values[$k], $t);
1082 if (!is_array($types) || !is_array($values) || count($types) != count($values)) {
1083 throw new ilDatabaseException(
"ilDB::manipulateF: types and values must be arrays of same size. ($query)");
1085 $quoted_values = array();
1086 foreach ($types as $k => $t) {
1087 $quoted_values[] = $this->
quote($values[$k], $t);
1128 public function like($column,
$type, $value =
"?", $case_insensitive =
true)
1130 return $this->manager->getQueryUtils()->like($column,
$type, $value, $case_insensitive);
1139 return $this->manager->getQueryUtils()->now();
1151 public function replace($table, $primaryKeys, $otherColumns)
1153 $a_columns = array_merge($primaryKeys, $otherColumns);
1155 $field_values = array();
1156 $placeholders = array();
1160 foreach ($a_columns as $k => $col) {
1162 $placeholders[] =
"%s";
1163 $placeholders2[] =
":$k";
1167 if ($col[0] ==
'integer' && !is_null($col[1])) {
1168 $col[1] = (int) $col[1];
1171 $values[] = $col[1];
1172 $field_values[$k] = $col[1];
1175 $q =
"REPLACE INTO " . $table .
" (" . implode(
",", $fields) .
") VALUES (" . implode(
",", $placeholders) .
")";
1192 if (!$emptyOrNull || $value !=
"") {
1195 return "(" .
$columns .
" = '' OR $columns IS NULL)";
1214 $this->host =
$host;
1304 $this->port =
$port;
1350 return " UPPER(" . $a_exp .
") ";
1360 return " LOWER(" . $a_exp .
") ";
1370 public function substr($a_exp, $a_pos = 1, $a_len = -1)
1374 $lenstr =
", " . $a_len;
1377 return " SUBSTR(" . $a_exp .
", " . $a_pos . $lenstr .
") ";
1409 $this->pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, $a_status);
1466 case self::FEATURE_TRANSACTIONS:
1468 case self::FEATURE_FULLTEXT:
1470 case self::FEATURE_SLAVE:
1483 return $this->manager->listTables();
1507 return $this->field_definition->getAllowedAttributes();
1526 return $this->manager->listSequences();
1535 public function concat(array $values, $allow_null =
true)
1537 return $this->manager->getQueryUtils()->concat($values, $allow_null);
1547 if ($this->limit !== null && $this->offset !== null) {
1549 $this->limit = null;
1550 $this->offset = null;
1565 public function locate($a_needle, $a_string, $a_start_pos = 1)
1567 return $this->manager->getQueryUtils()->locate($a_needle, $a_string, $a_start_pos);
1580 $def = $this->reverse->getTableFieldDefinition($table, $a_column);
1583 $best_alt = $analyzer->getBestDefinitionAlternative($def);
1584 $def = $def[$best_alt];
1585 unset($def[
"nativetype"]);
1586 unset($def[
"mdb2type"]);
1591 $type = ($a_attributes[
"type"] ??
"" !=
"") ? $a_attributes[
"type"] : $def[
"type"];
1592 foreach ($def as $k => $v) {
1593 if ($k !=
"type" && !$ilDBPdoFieldDefinition->isAllowedAttribute($k,
$type)) {
1597 $check_array = $def;
1598 foreach ($a_attributes as $k => $v) {
1599 $check_array[$k] = $v;
1602 throw new ilDatabaseException(
"ilDB Error: modifyTableColumn(" . $table .
", " . $a_column .
")");
1605 foreach ($a_attributes as
$a => $v) {
1609 $a_attributes[
"definition"] = $def;
1613 $a_column => $a_attributes,
1617 return $this->manager->alterTable($table, $changes,
false);
1625 public function free($a_st)
1630 return $a_st->closeCursor();
1646 throw new ilDatabaseException(
"ilDB Error: renameTable(" . $a_name .
"," . $a_new_name .
")<br />" . $e->getMessage());
1649 $this->manager->alterTable($a_name, [
"name" => $a_new_name],
false);
1669 return $this->field_definition->checkTableName($a_name);
1682 return $ilDBPdoMySQLFieldDefinition->
isReserved($a_word);
1692 if (!$this->
supports(self::FEATURE_TRANSACTIONS)) {
1696 return $this->pdo->beginTransaction();
1706 if (!$this->
supports(self::FEATURE_TRANSACTIONS)) {
1710 return $this->pdo->commit();
1720 if (!$this->
supports(self::FEATURE_TRANSACTIONS)) {
1724 return $this->pdo->rollBack();
1735 return $this->manager->dropIndex($a_table, $a_name);
1767 $type = PDO::FETCH_ASSOC;
1770 $type = PDO::FETCH_OBJ;
1773 $type = PDO::FETCH_ASSOC;
1777 return $this->pdo->query(
$query, PDO::FETCH_ASSOC)->fetchAll(PDO::FETCH_COLUMN, $colnum);
1789 switch ($fetchmode) {
1791 $type = PDO::FETCH_ASSOC;
1794 $type = PDO::FETCH_OBJ;
1797 $type = PDO::FETCH_ASSOC;
1811 return $this->pdo->query(
'SELECT VERSION()')->fetchColumn();
1820 public function escape($value, $escape_wildcards =
false)
1893 assert(is_array($fields));
1901 $fields_corrected = array();
1902 foreach ($fields as
$f) {
1903 $fields_corrected[
$f] = array();
1905 $definition = array(
1907 'fields' => $fields_corrected,
1921 return $this->manager->dropConstraint($a_table, $this->
constraintName($a_table, $a_name),
false);
1933 $cons = $analyzer->getConstraintsInformation($a_table);
1934 foreach ($cons as
$c) {
1935 if ($c[
"type"] ==
"unique" && count($a_fields) == count($c[
"fields"])) {
1937 foreach ($a_fields as
$f) {
1938 if (!isset($c[
"fields"][$f])) {
1957 return $this->pdo->lastInsertId();
1978 $cons = $analyzer->getConstraintsInformation($table);
1979 foreach ($cons as
$c) {
1980 if ($c[
"type"] ==
"unique" && count($fields) == count($c[
"fields"])) {
1982 foreach ($fields as
$f) {
1983 if (!isset($c[
"fields"][$f])) {
2003 return $this->manager->dropConstraint($table_name,
"PRIMARY",
true);
2013 for (
$i = 0, $j = count($a_data);
$i < $j;
$i++) {
2014 $stmt->execute($a_data[
$i]);
2026 return "FROM_UNIXTIME(" . $a_expr .
")";
2035 return "UNIX_TIMESTAMP()";
2056 $fields_values = (array) $fields;
2058 if (!empty($fields_values)) {
2059 $keys = $fields_values;
2064 $keys = array_keys($fields_values);
2066 $params = array_values($fields_values);
2067 if (empty($params)) {
2071 $stmt = $this->
autoPrepare($tablename,
$keys, $mode, $where, $types, $result_types);
2108 if ($this->options[
'quote_identifier']) {
2112 if (!empty($table_fields) && $this->options[
'quote_identifier']) {
2113 foreach ($table_fields as $key => $field) {
2118 if ($where !==
false && !is_null($where)) {
2119 if (is_array($where)) {
2120 $where = implode(
' AND ', $where);
2122 $where =
' WHERE ' . $where;
2127 if (empty($table_fields)) {
2130 $cols = implode(
', ', $table_fields);
2131 $values =
'?' . str_repeat(
', ?', (count($table_fields) - 1));
2133 return 'INSERT INTO ' . $table .
' (' .
$cols .
') VALUES (' . $values .
')';
2136 if (empty($table_fields)) {
2139 $set = implode(
' = ?, ', $table_fields) .
' = ?';
2140 $sql =
'UPDATE ' . $table .
' SET ' . $set . $where;
2145 $sql =
'DELETE FROM ' . $table . $where;
2150 $cols = !empty($table_fields) ? implode(
', ', $table_fields) :
'*';
2151 $sql =
'SELECT ' .
$cols .
' FROM ' . $table . $where;
2169 return (
$d->version ?
$d->version :
'Unknown');
2179 $query_replaced = preg_replace(
2180 '/[\x{10000}-\x{10FFFF}]/u',
2184 if (!empty($query_replaced)) {
2185 return $query_replaced;
2204 public function groupConcat($a_field_name, $a_seperator =
",", $a_order = null)
2206 return $this->manager->getQueryUtils()->groupConcat($a_field_name, $a_seperator, $a_order);
2212 public function cast($a_field_name, $a_dest_type)
2214 return $this->manager->getQueryUtils()->cast($a_field_name, $a_dest_type);
2222 $constraints = $this->manager->listTableConstraints($table_name);
2224 if (in_array(
'primary', $constraints)) {
2225 $definitions = $this->reverse->getTableConstraintDefinition($table_name,
'primary');
2226 $primary_fields = array_keys($definitions[
'fields']);
2227 sort($primary_fields);
2230 return $primary_fields === $fields;
sanitizeMB4StringIfNotSupported($query)
string to sanitize, all MB4-Characters like emojis will re replaced with ???string sanitized query ...
autoPrepare($table, $table_fields, $mode=ilDBConstants::AUTOQUERY_INSERT, $where=false, $types=null, $result_types=ilDBConstants::PREPARE_MANIP)
addPrimaryKey($table_name, $primary_keys)
setFieldDefinition($field_definition)
addIndex($table_name, $fields, $index_name='', $fulltext=false)
static getReservedWords()
Get reserved words.
getSequenceName($table_name)
doesCollationSupportMB4Strings()
equals($columns, $value, $type, $emptyOrNull=false)
execute($stmt, $data=array())
Class ilPDOStatement is a Wrapper Class for PDOStatement.
like($column, $type, $value="?", $case_insensitive=true)
const MYSQL_COLLATION_UTF8MB4
queryF($query, $types, $values)
getServerVersion($native=false)
escape($value, $escape_wildcards=false)
Interface ilDBPdoInterface.
dropUniqueConstraint($a_table, $a_name="con")
supportsCollationMigration()
dropSequence($table_name)
sequenceExists($sequence)
update($table_name, $columns, $where)
renameTableColumn($table_name, $column_old_name, $column_new_name)
queryCol($query, $type=PDO::FETCH_ASSOC, $colnum=0)
concat(array $values, $allow_null=true)
quote($value, $type=null)
modifyTableColumn($table, $a_column, $a_attributes)
Class ilDatabaseException.
executeMultiple($stmt, $a_data)
dropFulltextIndex($a_table, $a_name)
Drop fulltext index.
indexExistsByFields($table_name, $fields)
migrateAllTablesToCollation($collation=ilDBConstants::MYSQL_COLLATION_UTF8MB4)
manipulateF($query, $types, $values)
addFulltextIndex($a_table, $a_fields, $a_name="in")
getAdditionalAttributes()
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
autoExecute($tablename, $fields, $mode=ilDBConstants::AUTOQUERY_INSERT, $where=false)
Generate an insert, update or delete query and call prepare() and execute() on it.
dropTable($table_name, $error_if_not_existing=true)
checkTableColumns($a_cols)
queryRow($query, $types=null, $fetchmode=ilDBConstants::FETCHMODE_DEFAULT)
foreach($_POST as $key=> $value) $res
quoteIdentifier($identifier, $check_option=false)
dropUniqueConstraintByFields($a_table, $a_fields)
isFulltextIndex($a_table, $a_name)
Is index a fulltext index?
replace($table, $primaryKeys, $otherColumns)
Replace into method.
static isReservedWord($a_word)
createTable($table_name, $fields, $drop_table=false, $ignore_erros=false)
fetchAssoc($query_result)
createDatabase($a_name, $a_charset="utf8", $a_collation="")
const MYSQL_ENGINE_INNODB
tableColumnExists($table_name, $column_name)
dropPrimaryKey($table_name)
supportsEngineMigration()
setLimit($limit, $offset=0)
Set the Limit for the next Query.
dropTableColumn($table_name, $column_name)
dropIndexByFields($table_name, $fields)
checkColumn($a_col, $a_def)
groupConcat($a_field_name, $a_seperator=",", $a_order=null)
string
constraintName($a_table, $a_constraint)
Determine contraint name by table name and constraint name.
prepareManip($query, $types=null)
getPrimaryKeyIdentifier()
Class ilDBPdoMySQLFieldDefinition.
createSequence($table_name, $start=1)
in($field, $values, $negate=false, $type="")
getAllowedAttributes()
array
buildManipSQL($table, $table_fields, $mode, $where=false)
setStorageEngine($storage_engine)
addUniqueConstraint($table, $fields, $name="con")
const FEATURE_TRANSACTIONS
addTableColumn($table_name, $column_name, $attributes)
locate($a_needle, $a_string, $a_start_pos=1)
fromUnixtime($a_expr, $a_to_text=true)
enableResultBuffering($a_status)
$a
thx to https://mlocati.github.io/php-cs-fixer-configurator for the examples
performance measurement class
primaryExistsByFields(string $table_name, array $fields)
bool
insert($table_name, $values)
cast($a_field_name, $a_dest_type)
string;
Component logger with individual log levels by component id.
This class gives all kind of DB information using the database manager and reverse module...
connect($return_false_for_error=false)
uniqueConstraintExists($table, array $fields)
renameTable($a_name, $a_new_name)
dropIndex($a_table, $a_name="i1")
migrateAllTablesToEngine($engine=ilDBConstants::MYSQL_ENGINE_INNODB)
prepare($query, $types=null, $result_types=null)
fetchObject($query_result)
substr($a_exp, $a_pos=1, $a_len=-1)
initFromIniFile($tmpClientIniFile=null)
fetchAll($query_result, $fetch_mode=ilDBConstants::FETCHMODE_ASSOC)
for($i=6; $i< 13; $i++) for($i=1; $i< 13; $i++) $d
getIndexName($index_name_base)
checkColumnDefinition($a_def, $a_modify_mode=false)