Pdo.php 18 KB

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