Pdo.php 25 KB

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