Pdo.php 28 KB

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