MigrationsBase.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. <?php
  2. namespace MigrationsBundle\Migrations;
  3. use Doctrine\DBAL\Migrations\AbstractMigration;
  4. use Doctrine\DBAL\Schema\Schema;
  5. use Symfony\Component\DependencyInjection\ContainerAwareInterface;
  6. use Symfony\Component\DependencyInjection\ContainerInterface;
  7. use Symfony\Component\Yaml\Yaml;
  8. /**
  9. * Clase de migracion de base.
  10. * Orden de ejecucion de metodos.
  11. * 1- preUp
  12. * 2- up
  13. * 3- postUp
  14. * 4- preDown
  15. * 5- down
  16. * 6- postDown
  17. */
  18. class MigrationsBase extends AbstractMigration implements ContainerAwareInterface
  19. {
  20. /**
  21. * Tipo de senetencia sql insert.
  22. */
  23. const INSERT = "INSERT";
  24. /**
  25. * Tipo de sentencia sql update.
  26. */
  27. const UPDATE = "UPDATE";
  28. /**
  29. * Tipo de sentenca sql delete.
  30. */
  31. const DELETE = "DELETE";
  32. /**
  33. * @var int $line Contiene el numero de linea que estoy ejecutando.
  34. */
  35. private $line = 0;
  36. /**
  37. * @var bool Me dice si tengo que mostrar los parametros en las consultas.
  38. */
  39. private $showParameters = false;
  40. /**
  41. * @var bool Me dice si tengo que mostrar las queryies.
  42. */
  43. private $showQuery = true;
  44. /**
  45. * @var array $errorLineExecution Contiene una descripcion del error que ocaciono una linea del script YAML.
  46. */
  47. private $errorLineExecution = array();
  48. /**
  49. * @var array $lineExecution Contiene una descripcion de como se ejecuto cada linea del script YAML.
  50. */
  51. private $lineExecution = array();
  52. /**
  53. * @var ContainerInterface $container Contiene el contenedor.
  54. */
  55. private $container;
  56. /**
  57. * @param ContainerInterface|null $container Contiene un objeto que implementa "ContainerInterface".
  58. * @return ContainerInterface Retorna un objeto que implementa la interfaz "ContainerInterface".
  59. */
  60. public function setContainer(ContainerInterface $container = null)
  61. {
  62. $this->container = $container;
  63. return $this->container;
  64. }
  65. /**
  66. * @return ContainerInterface Retorna un objeto que implementa la interfaz "ContainerInterface".
  67. */
  68. public function getContainer()
  69. {
  70. return $this->container;
  71. }
  72. /**
  73. * @return bool Retorna el valor de la variable showParameters.
  74. */
  75. public function isShowParameters()
  76. {
  77. return $this->showParameters;
  78. }
  79. /**
  80. * @param bool $showParameters Si esta en TRUE muestra los parametros en las consultas.
  81. */
  82. public function setShowParameters($showParameters)
  83. {
  84. $this->showParameters = $showParameters;
  85. }
  86. /**
  87. * @return int Retorna el numero de linea que estoy analizando.
  88. */
  89. public function getLine()
  90. {
  91. return $this->line;
  92. }
  93. /**
  94. * @param int $line Setea el numero de linea.
  95. */
  96. private function setLine($line)
  97. {
  98. $this->line = $line;
  99. }
  100. /**
  101. * Funcion que suma 1 a la variable line.
  102. */
  103. private function sumLine()
  104. {
  105. $this->line = $this->line + 1;
  106. }
  107. /**
  108. * @return array Retorna un array con las lineas que produjeron errores.
  109. */
  110. public function getErrorLineExecution()
  111. {
  112. return $this->errorLineExecution;
  113. }
  114. /**
  115. * @param array $errorLineExecution Setea un array con las lineas que produjeron errores.
  116. */
  117. public function setErrorLineExecution($errorLineExecution)
  118. {
  119. $this->errorLineExecution = $errorLineExecution;
  120. }
  121. /**
  122. * Agrega una linea de error.
  123. * @param string $type Contiene el tipo de sentencia sql.
  124. * @param \Throwable $ex Contiene una excepcion.
  125. */
  126. private function addErrorLineExecution($type, \Throwable $ex)
  127. {
  128. if (!array_key_exists($type, $this->errorLineExecution)) {
  129. $this->errorLineExecution[$type] = array();
  130. }
  131. array_push($this->errorLineExecution[$type], "Line: " . $this->getLine() . " => [" . $ex->getCode() . "] = " . $ex->getMessage());
  132. }
  133. /**
  134. * @return array Retorna una array con el valor de la ejecucion de cada linea.
  135. */
  136. public function getLineExecution()
  137. {
  138. return $this->lineExecution;
  139. }
  140. /**
  141. * @param array $lineExecution Setea un array con las lineas de ejecucion.
  142. */
  143. public function setLineExecution($lineExecution)
  144. {
  145. $this->lineExecution = $lineExecution;
  146. }
  147. /**
  148. * Agrega el valor de la ejecucion.
  149. * @param string $type Contiene el tipo de sentencia sql.
  150. * @param string $value Contiene el valor de la ejecucion.
  151. */
  152. private function addLineExecution($type, $value)
  153. {
  154. if (!array_key_exists($type, $this->lineExecution)) {
  155. $this->lineExecution[$type] = array();
  156. }
  157. array_push($this->lineExecution[$type], "Line: " . $this->getLine() . " => " . $value);
  158. }
  159. /**
  160. * Realiza un up de la modificaciones DDL. Siempre son agregados.
  161. * Para realizar sentencias DML utilizarlos metodos preUp y postUp.
  162. * @param Schema $schema Contiene el objeto esquema.
  163. */
  164. public function up(Schema $schema)
  165. {
  166. }
  167. /**
  168. * Realiza un up de la modificaciones DDL. Siempre son eliminacion.
  169. * Para realizar sentencias DML utilizarlos metodos preDown y postDown.
  170. * @param Schema $schema Contiene el objeto esquema.
  171. */
  172. public function down(Schema $schema)
  173. {
  174. }
  175. /**
  176. * Procesa un yaml para generar las sentencias DML que luego seran ejecutadas en la base de datos.
  177. * El directorio origen es <code>app/DoctrineMigrations</code> en adelante.
  178. * @param string $dir Contiene el nombre del directorio a leer.
  179. * @param string $fileName Contiene el nombre del archivo a incorporar.
  180. */
  181. public function interpretYaml($dir, $fileName)
  182. {
  183. $dir = trim($dir);
  184. if (!(substr($dir, count($dir) - 2, count($dir) - 2) == "\\" ||
  185. substr($dir, count($dir) - 2, count($dir) - 2) == "/")
  186. ) {
  187. $dir = $dir . "/";
  188. }
  189. // leo el yaml
  190. $value = $this->readYaml($dir, $fileName);
  191. if ($value != null && count($value) > 0) {
  192. // paso las key a mayusculas
  193. foreach ($value as $key => $val) {
  194. unset($value[$key]);
  195. $value[strtoupper($key)] = $val;
  196. }
  197. // reemplazo las keys que poseen importkey
  198. $value = $this->replaceImportsKey($dir, $value);
  199. // reemplazo los valores que poseen import
  200. $value = $this->replaceImportsValue($dir, $value);
  201. // lo hago de esta forma para que se ejecuten de acuerdo a como se escribe el yaml.
  202. $this->setLine(0);
  203. foreach ($value as $key => $val) {
  204. if (strtoupper($key) === MigrationsBase::INSERT) {
  205. $this->createInserts($value[MigrationsBase::INSERT]);
  206. } else if (strtoupper($key) === MigrationsBase::UPDATE) {
  207. $this->createUpdates($value[MigrationsBase::UPDATE]);
  208. } else if (strtoupper($key) === MigrationsBase::DELETE) {
  209. $this->createDeletes($value[MigrationsBase::DELETE]);
  210. } else {
  211. die("Valor no esperado");
  212. }
  213. }
  214. }
  215. }
  216. /**
  217. * Crea los insert a partir de una estructura yaml. Se puede utilizar la palabra clave "ignore", "replace" o "orupdate".
  218. * El "replace" sobreescribe al "ignore" y el "orupdate" sobreescribe al "replace".
  219. * @param array $arrayInsert Contiene la estructura yaml para los insert.
  220. */
  221. private function createInserts($arrayInsert)
  222. {
  223. foreach ($arrayInsert as $table => $inserts) {
  224. // recorro las tablas
  225. foreach ($inserts as $key => $valueKey) {
  226. // recorro cada uno de los insert que quiero hacer
  227. // almacena los campos
  228. $fields = "";
  229. // almacena el valor de los campos
  230. $valuesFields = "";
  231. // me dice si tengo que utilizar la palabra ignore
  232. $ignore = " ";
  233. // contiene la primer palabra de la sentencia (INSERT/REPLACE)
  234. $insert = "INSERT";
  235. // me dice si es un insert or update
  236. $orUpdate = false;
  237. // contiene los valores del insert or update
  238. $orUpdateValues = "";
  239. // contiene los valores para el bind del stament
  240. $arrayPrepare = array();
  241. foreach ($valueKey as $field => $value) {
  242. // recorro los datos a insertar
  243. $field = strtolower(trim($field));
  244. $value = trim($value);
  245. if (strlen($field) > 0 && strlen($value) > 0) {
  246. if ($field === 'ignore') {
  247. $value = strtolower($value);
  248. if ($value === '1' || $value === 'true') {
  249. if ($insert === 'INSERT') {
  250. $ignore = " IGNORE ";
  251. }
  252. }
  253. } else if ($field === 'replace') {
  254. $value = strtolower($value);
  255. if ($value === '1' || $value === 'true') {
  256. $insert = "REPLACE";
  257. $ignore = " ";
  258. }
  259. } else if ($field === 'orupdate') {
  260. $value = strtolower($value);
  261. if ($value === '1' || $value === 'true') {
  262. $orUpdate = true;
  263. $ignore = " ";
  264. $insert = "INSERT";
  265. }
  266. } else {
  267. $arrayPrepare[':' . $field] = $value;
  268. $fields = $fields . $field . ", ";
  269. $valuesFields = $valuesFields . ":" . $field . ", ";
  270. $orUpdateValues = $orUpdateValues . $field . " = " . ":" . $field . ", ";
  271. }
  272. }
  273. }
  274. if (strlen($fields) > 1) {
  275. $fields = substr($fields, 0, strlen($fields) - 2);
  276. }
  277. if (strlen($valuesFields) > 1) {
  278. $valuesFields = substr($valuesFields, 0, strlen($valuesFields) - 2);
  279. }
  280. if (strlen($orUpdateValues) > 1) {
  281. $orUpdateValues = substr($orUpdateValues, 0, strlen($orUpdateValues) - 2);
  282. }
  283. if (strlen($fields) > 1 && strlen($valuesFields) > 1) {
  284. $sql = $insert . $ignore . "INTO " . $table . " (" . $fields . ") VALUES (" . $valuesFields . ")";
  285. if ($orUpdate) {
  286. $sql .= " ON DUPLICATE KEY UPDATE " . $orUpdateValues . ";";
  287. } else {
  288. $sql .= ";";
  289. }
  290. $this->executeSQL($sql, MigrationsBase::INSERT, $arrayPrepare);
  291. }
  292. }
  293. }
  294. }
  295. /**
  296. * Crea los update a partir de una estructura yaml.
  297. * @param array $arrayInsert Contiene la estructura yaml para los insert.
  298. */
  299. private function createUpdates($arrayInsert)
  300. {
  301. foreach ($arrayInsert as $table => $inserts) {
  302. // recorro las tablas
  303. foreach ($inserts as $key => $valueKey) {
  304. // recorro cada uno de los insert que quiero hacer
  305. $set = "";
  306. $where = "";
  307. // contiene los valores para el bind del stament
  308. $arrayPrepare = array();
  309. foreach ($valueKey as $field => $value) {
  310. // recorro los datos a realizar un update
  311. if (strlen(trim($field)) > 0 && strlen(trim($value)) > 0) {
  312. if ($field === "where") {
  313. $where = $value;
  314. } else {
  315. $arrayPrepare[':' . $field] = $value;
  316. $set = $set . $field . " = :" . $field . ", ";
  317. }
  318. }
  319. }
  320. if (strlen($set) > 1) {
  321. $set = substr($set, 0, strlen($set) - 2);
  322. }
  323. if (strlen($set) > 1) {
  324. $sql = "UPDATE " . $table . " SET " . $set . " WHERE " . $where . ";";
  325. $this->executeSQL($sql, MigrationsBase::UPDATE, $arrayPrepare);
  326. }
  327. }
  328. }
  329. }
  330. /**
  331. * Crea los delete a partir de una estructura yaml.
  332. * @param array $arrayInsert Contiene la estructura yaml para los insert.
  333. */
  334. private function createDeletes($arrayInsert)
  335. {
  336. foreach ($arrayInsert as $table => $inserts) {
  337. // recorro las tablas
  338. foreach ($inserts as $key => $valueKey) {
  339. // recorro cada uno de los insert que quiero hacer
  340. $where = "";
  341. foreach ($valueKey as $field => $value) {
  342. // recorro los datos a realizar un update
  343. if (strlen(trim($field)) > 0 && strlen(trim($value)) > 0) {
  344. if ($field === "where") {
  345. $where = $value;
  346. }
  347. }
  348. }
  349. $sql = "DELETE FROM " . $table . " WHERE " . $where . ";";
  350. $this->executeSQL($sql, MigrationsBase::DELETE);
  351. }
  352. }
  353. }
  354. /**
  355. * Obtiene el contenido de un archivo yaml.
  356. * @param string $dir Contiene el directorio de trabajo. Por defecto "DoctrineMigrations".
  357. * @param string $archivo Contiene el nombre del archivo a incorporar.
  358. * @return bool|string Retorna el contenido del archivo.
  359. */
  360. private function readYaml($dir, $archivo)
  361. {
  362. return Yaml::parse(file_get_contents($dir . $archivo));
  363. }
  364. /**
  365. * Obtiene el contenido de un archivo.
  366. * @param string $dir Contiene el directorio de trabajo. Por defecto "DoctrineMigrations".
  367. * @param string $archivo Contiene el nombre del archivo a incorporar.
  368. * @return bool|string Retorna el contenido del archivo.
  369. */
  370. private function readImportInValues($dir, $archivo)
  371. {
  372. return file_get_contents($dir . $archivo);
  373. }
  374. /**
  375. * Reemplaza el contenido de los imports dentro de los values.
  376. * @param string $dir Contiene el directorio de trabajo. Por defecto "DoctrineMigrations".
  377. * @param array $valores Contiene el array el contenido del yaml.
  378. * @return array Retorna el array con los valores cambiados.
  379. */
  380. private function replaceImportsValue($dir, $valores)
  381. {
  382. try {
  383. foreach ($valores as $key => $value) {
  384. if (is_array($value)) {
  385. if (count($value) == 1 && array_key_exists("import", $value)) {
  386. if (file_exists($dir . $value["import"])) {
  387. $valores[$key] = $this->readImportInValues($dir, $value["import"]);
  388. } else {
  389. $valores[$key] = "FILE NOT FOUND";
  390. }
  391. } else {
  392. $valores[$key] = $this->replaceImportsValue($dir, $value);
  393. }
  394. }
  395. }
  396. } catch (\Symfony\Component\Debug\Exception\ContextErrorException $e) {
  397. var_dump($e);
  398. }
  399. return $valores;
  400. }
  401. /**
  402. * Reemplaza el contenido de los imports dentro de las key.
  403. * @param string $dir Contiene el directorio de trabajo. Por defecto "DoctrineMigrations".
  404. * @param array $valores Contiene el array el contenido del yaml.
  405. * @return array Retorna el array con los valores cambiados.
  406. */
  407. private function replaceImportsKey($dir, $valores)
  408. {
  409. try {
  410. foreach ($valores as $key => $value) {
  411. if (is_array($value)) {
  412. $valores[$key] = $this->replaceImportsKey($dir, $value);
  413. } else {
  414. if (trim($key) === "importkey") {
  415. if (file_exists($dir . $value)) {
  416. $valores = $this->readYaml($dir, $value);
  417. } else {
  418. $valores[$key] = "FILE NOT FOUND";
  419. }
  420. }
  421. }
  422. }
  423. } catch (\Symfony\Component\Debug\Exception\ContextErrorException $e) {
  424. var_dump($e);
  425. }
  426. return $valores;
  427. }
  428. /**
  429. * Funcion ejecuta el YAML en la base de datos dentro de una transaccion.
  430. * @param string $dir Contiene el path del directorio donde se encuentra el archio a leer.
  431. * @param string $file Contiene el nombre de archivo a procesar.
  432. */
  433. public function executeYaml($dir, $file)
  434. {
  435. try {
  436. $tmp = explode("\\", get_class($this));
  437. if ($tmp != null && count($tmp) > 0) {
  438. $version = $tmp[count($tmp) - 1];
  439. } else {
  440. $version = "";
  441. }
  442. echo "\n\tInicio del procesamiento de la migracion: " . $version;
  443. $this->connection->beginTransaction();
  444. try {
  445. $this->interpretYaml($dir, $file);
  446. if (count($this->getErrorLineExecution()) > 0) {
  447. $this->connection->rollBack();
  448. //se produjeron errores
  449. echo "\n\t\tSe produjeron errores de sql.\n";
  450. } else {
  451. $this->connection->commit();
  452. echo "\n\t\tMigracion correcta.\n";
  453. }
  454. } catch (\Throwable $ex) {
  455. $this->connection->rollBack();
  456. echo "\n\t\tSe produjeron errores por una excepcion. " . $ex->getMessage() . "\n";
  457. }
  458. } catch (\Throwable $e) {
  459. echo "\n\t\tSe produjeron errores genericos. " . $e->getMessage() . "\n";
  460. }
  461. }
  462. /**
  463. * Funcion que ejecuta una sentencia sql.
  464. * @param string $sql Contiene el sql a ejecutar.
  465. * @param string $type Contiene el tipo de sentencia.
  466. * @param array $arrayPrepare Contiene un array con los valores. La key contiene el valor a
  467. * buscar en la sentencia sql y el value es el valor.
  468. */
  469. public function executeSQL($sql, $type, $arrayPrepare = null)
  470. {
  471. $this->connection->executeUpdate($sql, (array)$arrayPrepare);
  472. if ($this->isShowQuery() && count($arrayPrepare) > 0) {
  473. $tmp = $sql;
  474. foreach ($arrayPrepare as $key => $value) {
  475. $tmp = str_replace($key, $value, $tmp);
  476. }
  477. echo " -> $tmp\n";
  478. }
  479. $this->sumLine();
  480. }
  481. /**
  482. * Funcion que obtiene el numero de version.
  483. * @param mixed $obj Contiene el objeto de ejecucion.
  484. * @return string Retorna el numero de version que estoy ejecutando.
  485. */
  486. public function getMigrationNumber($obj)
  487. {
  488. $arr = explode("\\", get_class($obj));
  489. return str_ireplace("version", "", $arr[count($arr) - 1]);
  490. }
  491. /**
  492. * Borra la migracion de la tabla de migraciones.
  493. * @param string $obj Contiene el objeto this.
  494. */
  495. public function deleteMigrationsVersion($obj)
  496. {
  497. if ($this->existTable("migration_versions")) {
  498. $this->connection->beginTransaction();
  499. $stmt = $this->connection->prepare(
  500. "DELETE FROM migration_versions " .
  501. "WHERE migration_versions.version = '" . $this->getMigrationNumber($obj) . "'");
  502. $stmt->execute();
  503. $this->connection->commit();
  504. }
  505. }
  506. /**
  507. * Verifica si la migracion ya se incorporo.
  508. * @param string $obj Contiene el objeto this.
  509. * @return bool Retorna TRUE si ya se realizo la migracion.
  510. */
  511. public function verifyMigrationsVersion($obj)
  512. {
  513. $existe = false;
  514. try {
  515. if ($this->existTable("migration_versions")) {
  516. $nroVersion = $this->getMigrationNumber($obj);
  517. $base = $this->getDataBaseName();
  518. $sql =
  519. "SELECT ifnull(version, '') as nombre " .
  520. "FROM migration_versions " .
  521. "WHERE " .
  522. $base . ".migration_versions.version = '" . $nroVersion . "';";
  523. $stmt = $this->connection->prepare($sql);
  524. $stmt->execute();
  525. $resp = $stmt->fetchAll();
  526. foreach ($resp as $key => $value) {
  527. if (strtolower($value["nombre"]) === strtolower($nroVersion)) {
  528. $existe = true;
  529. break;
  530. }
  531. }
  532. }
  533. return $existe;
  534. } catch (\Throwable $e) {
  535. return $existe;
  536. }
  537. }
  538. /**
  539. * Funcion que muestra por pantalla el resultado de la ejecucion y de los errores.
  540. */
  541. public function showResult()
  542. {
  543. if (count($this->getLineExecution()) > 0) {
  544. echo "-----------------------------------------------\n";
  545. echo " EJECUCIONES\n";
  546. echo "-----------------------------------------------\n";
  547. foreach ($this->getLineExecution() as $key => $value) {
  548. echo $key . "\n";
  549. foreach ($this->getLineExecution()[$key] as $k => $v) {
  550. echo "\t" . $v . "\n";
  551. }
  552. }
  553. }
  554. if (count($this->getErrorLineExecution()) > 0) {
  555. echo "-----------------------------------------------\n";
  556. echo " ERRORES\n";
  557. echo "-----------------------------------------------\n";
  558. foreach ($this->getErrorLineExecution() as $key => $value) {
  559. echo $key . "\n";
  560. foreach ($this->getErrorLineExecution()[$key] as $k => $v) {
  561. echo "\t" . $v . "\n";
  562. }
  563. }
  564. }
  565. }
  566. /**
  567. * Funcion que verifica si existe un campo de una tabla.
  568. * @param string $table Contiene el nombre de la tabla.
  569. * @param string $field Contiene el nombre el campo.
  570. * @return bool Retorna true si el campo existe.
  571. */
  572. public function existFieldInTable($table, $field)
  573. {
  574. $existe = false;
  575. try {
  576. $base = $this->getDataBaseName();
  577. $sql = "SELECT ifnull(COLUMN_NAME, '') as nombre " .
  578. "FROM information_schema.columns " .
  579. "WHERE TABLE_SCHEMA = '" . $base . "' AND " .
  580. " TABLE_NAME = '" . $table . "' AND " .
  581. " COLUMN_NAME = '" . $field . "'; ";
  582. $stmt = $this->connection->prepare($sql);
  583. $stmt->execute();
  584. $resp = $stmt->fetchAll();
  585. foreach ($resp as $key => $value) {
  586. if (strtolower($value["nombre"]) === strtolower($field)) {
  587. $existe = true;
  588. break;
  589. }
  590. }
  591. return $existe;
  592. } catch (\Throwable $e) {
  593. return $existe;
  594. }
  595. }
  596. /**
  597. * Funcion que verifica si existe un valor dentro de una tabla.
  598. * @param string $table Contiene el nombre de la tabla.
  599. * @param string $field Contiene el/los campos a mostrar.
  600. * @param string $where Contiene el where de la consulta. Solo los campos con los valores. SIN
  601. * LA PALABRA CLAVE.
  602. * @return array Retorna el array con los datos encontrados. O NULL en caso de error.
  603. */
  604. public function existValueInTable($table, $field, $where)
  605. {
  606. try {
  607. $sql = "SELECT " . $field . " " .
  608. "FROM " . $table . " " .
  609. "WHERE " . $where . "; ";
  610. $stmt = $this->connection->prepare($sql);
  611. $stmt->execute();
  612. $resp = $stmt->fetchAll();
  613. return $resp;
  614. } catch (\Throwable $e) {
  615. return null;
  616. }
  617. }
  618. /**
  619. * Funcion que verifica si existe un campo de una tabla.
  620. * @param string $table Contiene el nombre de la tabla.
  621. * @param string $field Contiene el nombre el campo.
  622. * @param string $type Contiene el typo de dato.
  623. * @return bool Retorna true si el campo existe.
  624. */
  625. public function existFieldType($table, $field, $type)
  626. {
  627. $existe = false;
  628. try {
  629. $base = $this->getDataBaseName();
  630. $sql = "SELECT ifnull(DATA_TYPE, '') as nombre " .
  631. "FROM information_schema.columns " .
  632. "WHERE TABLE_SCHEMA = '" . $base . "' AND " .
  633. " TABLE_NAME = '" . $table . "' AND " .
  634. " COLUMN_NAME = '" . $field . "' " .
  635. "LIMIT 1;";
  636. $stmt = $this->connection->prepare($sql);
  637. $stmt->execute();
  638. $resp = $stmt->fetchAll();
  639. foreach ($resp as $key => $value) {
  640. if (strtolower($value["nombre"]) === strtolower($type)) {
  641. $existe = true;
  642. break;
  643. }
  644. }
  645. return $existe;
  646. } catch (\Throwable $e) {
  647. return $existe;
  648. }
  649. }
  650. /**
  651. * Funcion que verifica si existe una tabla.
  652. * @param string $table Contiene el nombre de la tabla.
  653. * @return bool Retorna true si la tabla existe.
  654. */
  655. public function existTable($table)
  656. {
  657. $existe = false;
  658. try {
  659. $base = $this->getDataBaseName();
  660. $sql = "SELECT ifnull(TABLE_NAME, '') as nombre " .
  661. "FROM information_schema.columns " .
  662. "WHERE TABLE_SCHEMA = '" . $base . "' AND " .
  663. " TABLE_NAME = '" . $table . "' " .
  664. "LIMIT 1;";
  665. $stmt = $this->connection->prepare($sql);
  666. $stmt->execute();
  667. $resp = $stmt->fetchAll();
  668. foreach ($resp as $key => $value) {
  669. if (strtolower($value["nombre"]) === strtolower($table)) {
  670. $existe = true;
  671. break;
  672. }
  673. }
  674. return $existe;
  675. } catch (\Throwable $e) {
  676. return $existe;
  677. }
  678. }
  679. /**
  680. * Funcion que obtiene el nombre de la base de datos a la cual estoy conectado.
  681. * @return string Retorna el nombre de la base de datos o NULL en caso de error.
  682. */
  683. public function getDataBaseName()
  684. {
  685. $resp = null;
  686. try {
  687. $stmt = $this->connection->prepare("SELECT DATABASE() as base;");
  688. $stmt->execute();
  689. $resp = $stmt->fetchAll();
  690. foreach ($resp as $key => $value) {
  691. $resp = $value["base"];
  692. break;
  693. }
  694. return $resp;
  695. } catch (\Throwable $e) {
  696. return $resp;
  697. }
  698. }
  699. /**
  700. * Funcion que obtiene el valor del auto_increment.
  701. * @param string $table Contiene el nombre de la tabla.
  702. * @return array Retorna el array con los datos encontrados. O NULL en caso de error.
  703. */
  704. public function getAutoIncrementValue($table)
  705. {
  706. $autoIncrement = 1;
  707. try {
  708. $base = $this->getDataBaseName();
  709. $sql = "SELECT `AUTO_INCREMENT` " .
  710. "FROM INFORMATION_SCHEMA.TABLES " .
  711. "WHERE TABLE_SCHEMA = '" . $base . "' AND " .
  712. " TABLE_NAME = '" . $table . "';";
  713. $stmt = $this->connection->prepare($sql);
  714. $stmt->execute();
  715. $resp = $stmt->fetchAll();
  716. foreach ($resp as $key => $value) {
  717. if (isset($value["AUTO_INCREMENT"])) {
  718. $autoIncrement = $value["AUTO_INCREMENT"];
  719. }
  720. }
  721. } catch (\Throwable $e) {
  722. }
  723. return $autoIncrement;
  724. }
  725. /**
  726. * Funcion que setea el valor del auto_increment.
  727. * @param string $table Contiene el nombre de la tabla.
  728. * @param int $value Contiene el proximo numero autilizar.
  729. */
  730. public function setAutoIncrementValue($table, $value)
  731. {
  732. try {
  733. $base = $this->getDataBaseName();
  734. $stmt = $this->connection->prepare("ALTER TABLE " . $base . "." . $table . " AUTO_INCREMENT=" . $value . ";");
  735. $stmt->execute();
  736. } catch (\Throwable $e) {
  737. }
  738. }
  739. /**
  740. * @return bool
  741. */
  742. public function isShowQuery()
  743. {
  744. return $this->showQuery;
  745. }
  746. /**
  747. * @param bool $showQuery
  748. */
  749. public function setShowQuery($showQuery)
  750. {
  751. $this->showQuery = $showQuery;
  752. }
  753. }