Pdo.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. <?php
  2. Lib::loadClass('DBG');
  3. class Core_Pdo extends PDO {
  4. protected $_database_name;
  5. protected $_zasob_id;
  6. protected $_type;
  7. protected $_schema;
  8. // public PDO::__construct ( string $dsn [, string $username [, string $password [, array $options ]]] )
  9. public function __construct($dsn, $username, $password, $options = array()) {
  10. $this->_database_name = $options['database'];
  11. $this->_zasob_id = $options['zasob_id'];
  12. $this->_type = $options['type'];
  13. $this->_schema = (!empty($options['schema'])) ? $options['schema'] : null;
  14. unset($options['database']);
  15. unset($options['zasob_id']);
  16. parent::__construct($dsn, $username, $password, $options);
  17. $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  18. $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  19. $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1); // Default 1, fetch returns value types: |> 0 -> int, string, null |> 1 -> string, null
  20. }
  21. public function getDatabaseName() {
  22. return $this->_database_name;
  23. }
  24. public function getZasobId() {
  25. return $this->_zasob_id;
  26. }
  27. public function getType() {
  28. return strtolower($this->_type);
  29. }
  30. public function identifierQuote($identifier) {
  31. switch (strtolower($this->_type)) {
  32. // case 'pgsql': return $identifier;
  33. case 'pgsql': return "\"{$identifier}\""; // https://www.postgresql.org/docs/9.1/sql-syntax-lexical.html
  34. case 'mysql': return "`{$identifier}`";
  35. }
  36. return $identifier;
  37. }
  38. public function tableNameQuote($tableName) {
  39. switch (strtolower($this->_type)) {
  40. case 'pgsql': return ($this->_schema) ? "{$this->_schema}.{$tableName}" : $tableName; // "'{$identifier}'";
  41. case 'mysql': return "`{$tableName}`";
  42. }
  43. return $tableName;
  44. }
  45. public function getTableStruct($tblName) {// TODO: mved to Core_Storage_*
  46. $sth = $this->prepare("
  47. -- show fields from {$tblName}
  48. select cols.COLUMN_NAME as name
  49. , cols.DATA_TYPE as type
  50. , cols.COLUMN_TYPE as type_mysql
  51. , if('YES' = cols.IS_NULLABLE, 1, 0) as is_nullable
  52. , cols.COLUMN_DEFAULT as default_value
  53. , if(cols.COLUMN_DEFAULT is null, 1, 0) as default_is_null
  54. , cols.CHARACTER_MAXIMUM_LENGTH as max_length
  55. , cols.NUMERIC_PRECISION as num_precision
  56. , cols.NUMERIC_SCALE as num_scale
  57. , cols.CHARACTER_SET_NAME as char_encoding -- latin2
  58. , cols.COLLATION_NAME as char_collation -- latin2_general_ci
  59. , cols.EXTRA as extra
  60. -- , cols.*
  61. from INFORMATION_SCHEMA.COLUMNS cols
  62. where cols.TABLE_SCHEMA = :db_name
  63. and cols.TABLE_NAME = :tbl_name
  64. ");
  65. $sth->bindValue(':db_name', $this->getDatabaseName(), PDO::PARAM_STR);
  66. $sth->bindValue(':tbl_name', $tblName, PDO::PARAM_STR);
  67. $sth->execute();
  68. $structRaw = $sth->fetchAll();
  69. if (empty($structRaw)) throw new Exception("Empty struct for table '{$tblName}'", 404);
  70. foreach ($structRaw as $field) {
  71. $struct[$field['name']] = $field;
  72. }
  73. return $struct;
  74. }
  75. public function assertTableStructXsd($tblName, $expectedStructXsd) {
  76. throw new Exception("Unimplemented - TODO!");
  77. /*
  78. - `decimal(5,2)`:
  79. <xsd:element name="A" type="decimal_5_2"/>
  80. <xsd:simpleType name="decimal_5_2">
  81. <xsd:restriction base="xsd:decimal">
  82. <xsd:totalDigits value="5"/>
  83. <xsd:fractionDigits value="2"/>
  84. </xsd:restriction>
  85. </xsd:simpleType>
  86. */
  87. /* MySQL types:
  88. int tinyint smallint mediumint bigint
  89. decimal
  90. float double real => double
  91. date datetime timestamp time year
  92. char varchar
  93. text tinytext mediumtext longtext
  94. enum
  95. set
  96. bit
  97. boolean => `tinyint(1)` -- 0 or 1
  98. serial => `bigint(20) unsigned` and unique key
  99. binary varbinary
  100. blob tinyblob mediumblob longblob
  101. geometry point linestring polygon multipoint multilinestring multipolygon geometrycollection
  102. */
  103. }
  104. /*
  105. * TODO: update keys:
  106. * TODO: keys name may be different - try to find and connect with given schema?
  107. * TODO: remove old uniq keys?
  108. */
  109. public function assertTableStruct($tblName, $expectedStruct, $params = array()) {
  110. // TODO: make backup for table?
  111. $expectedStruct = $this->_fixExpectedStruct($expectedStruct);
  112. //DBG::_(true, true, "fixedEpectedStruct", $expectedStruct, __CLASS__, __FUNCTION__, __LINE__);
  113. //DBG::_(true, true, "fixedEpectedStruct", $this->showCreateStruct($tblName, $expectedStruct, $params), __CLASS__, __FUNCTION__, __LINE__);
  114. $struct = $this->getTableStruct($tblName);
  115. $expectedFields = array();//array_keys($expectedStruct);
  116. foreach ($expectedStruct as $fldName => $fld) {
  117. if ('UNIQUE KEY' == $fld['type']) continue;
  118. if ('KEY' == $fld['type']) continue;
  119. $expectedFields[] = $fldName;
  120. }
  121. $currentFields = array_keys($struct);
  122. $missingFields = array_diff($expectedFields, $currentFields);
  123. DBG::_(true, true, "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  124. DBG::_(true, true, "missingFields", $missingFields, __CLASS__, __FUNCTION__, __LINE__);
  125. foreach ($missingFields as $fldName) {
  126. $fld = $expectedStruct[$fldName];
  127. DBG::_(true, true, "add missing field[{$fldName}]:", $fld, __CLASS__, __FUNCTION__, __LINE__);
  128. $sqlFieldStruct = $this->showTableStructField($fldName, $fld);
  129. if ($sqlFieldStruct) {
  130. $sqlAdd = "alter table {$tblName} add {$sqlFieldStruct}";
  131. DBG::_(true, true, "sqlAdd", $sqlAdd, __CLASS__, __FUNCTION__, __LINE__);
  132. $this->exec($sqlAdd);
  133. } else {
  134. throw new Exception("Unimplemented type '{$fld['type']}': " . json_encode($fld));
  135. }
  136. }
  137. $toUpdateFields = array_intersect($expectedFields, $currentFields);
  138. DBG::_(true, true, "toUpdateFields", $toUpdateFields, __CLASS__, __FUNCTION__, __LINE__);
  139. foreach ($toUpdateFields as $fldName) {
  140. $current = $struct[$fldName];
  141. $expected = $expectedStruct[$fldName];
  142. $needChange = false;
  143. $sqlFieldStruct = $this->showTableStructField($fldName, $expected);
  144. if (!$sqlFieldStruct) throw new Exception("Unimplemented type '{$expected['type']}' for field '{$fldName}': " . json_encode($expected));
  145. $sqlChange = "alter table `{$tblName}` change `{$fldName}` {$sqlFieldStruct}";
  146. DBG::_(true, true, "DBG: sqlChange", $sqlChange, __CLASS__, __FUNCTION__, __LINE__);
  147. //DBG::_(true, true, "TODO: update field[{$fldName}]:", array('expected'=>$expected,'current'=>$current), __CLASS__, __FUNCTION__, __LINE__);
  148. if ($current['type'] != $expected['type']) {
  149. throw new Exception("Unimplemented change field type from '{$current['type']}' to '{$expected['type']}' for field '{$fldName}': " . json_encode($expected));
  150. }
  151. if ($current['is_nullable'] != $expected['is_nullable']) {
  152. $needChange = true;
  153. if ($current['is_nullable'] && !$expected['is_nullable']) {
  154. throw new Exception("Field struct needs change 'is_nullable' to false but this change is not implemented - field '{$fldName}': " . json_encode(array('expected'=>$expected,'current'=>$current)));
  155. }
  156. }
  157. if ($current['max_length'] != $expected['max_length']) {
  158. $needChange = true;
  159. if ($current['max_length'] > $expected['max_length']) {
  160. throw new Exception("Field struct needs decrease 'max_length' but this change is not implemented - field '{$fldName}': " . json_encode(array('expected'=>$expected,'current'=>$current)));
  161. }
  162. }
  163. if ($current['default_value'] !== $expected['default_value']) $needChange = true;
  164. if ($needChange) {
  165. DBG::_(true, true, "EXEC sqlChange ...", $sqlChange, __CLASS__, __FUNCTION__, __LINE__);
  166. $this->exec($sqlChange);
  167. }
  168. }
  169. }
  170. /* assert's that field struct has defined or throw exception if cannot set default value:
  171. ['type'] = 'varchar', 'int', ... (MySQL Types)
  172. ['is_nullable'] = true, false
  173. ['default_value'] = NULL or (string, numeric - based on type)
  174. default_value is not set when default_value == NULL and is_nullable == false
  175. ['default_is_null'] = true, false
  176. ['max_length'] = NULL, [0-...] // MySQL `CHARACTER_MAXIMUM_LENGTH`
  177. ['num_precision'] = NULL, [0-65]
  178. ['num_scale'] = NULL, [0-12]
  179. ['char_encoding'] = 'utf8', 'latin2', ...
  180. ['char_collation'] = 'utf8_general_ci', 'latin2_general_ci', ...
  181. ['extra'] = 'auto_increment', 'on update CURRENT_TIMESTAMP'
  182. ['values'] = null or array for enum and set
  183. TODO: validate - wrong related values. ex: {type: 'int', char_collation: 'latin2'}
  184. TODO: validate - not allowed value. ex: {type: 'xyz'}
  185. */
  186. public function _fixExpectedStruct($expectedStruct) {
  187. $fixedStruct = array();
  188. foreach ($expectedStruct as $fldName => $expected) {
  189. //DBG::_(true, true, "TODO: expected", $expected, __CLASS__, __FUNCTION__, __LINE__);
  190. if (!array_key_exists('type', $expected)) throw new Exception("Undefined type for field '{$fldName}'");
  191. if (!array_key_exists('is_nullable', $expected)) {
  192. $expected['is_nullable'] = false;
  193. if (array_key_exists('default_value', $expected) && null === $expected['default_value']) {
  194. $expected['is_nullable'] = true;
  195. }
  196. }
  197. if (!array_key_exists('default_is_null', $expected)) $expected['default_is_null'] = false;
  198. if (!array_key_exists('default_value', $expected)) {
  199. $expected['default_value'] = null;
  200. // switch ($expected['type']) {
  201. // case 'char':
  202. // case 'varchar': $expected['default_value'] = ($expected['is_nullable'])? null : ''; break;
  203. // case 'tinyint':
  204. // case 'bigint':
  205. // case 'int': $expected['default_value'] = ($expected['is_nullable'])? null : 0; break;
  206. // }
  207. if ($expected['is_nullable'] && null === $expected['default_value']) {
  208. $expected['default_is_null'] = true;
  209. }
  210. }
  211. if (!array_key_exists('max_length', $expected)) {
  212. switch ($expected['type']) {
  213. case 'char':
  214. case 'varchar': $expected['max_length'] = 255; break;
  215. case 'binary': $expected['max_length'] = 255; break;// bainary(0) is possible - why? Cannot store values.
  216. case 'varbinary': $expected['max_length'] = 255; break;
  217. case 'binary':
  218. case 'varbinary':
  219. case 'bit': throw new Exception("Undefined max_length for field '{$fldName}' with type '{$expected['type']}'");
  220. //case 'blob': $expected['max_length'] = 65535; break;// is set by engine
  221. //case 'tinyblob': $expected['max_length'] = 255; break;// is set by engine
  222. //case 'mediumblob': $expected['max_length'] = 16777215; break;// is set by engine
  223. //case 'longblob': $expected['max_length'] = 4294967295; break;// is set by engine
  224. //case 'text': $expected['max_length'] = 65535; break;// is set by engine
  225. //case 'tinytext': $expected['max_length'] = 255; break;// is set by engine
  226. //case 'mediumtext': $expected['max_length'] = 16777215; break;// is set by engine
  227. //case 'longtext': $expected['max_length'] = 4294967295; break;// is set by engine
  228. //case 'enum': $expected['max_length'] = 255; break;// is set by engine
  229. //case 'set': $expected['max_length'] = 255; break;// is set by engine
  230. default: $expected['max_length'] = null;//throw new Exception("Undefined max_length for field '{$fldName}'");
  231. }
  232. }
  233. if (!array_key_exists('num_precision', $expected)) {
  234. switch ($expected['type']) {
  235. case 'int': $expected['num_precision'] = 10; break;// int(11) - +1 in type definition
  236. case 'tinyint': $expected['num_precision'] = 3; break;// int(4)
  237. case 'smallint': $expected['num_precision'] = 5; break;// int(6)
  238. case 'mediumint': $expected['num_precision'] = 7; break;// int(8)
  239. case 'bigint': $expected['num_precision'] = 19; break;// int(20)
  240. case 'decimal': $expected['num_precision'] = 10; break;// decimal(10,0)
  241. default: $expected['num_precision'] = null;
  242. }
  243. //throw new Exception("Undefined num_precision for field '{$fldName}'");
  244. }
  245. if (!array_key_exists('num_scale', $expected)) {
  246. switch ($expected['type']) {
  247. case 'int': $expected['num_scale'] = 0; break;
  248. case 'tinyint': $expected['num_scale'] = 0; break;
  249. case 'smallint': $expected['num_scale'] = 0; break;
  250. case 'mediumint': $expected['num_scale'] = 0; break;
  251. case 'bigint': $expected['num_scale'] = 0; break;
  252. case 'decimal': $expected['num_scale'] = 0; break;// ex.: decimal(3,2); decimal(24,0)
  253. case 'double': $expected['num_scale'] = null; break;// ex.: double(10,4); double; double(17,0);
  254. case 'float': $expected['num_scale'] = null; break;// ex.: float(6,2); float; float(17,0);
  255. default: $expected['num_scale'] = null;
  256. }
  257. //throw new Exception("Undefined num_scale for field '{$fldName}'");
  258. }
  259. if (!array_key_exists('char_encoding', $expected)) {
  260. switch ($expected['type']) {
  261. case 'char':
  262. case 'varchar': $expected['char_encoding'] = 'utf8'; break;
  263. case 'enum':
  264. case 'set': $expected['char_encoding'] = 'utf8'; break;
  265. case 'text':
  266. case 'tinytext':
  267. case 'mediumtext':
  268. case 'longtext': $expected['char_encoding'] = 'utf8'; break;
  269. default: $expected['char_encoding'] = null;
  270. }
  271. //throw new Exception("Undefined char_encoding for field '{$fldName}'");
  272. }
  273. if (!array_key_exists('char_collation', $expected)) {
  274. switch ($expected['type']) {
  275. case 'char':
  276. case 'varchar': $expected['char_collation'] = 'utf8_general_ci'; break;
  277. case 'enum':
  278. case 'set': $expected['char_collation'] = 'utf8_general_ci'; break;
  279. case 'text':
  280. case 'tinytext':
  281. case 'mediumtext':
  282. case 'longtext': $expected['char_collation'] = 'utf8_general_ci'; break;
  283. default: $expected['char_collation'] = null;
  284. }
  285. //throw new Exception("Undefined char_collation for field '{$fldName}'");
  286. }
  287. if (!array_key_exists('extra', $expected)) {
  288. $expected['extra'] = null;//throw new Exception("Undefined extra for field '{$fldName}'");
  289. }
  290. if (!array_key_exists('values', $expected) || !is_array($expected['values']) || empty($expected['values'])) {
  291. switch ($expected['type']) {
  292. case 'enum':
  293. case 'set': throw new Exception("Undefined values for field '{$fldName}' with type '{$expected['type']}'");
  294. default: $expected['values'] = null;
  295. }
  296. }
  297. $fixedStruct[$fldName] = $expected;
  298. }
  299. return $fixedStruct;
  300. }
  301. public function showCreateStruct($tblName, $struct, $params = array()) {
  302. // TODO: check database type, if == MySQL - fix construct
  303. $expectedStruct = $this->_fixExpectedStruct($struct);
  304. $linesSql = array();
  305. $dbgSql = array();
  306. foreach ($expectedStruct as $fldName => $fld) {
  307. $sqlFieldStruct = $this->showTableStructField($fldName, $fld);
  308. if ($sqlFieldStruct) {
  309. $linesSql[] = $sqlFieldStruct;
  310. } else {
  311. $dbgSql[] = "-- Unimplemented type '{$fld['type']}': " . json_encode($fld);
  312. }
  313. }
  314. $linesSql = implode("\n\t\t, ", $linesSql);
  315. $dbgSql = implode("\n\t\t", $dbgSql);
  316. $tblCharEncoding = V::get('char_encoding', 'utf8', $params);
  317. $structSql = <<<EOF_STRUCT_MYSQL
  318. CREATE TABLE IF NOT EXISTS `{$tblName}` (
  319. {$linesSql}
  320. {$dbgSql}
  321. ) ENGINE=MyISAM DEFAULT CHARSET={$tblCharEncoding}
  322. EOF_STRUCT_MYSQL;
  323. return $structSql;
  324. }
  325. public function showTableStructField($fldName, $fld) {
  326. // TODO: check database type, if == MySQL - fix construct
  327. $nullSql = ($fld['is_nullable'])? '' : 'NOT NULL';
  328. $defaultSql = (is_null($fld['default_value']))? 'DEFAULT NULL' : "DEFAULT '{$fld['default_value']}'";
  329. if (is_null($fld['default_value']) && !$fld['is_nullable']) $defaultSql = '';
  330. switch ($fld['type']) {
  331. case 'char':
  332. case 'varchar': return "`{$fldName}` {$fld['type']}({$fld['max_length']}) {$nullSql} {$defaultSql}"; break;
  333. case 'text':
  334. case 'tinytext':
  335. case 'longtext':
  336. case 'mediumtext': return "`{$fldName}` {$fld['type']} {$nullSql}"; break;
  337. case 'time':
  338. case 'timestamp':
  339. case 'year':
  340. case 'date':
  341. case 'datetime': return "`{$fldName}` {$fld['type']} {$nullSql} {$defaultSql}"; break;
  342. // -- Unimplemented type 'int': {"type":"int","is_nullable":false,"default_is_null":false,"default_value":null,"max_length":null,"num_precision":10,"num_scale":0,"char_encoding":null,"char_collation":null,"extra":null}
  343. // -- Unimplemented type 'int': {"type":"int","num_precision":11,"default_value":null,"is_nullable":true,"default_is_null":false,"max_length":null,"num_scale":0,"char_encoding":null,"char_collation":null,"extra":null}
  344. case 'int':
  345. case 'tinyint':
  346. case 'smallint':
  347. case 'mediumint':
  348. case 'bigint':
  349. if ($fld['num_precision'] > 0) {
  350. $typeParamsSql = "(" . ($fld['num_precision'] + 1) . ")";
  351. }
  352. //if ($fld['num_scale']) $typeParamsSql = ",{$fld['num_scale']}";
  353. return "`{$fldName}` {$fld['type']}{$typeParamsSql} {$nullSql} {$defaultSql}";
  354. break;
  355. case 'decimal':
  356. $typeParamsSql = "{$fld['num_precision']},{$fld['num_scale']}";
  357. return "`{$fldName}` {$fld['type']}({$typeParamsSql}) {$nullSql} {$defaultSql}";
  358. break;
  359. case 'float':
  360. case 'double':
  361. case 'real':
  362. return "`{$fldName}` {$fld['type']} {$nullSql} {$defaultSql}";
  363. break;
  364. case 'enum':
  365. case 'set':
  366. $typeParamsSql = "'" . implode("','", $fld['values']) . "'";
  367. return "`{$fldName}` {$fld['type']}({$typeParamsSql}) {$nullSql} {$defaultSql}";
  368. break;
  369. case 'bit':
  370. case 'binary':
  371. case 'varbinary':
  372. return "`{$fldName}` {$fld['type']}({$fld['max_length']}) {$nullSql} {$defaultSql}";
  373. break;
  374. case 'boolean':
  375. case 'serial':
  376. case 'blob':
  377. case 'tinyblob':
  378. case 'mediumblob':
  379. case 'longblob':
  380. return "`{$fldName}` {$fld['type']} {$nullSql} {$defaultSql}";
  381. break;
  382. case 'geometry':
  383. case 'point':
  384. case 'linestring':
  385. case 'polygon':
  386. case 'multipoint':
  387. case 'multilinestring':
  388. case 'multipolygon':
  389. case 'geometrycollection':
  390. return "`{$fldName}` {$fld['type']} {$nullSql} {$defaultSql}";
  391. break;
  392. case 'UNIQUE KEY':
  393. $keyFieldsSql = "`" . implode("`,`", $fld['key_fields']) . "`";
  394. return "UNIQUE KEY `{$fldName}` ({$keyFieldsSql})";
  395. break;
  396. case 'KEY':
  397. $keyFieldsSql = "`" . implode("`,`", $fld['key_fields']) . "`";
  398. return "KEY `{$fldName}` ({$keyFieldsSql})";
  399. break;
  400. case 'PRIMARY KEY':
  401. $keyFieldsSql = "`" . implode("`,`", $fld['key_fields']) . "`";
  402. return "PRIMARY KEY ({$keyFieldsSql})";
  403. break;
  404. }
  405. return null;
  406. }
  407. public function fetchValue($sql, $values = []) { // for sql like `select count() from ...`
  408. $sth = $this->prepare($sql);
  409. if (!empty($values)) {
  410. $this->bindValues($sth, $values);
  411. DBG::log($this->getRawSql($sth), 'sql');
  412. } else {
  413. DBG::log($sql, 'sql');
  414. }
  415. $sth->execute();
  416. return $sth->fetchColumn();
  417. }
  418. public function fetchValuesList($sql, $values = []) { // for sql like `select ID from ...` @returns array of ID
  419. return array_map(function ($row) {
  420. return reset($row);
  421. }, $this->fetchAll($sql, $values));
  422. }
  423. public function fetchValuesListByKey($sql, $key, $values = []) { // for sql like `select ID from ...` @returns array of ID
  424. return array_map(function ($row) {
  425. return reset($row);
  426. }, $this->fetchAllByKey($sql, $key, $values));
  427. }
  428. public function fetchFirst($sql, $values = []) { // fetch only first row
  429. $sth = $this->prepare($sql);
  430. if (!empty($values)) {
  431. $this->bindValues($sth, $values);
  432. DBG::log($this->getRawSql($sth), 'sql');
  433. } else {
  434. DBG::log($sql, 'sql');
  435. }
  436. $sth->execute();
  437. return $sth->fetch();
  438. }
  439. public function fetchFirstNoLog($sql, $values = []) { // fetch only first row - used in User::getID() required in DBG
  440. $sth = $this->prepare($sql);
  441. if (!empty($values)) {
  442. $this->bindValues($sth, $values);
  443. }
  444. $sth->execute();
  445. return $sth->fetch();
  446. }
  447. public function fetchAll($sql, $values = []) {
  448. $sth = $this->prepare($sql);
  449. if (!empty($values)) {
  450. $this->bindValues($sth, $values);
  451. DBG::log($this->getRawSql($sth), 'sql');
  452. } else {
  453. DBG::log($sql, 'sql');
  454. }
  455. $sth->execute();
  456. return $sth->fetchAll();
  457. }
  458. public function fetchAllByKey($sql, $key = 'ID', $values = []) {
  459. $rowsByKey = array();
  460. $sth = $this->prepare($sql);
  461. if (!empty($values)) {
  462. $this->bindValues($sth, $values);
  463. DBG::log($this->getRawSql($sth), 'sql');
  464. } else {
  465. DBG::log($sql, 'sql');
  466. }
  467. $sth->execute();
  468. $rows = $sth->fetchAll();
  469. foreach ($rows as $row) {
  470. $keyRow = V::get($key, null, $row);
  471. $rowsByKey[$keyRow] = $row;
  472. }
  473. return $rowsByKey;
  474. }
  475. public function bindValues($sth, $values) {
  476. foreach ($values as $name => $value) {
  477. $val = $value;
  478. $type = PDO::PARAM_STR;
  479. if (is_array($value)) {
  480. $val = $value[0];
  481. if (count($value) > 1) {
  482. $type = $value[1];
  483. }
  484. }
  485. $sth->bindValue($name, $val, $type);
  486. if (!isset($sth->bindedValues)) $sth->bindedValues = array();
  487. $sth->bindedValues[$name] = array($val, $type);
  488. }
  489. }
  490. public function getRawSql($sth, $values = array()) {
  491. $sql = $sth->queryString;
  492. $params = array();
  493. if (!empty($sth->bindedValues)) {
  494. foreach ($sth->bindedValues as $name => $value) {
  495. $params[$name] = array($value[0], $value[1]);
  496. }
  497. }
  498. foreach ($values as $name => $value) {
  499. $val = $value;
  500. $type = PDO::PARAM_STR;
  501. if (is_array($value)) {
  502. $val = $value[0];
  503. if (count($value) > 1) {
  504. $type = $value[1];
  505. }
  506. }
  507. $params[$name] = array($val, $type);
  508. }
  509. if (!empty($params)) {
  510. foreach ($params as $name => $val) {
  511. $outValue = $val[0];
  512. if (PDO::PARAM_STR == $val[1]) $outValue = "'{$outValue}'";
  513. $sql = str_replace((':' === $name[0] ? $name : ":{$name}"), $outValue, $sql);
  514. }
  515. }
  516. return $sql;
  517. }
  518. public function insert($tableName, $item, $sqlSchema = []) {// @returns int last inserted id
  519. if (empty($tableName)) throw new Exception("Missing table name");
  520. if (!is_array($item)) throw new Exception("Missing item");
  521. $sqlFields = [];
  522. $sqlValues = [];
  523. foreach ($item as $field => $val) {
  524. $sqlFields[] = $this->identifierQuote($field);
  525. $sqlValues[] = $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  526. }
  527. $sqlTableName = $this->tableNameQuote($tableName);
  528. $sql = "
  529. insert into {$sqlTableName} (" . implode(", ", $sqlFields) . ")
  530. values (" . implode(", ", $sqlValues) . ")
  531. ";
  532. $this->execSql($sql);
  533. return $this->lastInsertId();
  534. }
  535. public function insertIgnore($tableName, $item, $sqlSchema = []) {// @returns int last inserted id
  536. if (empty($tableName)) throw new Exception("Missing table name");
  537. if (!is_array($item)) throw new Exception("Missing item");
  538. $sqlFields = [];
  539. $sqlValues = [];
  540. foreach ($item as $field => $val) {
  541. $sqlFields[] = $this->identifierQuote($field);
  542. $sqlValues[] = $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  543. }
  544. $sqlTableName = $this->tableNameQuote($tableName);
  545. $sql = "
  546. insert ignore into {$sqlTableName} (" . implode(", ", $sqlFields) . ")
  547. values (" . implode(", ", $sqlValues) . ")
  548. ";
  549. $this->execSql($sql);
  550. return $this->lastInsertId();
  551. }
  552. public function update($tableName, $primaryKeyName, $primaryKey, $item, $sqlSchema = []) {// @returns int affected rows
  553. if (empty($tableName)) throw new Exception("Missing table name");
  554. if (empty($primaryKeyName)) throw new Exception("Missing primaryKey name");
  555. if (empty($primaryKey)) throw new Exception("Missing primaryKey");
  556. if (empty($item) || !is_array($item)) throw new Exception("Missing item");
  557. $sqlPrimaryKey = $this->quote($primaryKey, PDO::PARAM_STR);
  558. $sqlUpdateSet = [];
  559. foreach ($item as $field => $val) {
  560. $sqlUpdateSet[] = $this->identifierQuote($field) . " = " . $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  561. }
  562. $sqlTableName = $this->identifierQuote($tableName);
  563. $sqlPkName = $this->identifierQuote($primaryKeyName);
  564. $sql = "
  565. update {$sqlTableName}
  566. set " . implode("\n , ", $sqlUpdateSet) . "
  567. where {$sqlPkName} = {$sqlPrimaryKey}
  568. ";
  569. return $this->execSql($sql);
  570. }
  571. // '@insert' => [
  572. // 'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
  573. // 'A_RECORD_CREATE_DATE' => 'NOW()',
  574. // ],
  575. // '@update' => [
  576. // 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  577. // 'A_RECORD_UPDATE_DATE' => 'NOW()',
  578. // ]
  579. public function insertOrUpdate($tableName, $item, $sqlSchema = []) {
  580. if (empty($tableName)) throw new Exception("Missing table name");
  581. if (empty($item) || !is_array($item)) throw new Exception("Missing item");
  582. $sqlFields = [];
  583. $sqlValues = [];
  584. $sqlUpdateSet = [];
  585. foreach ($item as $field => $val) {
  586. if ('@insert' == $field) continue;
  587. if ('@update' == $field) continue;
  588. $sqlVal = $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  589. $sqlFields[] = "`{$field}`";
  590. $sqlValues[] = $sqlVal;
  591. $sqlUpdateSet[] = "`{$field}` = {$sqlVal}";
  592. }
  593. if (!empty($item['@insert'])) {
  594. foreach ($item['@insert'] as $field => $val) {
  595. $sqlFields[] = "`{$field}`";
  596. $sqlValues[] = $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  597. }
  598. }
  599. if (!empty($item['@update'])) {
  600. foreach ($item['@update'] as $field => $val) {
  601. $sqlUpdateSet[] = "`{$field}` = " . $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  602. }
  603. }
  604. $sql = "
  605. insert into `{$tableName}` (" . implode(", ", $sqlFields) . ")
  606. values (" . implode(", ", $sqlValues) . ")
  607. ";
  608. if (!empty($sqlUpdateSet)) $sql .= " on duplicate key update " . implode(", ", $sqlUpdateSet);
  609. $affected = $this->execSql($sql);
  610. return true; // return $affected; // $this->lastInsertId();
  611. }
  612. public function convertValueToSqlSafe($value, $xsdType = null) {
  613. if ('NOW()' === $value) return 'NOW()';
  614. else if (NULL === $value) return 'NULL';
  615. else if ('GeomFromText' == substr($value, 0, strlen('GeomFromText'))) return $value;
  616. else return $this->quote($value, PDO::PARAM_STR);// TODO: use $sqlSchema if set
  617. }
  618. public function execSql($sql, $values = []) {
  619. try {
  620. if (empty($values)) {
  621. DBG::log($sql, 'sql');
  622. $retAffected = $this->exec($sql);
  623. } else {
  624. $sth = $this->prepare($sql);
  625. if (!empty($values)) {
  626. $this->bindValues($sth, $values);
  627. DBG::log($this->getRawSql($sth), 'sql');
  628. } else {
  629. DBG::log($sql, 'sql');
  630. }
  631. $sth->execute();
  632. $retAffected = $sth->rowCount();
  633. }
  634. } catch (Exception $e) {
  635. DBG::log($e);
  636. $dbType = $this->getType();
  637. $duplicateRegexp = "/^SQLSTATE\[23000\]\: Integrity constraint violation: 1062 Duplicate entry '([0-9]+)' for key '(.*)'/";
  638. if ('mysql' == $dbType && preg_match_all($duplicateRegexp, $e->getMessage(), $matches) > 0) {
  639. DBG::log(['matches'=>$matches,'msg'=>$e->getMessage(),'regex'=>$duplicateRegexp], 'array', '$matches duplicate test');
  640. throw new MysqlDuplicateEntryException("Duplicate entry '{$matches[1][0]}'", 1062, null, $matches[1][0], $matches[2][0]);
  641. } else {
  642. throw $e;
  643. }
  644. }
  645. return $retAffected;
  646. }
  647. public function getBlob($tableName, $fieldName, $pkField, $primaryKey) {
  648. if (empty($tableName)) throw new Exception("Missing tableName in PDO::getBlob");
  649. if (empty($fieldName)) throw new Exception("Missing fieldName in PDO::getBlob");
  650. if (empty($pkField)) throw new Exception("Missing pkField in PDO::getBlob");
  651. if (empty($primaryKey)) throw new Exception("Missing primaryKey in PDO::getBlob");
  652. $dbType = $this->getType();
  653. switch ($dbType) {
  654. case 'mysql': {
  655. $sql = "
  656. select `{$fieldName}`
  657. from `{$tableName}`
  658. where `{$pkField}` = :pk
  659. limit 1
  660. ";
  661. $sth = $this->prepare($sql);
  662. $sth->bindValue(':pk', $primaryKey, PDO::PARAM_STR);
  663. $sth->execute();
  664. $sth->bindColumn(1, $content, PDO::PARAM_LOB);
  665. $sth->fetch();
  666. return $content;
  667. } break;
  668. default: throw new Exception("Not implemented getBlob for database type '{$dbType}'");
  669. }
  670. }
  671. public function queryNotBuffered($query) {
  672. if ($bufferedQuery = $this->getAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY)) DB::getPDO()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
  673. $return = parent::query($query);
  674. if ($bufferedQuery) DB::getPDO()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
  675. return $return;
  676. }
  677. }
  678. class MysqlDuplicateEntryException extends DatabaseDuplicateEntryException {}
  679. class DatabaseDuplicateEntryException extends Exception {
  680. public function __construct($message, $code = 0, Exception $previous = null, $sqlPrimaryKey = '', $sqlKeyName = '') {
  681. $this->keyName = $sqlKeyName;
  682. $this->primaryKey = $sqlPrimaryKey;
  683. parent::__construct($message, $code, $previous);
  684. }
  685. }