table.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. <?php
  2. namespace Juju\PDO;
  3. require_once(realpath(dirname(__DIR__).'/pdo.class.php'));
  4. use Juju\{PDO, PDO\Transaction};
  5. class Table {
  6. const COLUMN = 'column';
  7. const INDEX = 'index';
  8. const FOREIGN_KEY = 'foreignkey';
  9. private $pdo;
  10. private $name;
  11. private $exists;
  12. private $primaryKey;
  13. private $columns;
  14. private $index;
  15. private $foreignKey;
  16. private $columns_removed;
  17. private $index_removed;
  18. private $foreignKey_removed;
  19. public function __construct($pdo, string $name){
  20. if($pdo instanceof PDO || $pdo instanceof Transaction){
  21. $this->pdo = $pdo;
  22. $this->name = $name;
  23. $this->rollback();
  24. }else{
  25. throw new \Exception("Invalid pdo argument");
  26. }
  27. }
  28. public function __get($name){
  29. switch($name){
  30. case 'exists':case 'name':case 'columns':
  31. return $this->$name;
  32. break;
  33. default:
  34. throw new \Exception("Invalid property {$name}");
  35. }
  36. }
  37. public function exists(){
  38. $pdo = $this->pdo;
  39. try{
  40. $count = $pdo->exec("select count(1) from `{$this->name}` limit 1");
  41. $this->exists = $count > 0;
  42. }catch(\Exception $e){
  43. $this->exists = false;
  44. }
  45. return $this->exists;
  46. }
  47. public function describe(){
  48. $this->columns = [];
  49. $this->primaryKey = [];
  50. $this->index = [];
  51. $this->foreignKeys = [];
  52. $this->columns_removed = [];
  53. $this->index_removed = [];
  54. $this->foreignKey_removed = [];
  55. if($this->exists){
  56. $pdo = $this->pdo;
  57. $query = $pdo->query("show create table `{$this->name}`");
  58. $sql = $query->fetch()['create table'];
  59. $query->closeCursor();
  60. if(preg_match_all('/ PRIMARY KEY \(((?:`[^`]+`,?)+)\)/s', $sql, $primaryKey, PREG_SET_ORDER) > 0){
  61. $this->primaryKey = array_map(
  62. function($item){
  63. return preg_replace('/`([^`]+)`/', '\\1', $item);
  64. },
  65. array_merge(
  66. ...array_map(
  67. function($item){
  68. return explode(',', $item[1]);
  69. }, $primaryKey
  70. )
  71. )
  72. );
  73. }
  74. unset($primaryKey);
  75. if(preg_match_all('/ ((?:UNIQUE)? ?KEY) `([^`]+)` \(((?:`[^`]+`,?)+)\)/s', $sql, $indexes, PREG_SET_ORDER) > 0){
  76. $this->indexes = array_reduce($indexes, function($indexes, $item){
  77. $indexes[$item[2]] = [
  78. 'unique'=> $item[1] == 'UNIQUE KEY',
  79. 'columns'=> array_map(function($item){
  80. return preg_replace('/`([^`]+)`/', '\\1', $item);
  81. }, explode(',', $item[3])),
  82. 'dirty'=> false
  83. ];
  84. return $indexes;
  85. });
  86. }
  87. unset($indexes);
  88. if(preg_match_all('/ CONSTRAINT `([^`]+)` FOREIGN KEY \(((?:`[^`]+`(?:, )?)+)\) REFERENCES `([^`]+)` \(((?:`[^`]+`(?:, )?)+)\)/s', $sql, $foreignKeys, PREG_SET_ORDER, 0) > 0){
  89. $this->foreignKeys = array_reduce($foreignKeys, function($foreignKeys, $item) use($sql){
  90. $columns = explode(',', $item[2]);
  91. $matches = explode(',', $item[4]);
  92. foreach($columns as $key => &$column){
  93. $column = [
  94. preg_replace('/`([^`]+)`/', '\\1', $column),
  95. preg_replace('/`([^`]+)`/', '\\1', $matches[$key])
  96. ];
  97. }
  98. $foreignKeys[$item[1]] = [
  99. 'references'=> $item[3],
  100. 'columns'=> $columns,
  101. 'dirty'=> false
  102. ];
  103. return $foreignKeys;
  104. });
  105. }
  106. unset($foreignKeys);
  107. if(preg_match_all('/ `([^`]+)` ([^\(]+\([^\)]+\))[^,\n]*,?/s', $sql, $columns, PREG_SET_ORDER) > 0){
  108. foreach($columns as $column){
  109. $default = null;
  110. $line = $column[0];
  111. $line .= substr($line, -1, 1) === ',' ? '' : ',';
  112. if(preg_match('/ `[^`]+` [^\(]+\([^\)]+\)[^D$]+DEFAULT (?!NULL)(.+)(?: AUTO_INCREMENT|UNIQUE|KEY|PRIMARY|COMMENT|COLUMN_FORMAT|STORAGE|REFERENCES|,)/u', $line, $match) == 1){
  113. $default = preg_replace("/'(.+)'/", "\\1", $match[1]);
  114. }
  115. $this->column(
  116. $column[1], // name
  117. $column[2], // type
  118. $default, // default
  119. preg_match('/`[^`]+` [^\(]+\([^\)]+\) NOT NULL/', $column[0]) === 1, // null
  120. preg_match('/ `[^`]+` [^\(]+\([^\)]+\)[^A$]+AUTO_INCREMENT,?/u', $line) == 1 // increment
  121. );
  122. $this->columns[$column[1]]['dirty'] = false;
  123. }
  124. }
  125. unset($columns);
  126. }
  127. }
  128. public function commit(){
  129. $pdo = $this->pdo;
  130. if(!$this->exists){
  131. $columns = '';
  132. foreach($this->columns as $name => $column){
  133. $columns .= "{$pdo->stringColumn($name, $column)},";
  134. }
  135. if(count($columns) > 0){
  136. $columns = rtrim($columns, ',');
  137. }
  138. $pk = $this->primaryKey();
  139. if(count($pk)){
  140. $pk = ", primary key (".implode(',', $pk).")";
  141. }
  142. $index = '';
  143. foreach($this->index as $name => $idx){
  144. $index .=", {$pdo->stringIndex($name, $idx)}";
  145. }
  146. $fk = '';
  147. foreach($this->foreignKeys as $name => $k){
  148. $fk .= ", {$pdo->stringForeignKey($name, $k)}";
  149. }
  150. $count = $pdo->exec("create table `{$this->name}` ({$columns}{$pk}{$index}{$fk})");
  151. if($count === false){
  152. throw $pdo->getError();
  153. }
  154. if(!$this->exists()){
  155. throw new \Exception("Unable to create table {$this->name}");
  156. }
  157. $this->exists();
  158. }else{
  159. $columns = array_filter($this->columns, function($item){
  160. return (bool)$item['dirty'];
  161. });
  162. if(count($columns) + count($this->columns_removed) > 0){
  163. $sql = "alter table `{$this->name}`";
  164. foreach($this->index_removed as $name){
  165. if($pdo->exec("show index from `{$this->name}` where KEY_name = ".$pdo->quote($name)) > 0){
  166. $sql .= " drop index {$name},";
  167. }
  168. }
  169. foreach($this->foreignKey_removed as $name){
  170. $sql .= " drop foreign key {$name},";
  171. }
  172. foreach($this->columns_removed as $name){
  173. $sql .= " drop column {$name},";
  174. }
  175. if(count($columns) > 0){
  176. $sql .= " add (";
  177. foreach($columns as $name => $column){
  178. $sql .= "{$pdo->stringColumn($name, $column)},";
  179. }
  180. $sql = rtrim($sql , ',') . "),";
  181. }
  182. unset($columns);
  183. $sql = rtrim($sql, ',');
  184. if($pdo->exec($sql) === false){
  185. throw new \Exception("Unable to update table {$this->name}\n{$this->pdo->getError()}");
  186. }
  187. }
  188. $sql = '';
  189. if($pdo->exec("show index from `{$this->name}` where KEY_name = 'PRIMARY'") > 0){
  190. $sql .= " drop primary key,";
  191. }
  192. if(count($this->primaryKey) > 0){
  193. $sql .= " add primary key (".implode(',', $this->primaryKey)."),";
  194. }
  195. foreach(array_filter($this->index, function($item){
  196. return (bool)$item['dirty'];
  197. }) as $name => $idx){
  198. $sql .= " add {$pdo->stringIndex($name, $idx)},";
  199. }
  200. if(count($sql) > 0){
  201. $sql = "alter table `{$this->name}`".rtrim($sql, ',');
  202. if($pdo->exec($sql) === false){
  203. throw new \Exception("Unable to update table {$this->name}\n{$this->pdo->getError()}");
  204. }
  205. }
  206. $foreignKeys =array_filter($this->foreignKeys, function($item){
  207. return (bool)$item['dirty'];
  208. });
  209. if(count($foreignKeys) > 0){
  210. $sql = "alter table `{$this->name}`";
  211. foreach($foreignKeys as $name => $fk){
  212. $sql .= " add {$pdo->stringForeignKey($name, $fk)},";
  213. }
  214. $sql = rtrim($sql, ',');
  215. if($pdo->exec($sql) === false){
  216. throw new \Exception("Unable to update table {$this->name}\n{$this->pdo->getError()}");
  217. }
  218. }
  219. unset($foreignKeys);
  220. }
  221. $this->describe();
  222. }
  223. public function rollback(){
  224. $this->exists();
  225. $this->describe();
  226. }
  227. public function drop(string $type = null, string $name = null){
  228. if(!is_null($type)){
  229. switch($type){
  230. case self::COLUMN:
  231. if(isset($this->columns[$name])){
  232. if($this->exists){
  233. $this->columns_removed = array_merge($this->columns_removed, [$name]);
  234. }
  235. unset($this->columns[$name]);
  236. }
  237. break;
  238. case self::INDEX:
  239. if(isset($this->index[$name])){
  240. if($this->exists){
  241. $this->index_removed = array_merge($this->index_removed, [$name]);
  242. }
  243. unset($this->index[$name]);
  244. }
  245. break;
  246. case self::FOREIGN_KEY:
  247. if(isset($this->foreignKey[$name])){
  248. if($this->exists){
  249. $this->foreignKey_removed = array_merge($this->foreignKey_removed, [$name]);
  250. }
  251. unset($this->foreignKey[$name]);
  252. }
  253. break;
  254. default:
  255. throw new \Exception("Cannot drop {$name}. Unknown type {$type}");
  256. }
  257. }else{
  258. if($this->exists){
  259. $this->pdo->exec("drop table `{$this->name}`");
  260. }
  261. $this->rollback();
  262. }
  263. return $this;
  264. }
  265. public function column(string $name, string $type = null, string $default = null, bool $null = false, bool $increment = false){
  266. if(!is_null($type)){
  267. $new = [
  268. 'type'=> $type,
  269. 'default'=> $default,
  270. 'null'=> $null,
  271. 'increment'=> $increment,
  272. 'dirty'=> false
  273. ];
  274. if(isset($this->columns[$name])){
  275. $old = $this->columns[$name];
  276. foreach($new as $key => $val){
  277. if($key != 'dirty' && $old[$key] !== $val){
  278. $new['dirty'] = true;
  279. break;
  280. }
  281. }
  282. }else{
  283. $new['dirty'] = true;
  284. }
  285. $this->columns[$name] = $new;
  286. return $this;
  287. }else{
  288. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  289. }
  290. }
  291. public function index(string $name, array $columns = null, bool $unique = false){
  292. if(!is_null($columns)){
  293. foreach($columns as $column){
  294. if(!isset($this->columns[$column])){
  295. throw new \Exception("Can't add index. Column {$this->name}.{$column} doesn't exist");
  296. }
  297. }
  298. $this->index[$name] = [
  299. 'columns'=> $columns,
  300. 'unique'=> $unique,
  301. 'dirty'=>true
  302. ];
  303. return $this;
  304. }else{
  305. return isset($this->index[$name]) ? $this->index[$name] : null;
  306. }
  307. }
  308. public function addToIndex(string $name, string $column){
  309. if(!isset($this->index[$name])){
  310. throw new \Exception("Can't add column to index. Index {$this->name}.{$name} doesn't exist");
  311. }
  312. if(!isset($this->columns[$column])){
  313. throw new \Exception("Can't add column to index. Column {$this->name}.{$column} doesn't exist");
  314. }
  315. $this->index[$name]['columns'] = array_merge($this->index[$name]['columns'], [$column]);
  316. }
  317. public function foreignKey(string $name, string $references = null, array $columns = []){
  318. if(!is_null($references)){
  319. $table = $this->pdo->table($references);
  320. if(!$table->exists){
  321. throw new \Exception("Can't create foreign key {$name}. Table {$references} does not exist.");
  322. }
  323. foreach($columns as $column){
  324. if(is_null($this->column($column[0]))){
  325. throw new \Exception("Can't create foreign key {$name}. Column {$this->name}.{$column[0]} does not exist");
  326. }
  327. if(is_null($table->column($column[1]))){
  328. throw new \Exception("Can't create foreign key {$name}. Column {$references}.{$column[1]} does not exist");
  329. }
  330. }
  331. $this->foreignKeys[$name] = [
  332. 'references'=> $references,
  333. 'columns'=> $columns,
  334. 'dirty'=> true
  335. ];
  336. return $this;
  337. }else{
  338. return isset($this->foreignKeys[$name]) ? $this->foreignKeys[$name] : null;
  339. }
  340. }
  341. public function primaryKey(...$columns){
  342. if(count($columns) > 0){
  343. foreach($columns as $column){
  344. if(!isset($this->columns[$column])){
  345. throw new \Exception("Can't add Primary key. Column {$this->name}.{$column} doesn't exist");
  346. }
  347. }
  348. $this->primaryKey = $columns;
  349. return $this;
  350. }else{
  351. return $this->primaryKey;
  352. }
  353. }
  354. public function insert(array $data){
  355. return $this->exists ? $this->pdo->exec("insert into `{$this->name}` {$this->pdo->stringSet($data)}") : 0;
  356. }
  357. public function update(array $data, array $filter = null){
  358. return $this->exists ? $this->pdo->exec("update `{$this->name}` {$this->pdo->stringSet($data)} {$this->pdo->stringFilter($filter)}") : 0;
  359. }
  360. public function delete(array $filter = null){
  361. return $this->exists ? $this->pdo->exec("delete from `{$this->name}` {$this->pdo->stringFilter($filter)}") : 0;
  362. }
  363. public function fetch(array $columns = null, array $filter = null, int $start = null, int $amount = null){
  364. $results = [];
  365. $this->each(function($row) use($results){
  366. $results[] = $row;
  367. }, $columns, $filter, $start, $amount);
  368. return $results;
  369. }
  370. public function each(callable $fn, array $columns = null, array $filter = null, int $start = null, int $amount = null){
  371. if($this->exists){
  372. $limit = '';
  373. if(!is_null($start) && !is_null($amount)){
  374. $limit .= " limit {$start}, {$amount}";
  375. }
  376. $columns = $columns ?? ['*'];
  377. $cols = '';
  378. foreach($columns as $column){
  379. $cols .= "{$column},";
  380. }
  381. $cols = rtrim($cols, ',');
  382. $query = $this->pdo->query("select {$cols} from `{$this->name}` {$this->pdo->stringFilter($filter)} {$limit}");
  383. while($row = $query->fetch()){
  384. $fn($row);
  385. }
  386. $query->closeCursor();
  387. }
  388. return $this;
  389. }
  390. public function count(array $filter = null){
  391. return $this->exists ? $this->pdo->exec("select 1 from `{$this->name}` {$this->pdo->stringFilter($filter)}") : 0;
  392. }
  393. }
  394. ?>