Pdo.php 25 KB

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