Pdo.php 18 KB

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