30require_once DOL_DOCUMENT_ROOT.
'/core/db/DoliDB.class.php';
54 const WEEK_MONDAY_FIRST = 1;
56 const WEEK_FIRST_WEEKDAY = 4;
75 if (!empty(
$conf->db->character_set)) {
76 $this->forcecharset =
$conf->db->character_set;
78 if (!empty(
$conf->db->dolibarr_main_db_collation)) {
79 $this->forcecollate =
$conf->db->dolibarr_main_db_collation;
82 $this->database_user = $user;
83 $this->database_host = $host;
84 $this->database_port = $port;
86 $this->transaction_opened = 0;
110 $this->db = $this->
connect($host, $user, $pass, $name, $port);
113 $this->connected =
true;
115 $this->database_selected =
true;
116 $this->database_name = $name;
129 $this->connected =
false;
131 $this->database_selected =
false;
132 $this->database_name =
'';
134 dol_syslog(get_class($this).
"::DoliDBSqlite3 : Error Connect ".$this->
error, LOG_ERR);
149 if (preg_match(
'/^--\s\$Id/i', $line)) {
153 if (preg_match(
'/^#/i', $line) || preg_match(
'/^$/i', $line) || preg_match(
'/^--/i', $line)) {
157 if (
$type ==
'auto') {
158 if (preg_match(
'/ALTER TABLE/i', $line)) {
160 } elseif (preg_match(
'/CREATE TABLE/i', $line)) {
162 } elseif (preg_match(
'/DROP TABLE/i', $line)) {
167 if (
$type ==
'dml') {
168 $line = preg_replace(
'/\s/',
' ', $line);
171 if (preg_match(
'/(ISAM|innodb)/i', $line)) {
172 $line = preg_replace(
'/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i',
');', $line);
173 $line = preg_replace(
'/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i',
');', $line);
174 $line = preg_replace(
'/,$/',
'', $line);
178 if (preg_match(
'/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
179 $newline = preg_replace(
'/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i',
'\\1 \\2 integer PRIMARY KEY AUTOINCREMENT', $line);
185 $line = str_replace(
'tinyint',
'smallint', $line);
188 $line = preg_replace(
'/(int\w+|smallint)\s+unsigned/i',
'\\1', $line);
191 $line = preg_replace(
'/\w*blob/i',
'text', $line);
194 $line = preg_replace(
'/tinytext/i',
'text', $line);
195 $line = preg_replace(
'/mediumtext/i',
'text', $line);
199 $line = preg_replace(
'/datetime not null/i',
'datetime', $line);
200 $line = preg_replace(
'/datetime/i',
'timestamp', $line);
203 $line = preg_replace(
'/^double/i',
'numeric', $line);
204 $line = preg_replace(
'/(\s*)double/i',
'\\1numeric', $line);
206 $line = preg_replace(
'/^float/i',
'numeric', $line);
207 $line = preg_replace(
'/(\s*)float/i',
'\\1numeric', $line);
210 if (preg_match(
'/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line)) {
211 $line = preg_replace(
'/unique index\s*\((\w+\s*,\s*\w+)\)/i',
'UNIQUE\(\\1\)', $line);
215 $line = preg_replace(
'/AFTER [a-z0-9_]+/i',
'', $line);
218 $line = preg_replace(
'/ALTER TABLE [a-z0-9_]+ DROP INDEX/i',
'DROP INDEX', $line);
221 if (preg_match(
'/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg)) {
222 $line =
"-- ".$line.
" replaced by --\n";
223 $line .=
"ALTER TABLE ".$reg[1].
" RENAME COLUMN ".$reg[2].
" TO ".$reg[3];
227 if (preg_match(
'/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg)) {
228 $line =
"-- ".$line.
" replaced by --\n";
230 $newreg3 = preg_replace(
'/ DEFAULT NULL/i',
'', $newreg3);
231 $newreg3 = preg_replace(
'/ NOT NULL/i',
'', $newreg3);
232 $newreg3 = preg_replace(
'/ NULL/i',
'', $newreg3);
233 $newreg3 = preg_replace(
'/ DEFAULT 0/i',
'', $newreg3);
234 $newreg3 = preg_replace(
'/ DEFAULT \'[0-9a-zA-Z_@]*\'/i',
'', $newreg3);
235 $line .=
"ALTER TABLE ".$reg[1].
" ALTER COLUMN ".$reg[2].
" TYPE ".$newreg3;
241 if (preg_match(
'/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i', $line, $reg)) {
242 $line =
"-- ".$line.
" replaced by --\n";
243 $line .=
"CREATE UNIQUE INDEX ".$reg[2].
" ON ".$reg[1].
"(".$reg[3];
248 if (preg_match(
'/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
249 $line =
"-- ".$line.
" replaced by --\n";
250 $line .=
"ALTER TABLE ".$reg[1].
" DROP CONSTRAINT ".$reg[2];
255 if (preg_match(
'/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i', $line, $reg)) {
256 $fieldlist = $reg[4];
258 $tablename = $reg[1];
259 $line =
"-- ".$line.
" replaced by --\n";
260 $line .=
"CREATE ".(preg_match(
'/UNIQUE/', $reg[2]) ?
'UNIQUE ' :
'').
"INDEX ".$idxname.
" ON ".$tablename.
" (".$fieldlist.
")";
262 if (preg_match(
'/ALTER\s+TABLE\s*(.*)\s*ADD\s+CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*\(([\w,\s]+)\)\s*REFERENCES\s+(\w+)\s*\(([\w,\s]+)\)/i', $line, $reg)) {
264 dol_syslog(get_class().
'::query line emptied');
275 if (preg_match(
'/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg)) {
276 if ($reg[1] == $reg[2]) {
277 $line = preg_replace(
'/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',
'DELETE FROM \\1 USING \\3', $line);
282 $line = preg_replace(
'/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i',
'FROM \\1', $line);
286 $line = preg_replace(
'/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i',
'FROM \\1, \\2', $line);
290 $line = preg_replace(
'/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i',
'FROM \\1, \\2, \\3', $line);
309 dol_syslog(get_class($this).
"::select_db database=".$database, LOG_DEBUG);
327 public function connect($host, $login, $passwd, $name, $port = 0)
329 global $main_data_dir;
331 dol_syslog(get_class($this).
"::connect name=".$name, LOG_DEBUG);
333 $dir = $main_data_dir;
335 $dir = DOL_DATA_ROOT;
339 $database_name = $dir.
'/database_'.$name.
'.sdb';
343 $this->db =
new SQLite3($database_name);
346 $this->
error = self::LABEL.
' '.$e->getMessage().
' current dir='.$database_name;
362 $tmp = $this->db->version();
363 return $tmp[
'versionString'];
373 return 'sqlite3 php driver';
386 if ($this->transaction_opened > 0) {
387 dol_syslog(get_class($this).
"::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
389 $this->connected =
false;
407 public function query($query, $usesavepoint = 0,
$type =
'auto', $result_mode = 0)
409 global
$conf, $dolibarr_main_db_readonly;
413 $query = trim($query);
419 if (preg_match(
'/ALTER\s+TABLE\s*(.*)\s*ADD\s+CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*\(([\w,\s]+)\)\s*REFERENCES\s+(\w+)\s*\(([\w,\s]+)\)/i', $query, $reg)) {
424 $foreignFields = $reg[5];
425 $foreignTable = $reg[4];
426 $localfields = $reg[3];
427 $constraintname = trim($reg[2]);
428 $tablename = trim($reg[1]);
430 $descTable = $this->db->querySingle(
"SELECT sql FROM sqlite_master WHERE name='".$this->
escape($tablename).
"'");
433 $this->
query(
"ALTER TABLE ".$tablename.
" RENAME TO tmp_".$tablename);
438 $descTable = substr($descTable, 0, strlen($descTable) - 1);
439 $descTable .=
", CONSTRAINT ".$constraintname.
" FOREIGN KEY (".$localfields.
") REFERENCES ".$foreignTable.
"(".$foreignFields.
")";
445 $this->
query($descTable);
448 $this->
query(
"INSERT INTO ".$tablename.
" SELECT * FROM tmp_".$tablename);
451 $this->
query(
"DROP TABLE tmp_".$tablename);
460 if (!in_array($query, array(
'BEGIN',
'COMMIT',
'ROLLBACK'))) {
461 $SYSLOG_SQL_LIMIT = 10000;
462 dol_syslog(
'sql='.substr($query, 0, $SYSLOG_SQL_LIMIT), LOG_DEBUG);
468 if (!empty($dolibarr_main_db_readonly)) {
469 if (preg_match(
'/^(INSERT|UPDATE|REPLACE|DELETE|CREATE|ALTER|TRUNCATE|DROP)/i', $query)) {
470 $this->
lasterror =
'Application in read-only mode';
480 $ret = $this->db->query($query);
482 $this->queryString = $query;
485 $this->
error = $this->db->lastErrorMsg();
488 if (!preg_match(
"/^COMMIT/i", $query) && !preg_match(
"/^ROLLBACK/i", $query)) {
490 if (!is_object($ret) || $this->
error) {
495 dol_syslog(get_class($this).
"::query SQL Error query: ".$query, LOG_ERR);
497 $errormsg = get_class($this).
"::query SQL Error message: ".$this->lasterror;
499 if (preg_match(
'/[0-9]/', $this->
lasterrno)) {
500 $errormsg .=
' ('.$this->lasterrno.
')';
503 if (
$conf->global->SYSLOG_LEVEL < LOG_DEBUG) {
504 dol_syslog(get_class($this).
"::query SQL Error query: ".$query, LOG_ERR);
506 dol_syslog(get_class($this).
"::query SQL Error message: ".$errormsg, LOG_ERR);
509 $this->_results = $ret;
526 if (!is_object($resultset)) {
527 $resultset = $this->_results;
530 $ret = $resultset->fetchArray(SQLITE3_ASSOC);
532 return (
object) $ret;
549 if (!is_object($resultset)) {
550 $resultset = $this->_results;
553 $ret = $resultset->fetchArray(SQLITE3_ASSOC);
568 if (!is_bool($resultset)) {
569 if (!is_object($resultset)) {
570 $resultset = $this->_results;
572 return $resultset->fetchArray(SQLITE3_NUM);
592 if (!is_object($resultset)) {
593 $resultset = $this->_results;
596 if (preg_match(
"/^SELECT/i", $resultset->queryString)) {
598 return $this->db->querySingle(
"SELECT count(*) FROM (".$resultset->queryString.
") q");
616 if (!is_object($resultset)) {
617 $resultset = $this->_results;
619 if (preg_match(
"/^SELECT/i", $this->queryString)) {
624 return $this->db->changes();
634 public function free($resultset =
null)
637 if (!is_object($resultset)) {
638 $resultset = $this->_results;
641 if ($resultset && is_object($resultset)) {
642 $resultset->finalize();
654 return Sqlite3::escapeString($stringtoencode);
665 return str_replace(array(
'\\',
'_',
'%'), array(
'\\\\',
'\_',
'\%'), (
string) $stringtoencode);
675 if (!$this->connected) {
677 return 'DB_ERROR_FAILED_TO_CONNECT';
712 $errno = $this->db->lastErrorCode();
713 if ($errno ==
'HY000' || $errno == 0) {
714 if (preg_match(
'/table.*already exists/i', $this->
error)) {
715 return 'DB_ERROR_TABLE_ALREADY_EXISTS';
716 } elseif (preg_match(
'/index.*already exists/i', $this->
error)) {
717 return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
718 } elseif (preg_match(
'/syntax error/i', $this->
error)) {
719 return 'DB_ERROR_SYNTAX';
722 if ($errno ==
'23000') {
723 if (preg_match(
'/column.* not unique/i', $this->
error)) {
724 return 'DB_ERROR_RECORD_ALREADY_EXISTS';
725 } elseif (preg_match(
'/PRIMARY KEY must be unique/i', $this->
error)) {
726 return 'DB_ERROR_RECORD_ALREADY_EXISTS';
733 return ($errno ?
'DB_ERROR_'.$errno :
'0');
744 if (!$this->connected) {
746 return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version';
763 return $this->db->lastInsertRowId();
774 public function encrypt($fieldorvalue, $withQuotes = 1)
779 $cryptType = (!empty(
$conf->db->dolibarr_main_db_encryption) ?
$conf->db->dolibarr_main_db_encryption : 0);
782 $cryptKey = (!empty(
$conf->db->dolibarr_main_db_cryptkey) ?
$conf->db->dolibarr_main_db_cryptkey :
'');
784 $escapedstringwithquotes = ($withQuotes ?
"'" :
"").$this->
escape($fieldorvalue).($withQuotes ?
"'" :
"");
786 if ($cryptType && !empty($cryptKey)) {
787 if ($cryptType == 2) {
788 $escapedstringwithquotes =
"AES_ENCRYPT(".$escapedstringwithquotes.
", '".$this->
escape($cryptKey).
"')";
789 } elseif ($cryptType == 1) {
790 $escapedstringwithquotes =
"DES_ENCRYPT(".$escapedstringwithquotes.
", '".$this->
escape($cryptKey).
"')";
794 return $escapedstringwithquotes;
808 $cryptType = (
$conf->db->dolibarr_main_db_encryption ?
$conf->db->dolibarr_main_db_encryption : 0);
811 $cryptKey = (!empty(
$conf->db->dolibarr_main_db_cryptkey) ?
$conf->db->dolibarr_main_db_cryptkey :
'');
815 if ($cryptType && !empty($cryptKey)) {
816 if ($cryptType == 2) {
817 $return =
'AES_DECRYPT('.$value.
',\''.$cryptKey.
'\')
';
818 } elseif ($cryptType == 1) {
819 $return = 'DES_DECRYPT(
'.$value.',\
''.$cryptKey.
'\')
';
827 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
833 public function DDLGetConnectId()
840 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
852 public function DDLCreateDb($database, $charset = '
', $collation = '', $owner = '')
855 if (empty($charset)) {
856 $charset = $this->forcecharset;
858 if (empty($collation)) {
859 $collation = $this->forcecollate;
862 // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
863 $sql = "CREATE DATABASE ".$this->escape($database);
864 $sql .= " DEFAULT CHARACTER SET ".$this->escape($charset)." DEFAULT COLLATE ".$this->escape($collation);
866 dol_syslog($sql, LOG_DEBUG);
867 $ret = $this->query($sql);
872 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
880 public function DDLListTables($database, $table = '
')
883 $listtables = array();
887 $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i
', '', $table);
889 $like = "LIKE '".$this->escape($tmptable)."'";
891 $tmpdatabase = preg_replace('/[^a-z0-9\.\-\_]/i
', '', $database);
893 $sql = "SHOW TABLES FROM ".$tmpdatabase." ".$like.";";
895 $result = $this->query($sql);
897 while ($row = $this->fetch_row($result)) {
898 $listtables[] = $row[0];
904 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
912 public function DDLListTablesFull($database, $table = '
')
915 $listtables = array();
919 $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i
', '', $table);
921 $like = "LIKE '".$this->escape($tmptable)."'";
923 $tmpdatabase = preg_replace('/[^a-z0-9\.\-\_]/i
', '', $database);
925 $sql = "SHOW FULL TABLES FROM ".$tmpdatabase." ".$like.";";
927 $result = $this->query($sql);
929 while ($row = $this->fetch_row($result)) {
930 $listtables[] = $row;
936 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
945 public function DDLInfoTable($table)
948 $infotables = array();
950 $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i
', '', $table);
952 $sql = "SHOW FULL COLUMNS FROM ".$tmptable.";";
954 dol_syslog($sql, LOG_DEBUG);
955 $result = $this->query($sql);
957 while ($row = $this->fetch_row($result)) {
958 $infotables[] = $row;
964 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
977 public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
980 // @TODO: $fulltext_keys parameter is unused
985 // Keys found into the array $fields: type,value,attribute,null,default,extra
986 // ex. : $fields['rowid
'] = array(
987 // 'type'=>'int' or 'integer
',
989 // 'null'=>'not
null',
990 // 'extra
'=> 'auto_increment
'
992 $sql = "CREATE TABLE ".$this->sanitize($table)."(";
994 $sqlfields = array();
995 foreach ($fields as $field_name => $field_desc) {
996 $sqlfields[$i] = $this->sanitize($field_name)." ";
997 $sqlfields[$i] .= $this->sanitize($field_desc['type']);
998 if (!is_null($field_desc['value
']) && $field_desc['value
'] !== '') {
999 $sqlfields[$i] .= "(".$this->sanitize($field_desc['value
']).")";
1001 if (!is_null($field_desc['attribute
']) && $field_desc['attribute
'] !== '') {
1002 $sqlfields[$i] .= " ".$this->sanitize($field_desc['attribute
']);
1004 if (!is_null($field_desc['default']) && $field_desc['default'] !== '') {
1005 if (in_array($field_desc['type'], array('tinyint
', 'smallint
', 'int', 'double'))) {
1006 $sqlfields[$i] .= " DEFAULT ".((float) $field_desc['default']);
1007 } elseif ($field_desc['default'] == 'null' || $field_desc['default'] == 'CURRENT_TIMESTAMP
') {
1008 $sqlfields[$i] .= " DEFAULT ".$this->sanitize($field_desc['default']);
1010 $sqlfields[$i] .= " DEFAULT '".$this->escape($field_desc['default'])."'";
1013 if (!is_null($field_desc['null']) && $field_desc['null'] !== '') {
1014 $sqlfields[$i] .= " ".$this->sanitize($field_desc['null'], 0, 0, 1);
1016 if (!is_null($field_desc['extra
']) && $field_desc['extra
'] !== '') {
1017 $sqlfields[$i] .= " ".$this->sanitize($field_desc['extra
'], 0, 0, 1);
1021 if ($primary_key != "") {
1022 $pk = "PRIMARY KEY(".$this->sanitize($primary_key).")";
1028 if (is_array($unique_keys)) {
1030 foreach ($unique_keys as $key => $value) {
1031 $sqluq[$i] = "UNIQUE KEY '".$this->sanitize($key)."' ('".$this->escape($value)."')";
1035 if (is_array($keys)) {
1037 foreach ($keys as $key => $value) {
1038 $sqlk[$i] = "KEY ".$this->sanitize($key)." (".$value.")";
1042 $sql .= implode(',
', $sqlfields);
1043 if ($primary_key != "") {
1046 if ($unique_keys != "") {
1047 $sql .= ",".implode(',
', $sqluq);
1049 if (is_array($keys)) {
1050 $sql .= ",".implode(',
', $sqlk);
1053 //$sql .= " engine=".$this->sanitize($type);
1055 if (!$this->query($sql)) {
1062 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1069 public function DDLDropTable($table)
1072 $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i
', '', $table);
1074 $sql = "DROP TABLE ".$tmptable;
1076 if (!$this->query($sql)) {
1083 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1091 public function DDLDescTable($table, $field = "")
1094 $sql = "DESC ".$table." ".$field;
1096 dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
1097 $this->_results = $this->query($sql);
1098 return $this->_results;
1101 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1111 public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
1114 // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1115 // ex. : $field_desc = array('
type'=>'int','value
'=>'11
','null'=>'not
null','extra
'=> 'auto_increment
');
1116 $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
1117 $sql .= $field_desc['type'];
1118 if (isset($field_desc['value
']) && preg_match("/^[^\s]/i", $field_desc['value
'])) {
1119 if (!in_array($field_desc['type'], array('date
', 'datetime
'))) {
1120 $sql .= "(".$field_desc['value
'].")";
1123 if (isset($field_desc['attribute
']) && preg_match("/^[^\s]/i", $field_desc['attribute
'])) {
1124 $sql .= " ".$this->sanitize($field_desc['attribute
']);
1126 if (isset($field_desc['null']) && preg_match("/^[^\s]/i", $field_desc['null'])) {
1127 $sql .= " ".$this->sanitize($field_desc['null'], 0, 0, 1);
1129 if (isset($field_desc['default']) && preg_match("/^[^\s]/i", $field_desc['default'])) {
1130 if (in_array($field_desc['type'], array('tinyint
', 'smallint
', 'int', 'double'))) {
1131 $sql .= " DEFAULT ".((float) $field_desc['default']);
1132 } elseif ($field_desc['default'] == 'null' || $field_desc['default'] == 'CURRENT_TIMESTAMP
') {
1133 $sql .= " DEFAULT ".$this->sanitize($field_desc['default']);
1135 $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'";
1138 if (isset($field_desc['extra
']) && preg_match("/^[^\s]/i", $field_desc['extra
'])) {
1139 $sql .= " ".$this->sanitize($field_desc['extra
'], 0, 0, 1);
1141 $sql .= " ".$this->sanitize($field_position, 0, 0, 1);
1143 dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
1144 if (!$this->query($sql)) {
1150 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1159 public function DDLUpdateField($table, $field_name, $field_desc)
1162 $sql = "ALTER TABLE ".$this->sanitize($table);
1163 $sql .= " MODIFY COLUMN ".$this->sanitize($field_name)." ".$this->sanitize($field_desc['
type']);
1164 if ($field_desc['type'] == 'tinyint
' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar
') {
1165 $sql .= "(".$this->sanitize($field_desc['value
']).")";
1168 dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
1169 if (!$this->query($sql)) {
1175 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1183 public function DDLDropField($table, $field_name)
1186 $tmp_field_name = preg_replace('/[^a-z0-9\.\-\_]/i
', '', $field_name);
1188 $sql = "ALTER TABLE ".$this->sanitize($table)." DROP COLUMN `".$this->sanitize($tmp_field_name)."`";
1189 if (!$this->query($sql)) {
1190 $this->error = $this->lasterror();
1197 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1207 public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1210 $sql = "INSERT INTO user ";
1211 $sql .= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1212 $sql .= " VALUES ('
".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1213 $sql .= ",'Y
','Y
','Y
','Y
','Y
','Y
','Y
','Y
','Y
')";
1215 dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1216 $resql = $this->query($sql);
1221 $sql = "INSERT INTO db ";
1222 $sql .= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1223 $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1224 $sql .= ",'Y
','Y
','Y
','Y
','Y
','Y
','Y
','Y
','Y
')";
1226 dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1227 $resql = $this->query($sql);
1232 $sql = "FLUSH Privileges";
1234 dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1235 $resql = $this->query($sql);
1247 public function getDefaultCharacterSetDatabase()
1257 public function getListOfCharacterSet()
1261 $liste[$i]['charset
'] = 'UTF-8
';
1271 public function getDefaultCollationDatabase()
1281 public function getListOfCollation()
1285 $liste[$i]['charset
'] = 'UTF-8
';
1295 public function getPathOfDump()
1297 // FIXME: not for SQLite
1298 $fullpathofdump = '/pathtomysqldump/mysqldump
';
1300 $resql = $this->query('SHOW VARIABLES LIKE \
'basedir\'');
1303 $basedir = $liste[
'Value'];
1304 $fullpathofdump = $basedir.(preg_match(
'/\/$/', $basedir) ?
'' :
'/').
'bin/mysqldump';
1306 return $fullpathofdump;
1317 $fullpathofimport =
'/pathtomysql/mysql';
1319 $resql = $this->
query(
'SHOW VARIABLES LIKE \'basedir\'');
1322 $basedir = $liste[
'Value'];
1323 $fullpathofimport = $basedir.(preg_match(
'/\/$/', $basedir) ?
'' :
'/').
'bin/mysql';
1325 return $fullpathofimport;
1338 if (!isset($pragmas)) {
1343 'application_id',
'auto_vacuum',
'automatic_index',
'busy_timeout',
'cache_size',
1344 'cache_spill',
'case_sensitive_like',
'checkpoint_fullsync',
'collation_list',
1345 'compile_options',
'data_version',
1346 'defer_foreign_keys',
'encoding',
'foreign_key_check',
'freelist_count',
1347 'full_column_names',
'fullsync',
'ingore_check_constraints',
'integrity_check',
1348 'journal_mode',
'journal_size_limit',
'legacy_file_format',
'locking_mode',
1349 'max_page_count',
'page_count',
'page_size',
'parser_trace',
1350 'query_only',
'quick_check',
'read_uncommitted',
'recursive_triggers',
1351 'reverse_unordered_selects',
'schema_version',
'user_version',
1352 'secure_delete',
'short_column_names',
'shrink_memory',
'soft_heap_limit',
1353 'synchronous',
'temp_store',
'threads',
1354 'vdbe_addoptrace',
'vdbe_debug',
'vdbe_listing',
'vdbe_trace',
1355 'wal_autocheckpoint',
1360 foreach ($pragmas as $var) {
1361 $sql =
"PRAGMA $var";
1362 $resql = $this->
query($sql);
1366 $result[$var] = $obj[0];
1369 $result[$var] =
'FAIL';
1411 $newname = preg_replace(
'/_/',
'', $name);
1412 $localname = __CLASS__.
'::db'.$newname;
1413 $reflectClass =
new ReflectionClass(__CLASS__);
1414 $reflectFunction = $reflectClass->getMethod(
'db'.$newname);
1415 if ($arg_count < 0) {
1416 $arg_count = $reflectFunction->getNumberOfParameters();
1418 if (!$this->db->createFunction($name, $localname, $arg_count)) {
1419 $this->
error =
"unable to create custom function '$name'";
Class to manage Dolibarr database access.
lastqueryerror()
Return last query in error.
lasterror()
Return last error label.
lasterrno()
Return last error code.
lastquery()
Return last request executed with query()
Class to manage Dolibarr database access for a SQLite database.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
escape($stringtoencode)
Escape a string to insert data.
fetch_array($resultset)
Return datas as an array.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
error()
Renvoie le texte de l'erreur mysql de l'operation precedente.
fetch_row($resultset)
Return datas as an array.
getPathOfRestore()
Return full path of restore program.
errno()
Renvoie le code erreur generique de l'operation precedente.
const LABEL
Database label.
close()
Close database connection.
escapeforlike($stringtoencode)
Escape a string to insert data into a like.
encrypt($fieldorvalue, $withQuotes=1)
Encrypt sensitive data in database Warning: This function includes the escape and add the SQL simple ...
last_insert_id($tab, $fieldid='rowid')
Get last ID after an insert INSERT.
affected_rows($resultset)
Return number of lines for result of a SELECT.
decrypt($value)
Decrypt sensitive data in database.
getDriverInfo()
Return version of database client driver.
addCustomFunction($name, $arg_count=-1)
Add a custom function in the database engine (STORED PROCEDURE) Notes:
select_db($database)
Select a database.
connect($host, $login, $passwd, $name, $port=0)
Connection to server.
num_rows($resultset)
Return number of lines for result of a SELECT.
convertSQLFromMysql($line, $type='ddl')
Convert a SQL request in Mysql syntax to native syntax.
getVersion()
Return version of database server.
getServerParametersValues($filter='')
Return value of server parameters.
free($resultset=null)
Free last resultset used.
__construct($type, $host, $user, $pass, $name='', $port=0)
Constructor.
const VERSIONMIN
Version min database.
getServerStatusValues($filter='')
Return value of server status.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type