Pdo.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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 fetchValuesListByKey($sql, $key, $values = []) { // for sql like `select ID from ...` @returns array of ID
  423. return array_map(function ($row) {
  424. return reset($row);
  425. }, $this->fetchAllByKey($sql, $key, $values));
  426. }
  427. public function fetchFirst($sql, $values = []) { // fetch only first row
  428. $sth = $this->prepare($sql);
  429. if (!empty($values)) {
  430. $this->bindValues($sth, $values);
  431. DBG::log($this->getRawSql($sth), 'sql');
  432. } else {
  433. DBG::log($sql, 'sql');
  434. }
  435. $sth->execute();
  436. return $sth->fetch();
  437. }
  438. public function fetchFirstNoLog($sql, $values = []) { // fetch only first row - used in User::getID() required in DBG
  439. $sth = $this->prepare($sql);
  440. if (!empty($values)) {
  441. $this->bindValues($sth, $values);
  442. }
  443. $sth->execute();
  444. return $sth->fetch();
  445. }
  446. public function fetchAll($sql, $values = []) {
  447. $sth = $this->prepare($sql);
  448. if (!empty($values)) {
  449. $this->bindValues($sth, $values);
  450. DBG::log($this->getRawSql($sth), 'sql');
  451. } else {
  452. DBG::log($sql, 'sql');
  453. }
  454. $sth->execute();
  455. return $sth->fetchAll();
  456. }
  457. public function fetchAllByKey($sql, $key = 'ID', $values = []) {
  458. $rowsByKey = array();
  459. $sth = $this->prepare($sql);
  460. if (!empty($values)) {
  461. $this->bindValues($sth, $values);
  462. DBG::log($this->getRawSql($sth), 'sql');
  463. } else {
  464. DBG::log($sql, 'sql');
  465. }
  466. $sth->execute();
  467. $rows = $sth->fetchAll();
  468. foreach ($rows as $row) {
  469. $keyRow = V::get($key, null, $row);
  470. $rowsByKey[$keyRow] = $row;
  471. }
  472. return $rowsByKey;
  473. }
  474. public function bindValues($sth, $values) {
  475. foreach ($values as $name => $value) {
  476. $val = $value;
  477. $type = PDO::PARAM_STR;
  478. if (is_array($value)) {
  479. $val = $value[0];
  480. if (count($value) > 1) {
  481. $type = $value[1];
  482. }
  483. }
  484. $sth->bindValue($name, $val, $type);
  485. if (!isset($sth->bindedValues)) $sth->bindedValues = array();
  486. $sth->bindedValues[$name] = array($val, $type);
  487. }
  488. }
  489. public function getRawSql($sth, $values = array()) {
  490. $sql = $sth->queryString;
  491. $params = array();
  492. if (!empty($sth->bindedValues)) {
  493. foreach ($sth->bindedValues as $name => $value) {
  494. $params[$name] = array($value[0], $value[1]);
  495. }
  496. }
  497. foreach ($values as $name => $value) {
  498. $val = $value;
  499. $type = PDO::PARAM_STR;
  500. if (is_array($value)) {
  501. $val = $value[0];
  502. if (count($value) > 1) {
  503. $type = $value[1];
  504. }
  505. }
  506. $params[$name] = array($val, $type);
  507. }
  508. if (!empty($params)) {
  509. foreach ($params as $name => $val) {
  510. $outValue = $val[0];
  511. if (PDO::PARAM_STR == $val[1]) $outValue = "'{$outValue}'";
  512. $sql = str_replace((':' === $name[0] ? $name : ":{$name}"), $outValue, $sql);
  513. }
  514. }
  515. return $sql;
  516. }
  517. public function insert($tableName, $item, $sqlSchema = []) {// @returns int last inserted id
  518. if (empty($tableName)) throw new Exception("Missing table name");
  519. if (!is_array($item)) throw new Exception("Missing item");
  520. $sqlFields = [];
  521. $sqlValues = [];
  522. foreach ($item as $field => $val) {
  523. $sqlFields[] = $this->identifierQuote($field);
  524. $sqlValues[] = $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  525. }
  526. $sqlTableName = $this->tableNameQuote($tableName);
  527. $sql = "
  528. insert into {$sqlTableName} (" . implode(", ", $sqlFields) . ")
  529. values (" . implode(", ", $sqlValues) . ")
  530. ";
  531. $this->execSql($sql);
  532. return $this->lastInsertId();
  533. }
  534. public function update($tableName, $primaryKeyName, $primaryKey, $item, $sqlSchema = []) {// @returns int affected rows
  535. if (empty($tableName)) throw new Exception("Missing table name");
  536. if (empty($primaryKeyName)) throw new Exception("Missing primaryKey name");
  537. if (empty($primaryKey)) throw new Exception("Missing primaryKey");
  538. if (empty($item) || !is_array($item)) throw new Exception("Missing item");
  539. $sqlPrimaryKey = $this->quote($primaryKey, PDO::PARAM_STR);
  540. $sqlUpdateSet = [];
  541. foreach ($item as $field => $val) {
  542. $sqlUpdateSet[] = $this->identifierQuote($field) . " = " . $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  543. }
  544. $sqlTableName = $this->identifierQuote($tableName);
  545. $sqlPkName = $this->identifierQuote($primaryKeyName);
  546. $sql = "
  547. update {$sqlTableName}
  548. set " . implode("\n , ", $sqlUpdateSet) . "
  549. where {$sqlPkName} = {$sqlPrimaryKey}
  550. ";
  551. return $this->execSql($sql);
  552. }
  553. // '@insert' => [
  554. // 'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
  555. // 'A_RECORD_CREATE_DATE' => 'NOW()',
  556. // ],
  557. // '@update' => [
  558. // 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  559. // 'A_RECORD_UPDATE_DATE' => 'NOW()',
  560. // ]
  561. public function insertOrUpdate($tableName, $item, $sqlSchema = []) {
  562. if (empty($tableName)) throw new Exception("Missing table name");
  563. if (empty($item) || !is_array($item)) throw new Exception("Missing item");
  564. $sqlFields = [];
  565. $sqlValues = [];
  566. $sqlUpdateSet = [];
  567. foreach ($item as $field => $val) {
  568. if ('@insert' == $field) continue;
  569. if ('@update' == $field) continue;
  570. $sqlVal = $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  571. $sqlFields[] = "`{$field}`";
  572. $sqlValues[] = $sqlVal;
  573. $sqlUpdateSet[] = "`{$field}` = {$sqlVal}";
  574. }
  575. if (!empty($item['@insert'])) {
  576. foreach ($item['@insert'] as $field => $val) {
  577. $sqlFields[] = "`{$field}`";
  578. $sqlValues[] = $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  579. }
  580. }
  581. if (!empty($item['@update'])) {
  582. foreach ($item['@update'] as $field => $val) {
  583. $sqlUpdateSet[] = "`{$field}` = " . $this->convertValueToSqlSafe($val, V::get($field, null, $sqlSchema));
  584. }
  585. }
  586. $sql = "
  587. insert into `{$tableName}` (" . implode(", ", $sqlFields) . ")
  588. values (" . implode(", ", $sqlValues) . ")
  589. ";
  590. if (!empty($sqlUpdateSet)) $sql .= " on duplicate key update " . implode(", ", $sqlUpdateSet);
  591. $affected = $this->execSql($sql);
  592. return true; // return $affected; // $this->lastInsertId();
  593. }
  594. public function convertValueToSqlSafe($value, $xsdType = null) {
  595. if ('NOW()' === $value) return 'NOW()';
  596. else if (NULL === $value) return 'NULL';
  597. else return $this->quote($value, PDO::PARAM_STR);// TODO: use $sqlSchema if set
  598. }
  599. public function execSql($sql, $values = []) {
  600. if (empty($values)) {
  601. DBG::log($sql, 'sql');
  602. return $this->exec($sql);
  603. }
  604. $sth = $this->prepare($sql);
  605. if (!empty($values)) {
  606. $this->bindValues($sth, $values);
  607. DBG::log($this->getRawSql($sth), 'sql');
  608. } else {
  609. DBG::log($sql, 'sql');
  610. }
  611. $sth->execute();
  612. return $sth->rowCount();
  613. }
  614. public function getBlob($tableName, $fieldName, $pkField, $primaryKey) {
  615. if (empty($tableName)) throw new Exception("Missing tableName in PDO::getBlob");
  616. if (empty($fieldName)) throw new Exception("Missing fieldName in PDO::getBlob");
  617. if (empty($pkField)) throw new Exception("Missing pkField in PDO::getBlob");
  618. if (empty($primaryKey)) throw new Exception("Missing primaryKey in PDO::getBlob");
  619. $dbType = $this->getType();
  620. switch ($dbType) {
  621. case 'mysql': {
  622. $sql = "
  623. select `{$fieldName}`
  624. from `{$tableName}`
  625. where `{$pkField}` = :pk
  626. limit 1
  627. ";
  628. $sth = $this->prepare($sql);
  629. $sth->bindValue(':pk', $primaryKey, PDO::PARAM_STR);
  630. $sth->execute();
  631. $sth->bindColumn(1, $content, PDO::PARAM_LOB);
  632. $sth->fetch();
  633. return $content;
  634. } break;
  635. default: throw new Exception("Not implemented getBlob for database type '{$dbType}'");
  636. }
  637. }
  638. }