Pdo.php 21 KB

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