MigrationsBase.php 26 KB

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