72 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
93 public function connect($return_false_for_error =
false)
102 $this->error_code = $e->getCode();
103 if ($return_false_for_error) {
109 return ($this->pdo->errorCode() == PDO::ERR_NONE);
175 return $this->
query($this->manager->getQueryUtils()->createDatabase($a_name, $a_charset, $a_collation));
176 }
catch (PDOException
$e) {
187 if ($this->pdo instanceof PDO) {
188 return $this->pdo->errorCode();
202 if ($tmpClientIniFile instanceof
ilIniFile) {
203 $clientIniFile = $tmpClientIniFile;
205 $ilClientIniFile = null;
206 if ($DIC->offsetExists(
'ilClientIniFile')) {
207 $clientIniFile = $DIC[
'ilClientIniFile'];
213 $this->
setUsername($clientIniFile->readVariable(
"db",
"user"));
214 $this->
setHost($clientIniFile->readVariable(
"db",
"host"));
215 $this->
setPort((
int) $clientIniFile->readVariable(
"db",
"port"));
216 $this->
setPassword($clientIniFile->readVariable(
"db",
"pass"));
217 $this->
setDbname($clientIniFile->readVariable(
"db",
"name"));
218 $this->
setDBType($clientIniFile->readVariable(
"db",
"type"));
240 return '`' . $identifier .
'`';
249 abstract public function nextId($table_name);
260 public function createTable($table_name, $fields, $drop_table =
false, $ignore_erros =
false)
276 return $this->manager->createTable($table_name, $fields, array());
286 foreach ($a_cols as $col => $def) {
322 return $this->field_definition->checkColumnDefinition($a_def);
332 return $this->field_definition->checkColumnName($a_name);
344 assert(is_array($primary_keys));
347 foreach ($primary_keys as
$f) {
348 $fields[
$f] = array();
368 foreach ($this->manager->listTableIndexes($table_name) as $idx_name) {
369 $def = $this->reverse->getTableIndexDefinition($table_name, $idx_name);
370 $idx_fields = array_keys((array) $def[
'fields']);
372 if ($idx_fields === $fields) {
373 return $this->
dropIndex($table_name, $idx_name);
396 $this->manager->createSequence($table_name, $start);
407 $result = $this->pdo->prepare(
"SHOW TABLES LIKE :table_name");
408 $result->execute(array(
'table_name' => $table_name));
426 $in_array = in_array($column_name, $fields);
442 throw new ilDatabaseException(
"ilDB Error: addTableColumn(" . $table_name .
", " . $column_name .
")");
445 throw new ilDatabaseException(
"ilDB Error: addTableColumn(" . $table_name .
", " . $column_name .
")");
454 return $this->manager->alterTable($table_name, $changes,
false);
464 public function dropTable($table_name, $error_if_not_existing =
true)
467 $tables = $ilDBPdoManager->listTables();
468 $table_exists = in_array($table_name, $tables);
469 if (!$table_exists && $error_if_not_existing) {
474 $sequences = $ilDBPdoManager->listSequences();
475 if (in_array($table_name, $sequences)) {
476 $ilDBPdoManager->dropSequence($table_name);
481 $ilDBPdoManager->dropTable($table_name);
506 if (
$ilBench instanceof ilBenchmark) {
509 }
catch (PDOException
$e) {
513 $err = $this->pdo->errorCode();
514 if ($err != PDO::ERR_NONE) {
515 $info = $this->pdo->errorInfo();
516 $info_message = $info[2];
535 while (
$data = $query_result->fetch($fetch_mode)) {
548 $this->manager->dropSequence($table_name);
562 $column_name => array(),
566 return $this->manager->alterTable($table_name, $changes,
false);
581 throw new ilDatabaseException(
"ilDB Error: renameTableColumn(" . $table_name .
"," . $column_old_name .
"," . $column_new_name .
")");
584 $def = $this->reverse->getTableFieldDefinition($table_name, $column_old_name);
587 $best_alt = $analyzer->getBestDefinitionAlternative($def);
588 $def = $def[$best_alt];
589 unset($def[
"nativetype"]);
590 unset($def[
"mdb2type"]);
592 $f[
"definition"] = $def;
593 $f[
"name"] = $column_new_name;
597 $column_old_name =>
$f,
601 return $this->manager->alterTable($table_name, $changes,
false);
610 public function insert($table_name, $values)
614 foreach ($values as $key => $val) {
615 $real[] = $this->
quote($val[1], $val[0]);
618 $values = implode(
",", $real);
619 $fields = implode(
",", $fields);
620 $query =
"INSERT INTO " . $this->
quoteIdentifier($table_name) .
" (" . $fields .
") VALUES (" . $values .
")";
624 return $this->pdo->exec(
$query);
635 $res = $query_result->fetchObject();
637 $query_result->closeCursor();
655 $field_values = array();
656 $placeholders = array();
657 $placeholders_full = array();
663 $field_value = $col[1];
665 $placeholders[] =
"%s";
666 $placeholders_full[] =
":$k";
669 if ($col[0] ==
"blob" || $col[0] ==
"clob" || $col[0] ==
'text') {
674 if ($col[0] ==
'integer' && !is_null($field_value)) {
675 $field_value = (int) $field_value;
678 $values[] = $field_value;
679 $field_values[$k] = $field_value;
680 if ($col[0] ==
"blob" || $col[0] ==
"clob") {
689 foreach ($fields as $k => $field) {
690 $q .= $lim . $field .
" = " . $placeholders_full[$k];
695 foreach ($where as $k => $col) {
696 $q .= $lim . $k .
" = " . $this->
quote($col[1], $col[0]);
701 $this->
execute($r, $field_values);
704 foreach ($where as $k => $col) {
707 $field_values[$k] = $col;
711 foreach ($fields as $k => $field) {
712 $q .= $lim . $this->
quoteIdentifier($field) .
" = " . $placeholders[$k];
717 foreach ($where as $k => $col) {
718 $q .= $lim . $k .
" = %s";
744 $r = $this->pdo->exec(
$query);
745 if (
$ilBench instanceof ilBenchmark) {
748 }
catch (PDOException
$e) {
763 $res = $query_result->fetch(PDO::FETCH_ASSOC);
765 $query_result->closeCursor();
781 return $query_result->rowCount();
793 if ($value === null) {
797 $pdo_type = PDO::PARAM_STR;
807 $value = (int) $value;
812 $pdo_type = PDO::PARAM_INT;
816 $pdo_type = PDO::PARAM_STR;
820 return $this->pdo->quote($value, $pdo_type);
832 foreach ($this->manager->listTableIndexes($table_name) as $idx_name) {
833 $def = $this->reverse->getTableIndexDefinition($table_name, $idx_name);
834 $idx_fields = array_keys((array) $def[
'fields']);
836 if ($idx_fields === $fields) {
851 public function addIndex($table_name, $fields, $index_name =
'', $fulltext =
false)
853 assert(is_array($fields));
854 $this->field_definition->checkIndexName($index_name);
856 $definition_fields = array();
857 foreach ($fields as
$f) {
858 $definition_fields[
$f] = array();
861 'fields' => $definition_fields,
865 $this->manager->createIndex($table_name, $this->
constraintName($table_name, $index_name), $definition);
886 $f_str = implode(
",", $a_fields);
887 $q =
"ALTER TABLE $a_table ADD FULLTEXT $i_name ($f_str)";
898 $this->
query(
"ALTER TABLE $a_table DROP FULLTEXT $i_name");
907 $set = $this->
query(
"SHOW INDEX FROM " . $a_table);
909 if ($rec[
"Key_name"] == $a_name && $rec[
"Index_type"] ==
"FULLTEXT") {
944 return $a_constraint;
972 $this->db_type =
$type;
983 $ilDB = $DIC->database();
988 return $ilDB->getFieldDefinition()->getReservedMysql();
998 assert(is_array($tables));
1000 $lock = $this->manager->getQueryUtils()->lock($tables);
1002 $ilLogger = $DIC->logger()->root();
1003 if ($ilLogger instanceof
ilLogger) {
1004 $ilLogger->log(
'ilDB::lockTables(): ' . $lock);
1007 $this->pdo->exec($lock);
1017 $this->pdo->exec($this->manager->getQueryUtils()->unlock());
1028 public function in($field, $values, $negate =
false,
$type =
"")
1030 return $this->manager->getQueryUtils()->in($field, $values, $negate,
$type);
1043 if (!is_array($types) || !is_array($values) || count($types) != count($values)) {
1044 throw new ilDatabaseException(
"ilDB::queryF: Types and values must be arrays of same size. ($query)");
1046 $quoted_values = array();
1047 foreach ($types as $k => $t) {
1048 $quoted_values[] = $this->
quote($values[$k], $t);
1065 if (!is_array($types) || !is_array($values) || count($types) != count($values)) {
1066 throw new ilDatabaseException(
"ilDB::manipulateF: types and values must be arrays of same size. ($query)");
1068 $quoted_values = array();
1069 foreach ($types as $k => $t) {
1070 $quoted_values[] = $this->
quote($values[$k], $t);
1111 public function like($column,
$type, $value =
"?", $case_insensitive =
true)
1113 return $this->manager->getQueryUtils()->like($column,
$type, $value, $case_insensitive);
1122 return $this->manager->getQueryUtils()->now();
1134 public function replace($table, $primaryKeys, $otherColumns)
1136 $a_columns = array_merge($primaryKeys, $otherColumns);
1138 $field_values = array();
1139 $placeholders = array();
1143 foreach ($a_columns as $k => $col) {
1145 $placeholders[] =
"%s";
1146 $placeholders2[] =
":$k";
1150 if ($col[0] ==
'integer' && !is_null($col[1])) {
1151 $col[1] = (int) $col[1];
1154 $values[] = $col[1];
1155 $field_values[$k] = $col[1];
1158 $q =
"REPLACE INTO " . $table .
" (" . implode(
",", $fields) .
") VALUES (" . implode(
",", $placeholders) .
")";
1175 if (!$emptyOrNull || $value !=
"") {
1178 return "(" .
$columns .
" = '' OR $columns IS NULL)";
1197 $this->host =
$host;
1287 $this->port =
$port;
1333 return " UPPER(" . $a_exp .
") ";
1343 return " LOWER(" . $a_exp .
") ";
1353 public function substr($a_exp, $a_pos = 1, $a_len = -1)
1357 $lenstr =
", " . $a_len;
1360 return " SUBSTR(" . $a_exp .
", " . $a_pos . $lenstr .
") ";
1392 $this->pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, $a_status);
1449 case self::FEATURE_TRANSACTIONS:
1451 case self::FEATURE_FULLTEXT:
1453 case self::FEATURE_SLAVE:
1466 return $this->manager->listTables();
1490 return $this->field_definition->getAllowedAttributes();
1509 return $this->manager->listSequences();
1518 public function concat(array $values, $allow_null =
true)
1520 return $this->manager->getQueryUtils()->concat($values, $allow_null);
1530 if ($this->limit !== null && $this->offset !== null) {
1532 $this->limit = null;
1533 $this->offset = null;
1548 public function locate($a_needle, $a_string, $a_start_pos = 1)
1550 return $this->manager->getQueryUtils()->locate($a_needle, $a_string, $a_start_pos);
1563 $def = $this->reverse->getTableFieldDefinition($table, $a_column);
1566 $best_alt = $analyzer->getBestDefinitionAlternative($def);
1567 $def = $def[$best_alt];
1568 unset($def[
"nativetype"]);
1569 unset($def[
"mdb2type"]);
1574 $type = ($a_attributes[
"type"] ??
"" !=
"") ? $a_attributes[
"type"] : $def[
"type"];
1575 foreach ($def as $k => $v) {
1576 if ($k !=
"type" && !$ilDBPdoFieldDefinition->isAllowedAttribute($k,
$type)) {
1580 $check_array = $def;
1581 foreach ($a_attributes as $k => $v) {
1582 $check_array[$k] = $v;
1585 throw new ilDatabaseException(
"ilDB Error: modifyTableColumn(" . $table .
", " . $a_column .
")");
1588 foreach ($a_attributes as
$a => $v) {
1592 $a_attributes[
"definition"] = $def;
1596 $a_column => $a_attributes,
1600 return $this->manager->alterTable($table, $changes,
false);
1608 public function free($a_st)
1613 return $a_st->closeCursor();
1629 throw new ilDatabaseException(
"ilDB Error: renameTable(" . $a_name .
"," . $a_new_name .
")<br />" . $e->getMessage());
1632 $this->manager->alterTable($a_name, [
"name" => $a_new_name],
false);
1652 return $this->field_definition->checkTableName($a_name);
1665 return $ilDBPdoMySQLFieldDefinition->
isReserved($a_word);
1675 if (!$this->
supports(self::FEATURE_TRANSACTIONS)) {
1679 return $this->pdo->beginTransaction();
1689 if (!$this->
supports(self::FEATURE_TRANSACTIONS)) {
1693 return $this->pdo->commit();
1703 if (!$this->
supports(self::FEATURE_TRANSACTIONS)) {
1707 return $this->pdo->rollBack();
1718 return $this->manager->dropIndex($a_table, $a_name);
1750 $type = PDO::FETCH_ASSOC;
1753 $type = PDO::FETCH_OBJ;
1756 $type = PDO::FETCH_ASSOC;
1760 return $this->pdo->query(
$query, PDO::FETCH_ASSOC)->fetchAll(PDO::FETCH_COLUMN, $colnum);
1772 switch ($fetchmode) {
1774 $type = PDO::FETCH_ASSOC;
1777 $type = PDO::FETCH_OBJ;
1780 $type = PDO::FETCH_ASSOC;
1794 return $this->pdo->query(
'SELECT VERSION()')->fetchColumn();
1803 public function escape($value, $escape_wildcards =
false)
1876 assert(is_array($fields));
1884 $fields_corrected = array();
1885 foreach ($fields as
$f) {
1886 $fields_corrected[
$f] = array();
1888 $definition = array(
1890 'fields' => $fields_corrected,
1904 return $this->manager->dropConstraint($a_table, $this->
constraintName($a_table, $a_name),
false);
1916 $cons = $analyzer->getConstraintsInformation($a_table);
1917 foreach ($cons as
$c) {
1918 if ($c[
"type"] ==
"unique" && count($a_fields) == count($c[
"fields"])) {
1920 foreach ($a_fields as
$f) {
1921 if (!isset($c[
"fields"][$f])) {
1940 return $this->pdo->lastInsertId();
1961 $cons = $analyzer->getConstraintsInformation($table);
1962 foreach ($cons as
$c) {
1963 if ($c[
"type"] ==
"unique" && count($fields) == count($c[
"fields"])) {
1965 foreach ($fields as
$f) {
1966 if (!isset($c[
"fields"][$f])) {
1986 return $this->manager->dropConstraint($table_name,
"PRIMARY",
true);
1996 for (
$i = 0, $j = count($a_data);
$i < $j;
$i++) {
1997 $stmt->execute($a_data[
$i]);
2009 return "FROM_UNIXTIME(" . $a_expr .
")";
2018 return "UNIX_TIMESTAMP()";
2039 $fields_values = (array) $fields;
2041 if (!empty($fields_values)) {
2042 $keys = $fields_values;
2047 $keys = array_keys($fields_values);
2049 $params = array_values($fields_values);
2050 if (empty($params)) {
2054 $stmt = $this->
autoPrepare($tablename,
$keys, $mode, $where, $types, $result_types);
2091 if ($this->options[
'quote_identifier']) {
2095 if (!empty($table_fields) && $this->options[
'quote_identifier']) {
2096 foreach ($table_fields as $key => $field) {
2101 if ($where !==
false && !is_null($where)) {
2102 if (is_array($where)) {
2103 $where = implode(
' AND ', $where);
2105 $where =
' WHERE ' . $where;
2110 if (empty($table_fields)) {
2113 $cols = implode(
', ', $table_fields);
2114 $values =
'?' . str_repeat(
', ?', (count($table_fields) - 1));
2116 return 'INSERT INTO ' . $table .
' (' .
$cols .
') VALUES (' . $values .
')';
2119 if (empty($table_fields)) {
2122 $set = implode(
' = ?, ', $table_fields) .
' = ?';
2123 $sql =
'UPDATE ' . $table .
' SET ' . $set . $where;
2128 $sql =
'DELETE FROM ' . $table . $where;
2133 $cols = !empty($table_fields) ? implode(
', ', $table_fields) :
'*';
2134 $sql =
'SELECT ' .
$cols .
' FROM ' . $table . $where;
2152 return (
$d->version ?
$d->version :
'Unknown');
2162 $query_replaced = preg_replace(
2163 '/[\x{10000}-\x{10FFFF}]/u',
2167 if (!empty($query_replaced)) {
2168 return $query_replaced;
2187 public function groupConcat($a_field_name, $a_seperator =
",", $a_order = null)
2189 return $this->manager->getQueryUtils()->groupConcat($a_field_name, $a_seperator, $a_order);
2195 public function cast($a_field_name, $a_dest_type)
2197 return $this->manager->getQueryUtils()->cast($a_field_name, $a_dest_type);
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()
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
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)