MigrationsBase.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. <?php
  2. namespace 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 DoctrineMigrations en adelante.
  174. * @param string $fileName Contiene el nombre del archivo a incorporar.
  175. */
  176. protected function interpretYaml($fileName)
  177. {
  178. // obtengo el directorio de trabajo
  179. $dir = dirname(__DIR__) . "/DoctrineMigrations/";
  180. // leo el yaml
  181. $value = $this->readYaml($dir, $fileName);
  182. if ($value != null && count($value) > 0) {
  183. // paso las key a mayusculas
  184. foreach ($value as $key => $val) {
  185. unset($value[$key]);
  186. $value[strtoupper($key)] = $val;
  187. }
  188. // reemplazo las keys que poseen importkey
  189. $value = $this->replaceImportsKey($dir, $value);
  190. // reemplazo los valores que poseen import
  191. $value = $this->replaceImportsValue($dir, $value);
  192. // creo los insert
  193. if (array_key_exists(MigrationsBase::INSERT, $value)) {
  194. $this->setLine(0);
  195. $this->createInserts($value[MigrationsBase::INSERT]);
  196. }
  197. // creo los update
  198. if (array_key_exists(MigrationsBase::UPDATE, $value)) {
  199. $this->setLine(0);
  200. $this->createUpdates($value[MigrationsBase::UPDATE]);
  201. }
  202. // creo los delete
  203. if (array_key_exists(MigrationsBase::DELETE, $value)) {
  204. $this->setLine(0);
  205. $this->createDeletes($value[MigrationsBase::DELETE]);
  206. }
  207. }
  208. }
  209. /**
  210. * Crea los insert a partir de una estructura yaml. Se puede utilizar la palabra clave "ignore", "replace" o "orupdate".
  211. * El "replace" sobreescribe al "ignore" y el "orupdate" sobreescribe al "replace".
  212. * @param array $arrayInsert Contiene la estructura yaml para los insert.
  213. */
  214. private function createInserts($arrayInsert)
  215. {
  216. foreach ($arrayInsert as $table => $inserts) {
  217. // recorro las tablas
  218. foreach ($inserts as $key => $valueKey) {
  219. // recorro cada uno de los insert que quiero hacer
  220. // almacena los campos
  221. $fields = "";
  222. // almacena el valor de los campos
  223. $valuesFields = "";
  224. // me dice si tengo que utilizar la palabra ignore
  225. $ignore = " ";
  226. // contiene la primer palabra de la sentencia (INSERT/REPLACE)
  227. $insert = "INSERT";
  228. // me dice si es un insert or update
  229. $orUpdate = false;
  230. // contiene los valores del insert or update
  231. $orUpdateValues = "";
  232. // contiene los valores para el bind del stament
  233. $arrayPrepare = array();
  234. foreach ($valueKey as $field => $value) {
  235. // recorro los datos a insertar
  236. $field = strtolower(trim($field));
  237. $value = trim($value);
  238. if (strlen($field) > 0 && strlen($value) > 0) {
  239. if ($field === 'ignore') {
  240. $value = strtolower($value);
  241. if ($value === '1' || $value === 'true') {
  242. if ($insert === 'INSERT') {
  243. $ignore = " IGNORE ";
  244. }
  245. }
  246. } else if ($field === 'replace') {
  247. $value = strtolower($value);
  248. if ($value === '1' || $value === 'true') {
  249. $insert = "REPLACE";
  250. $ignore = " ";
  251. }
  252. } else if ($field === 'orupdate') {
  253. $value = strtolower($value);
  254. if ($value === '1' || $value === 'true') {
  255. $orUpdate = true;
  256. $ignore = " ";
  257. $insert = "INSERT";
  258. }
  259. } else {
  260. $arrayPrepare[':' . $field] = $value;
  261. $fields = $fields . $field . ", ";
  262. $valuesFields = $valuesFields . ":" . $field . ", ";
  263. $orUpdateValues = $orUpdateValues . $field . " = " . ":" . $field . ", ";
  264. }
  265. }
  266. }
  267. if (strlen($fields) > 1) {
  268. $fields = substr($fields, 0, strlen($fields) - 2);
  269. }
  270. if (strlen($valuesFields) > 1) {
  271. $valuesFields = substr($valuesFields, 0, strlen($valuesFields) - 2);
  272. }
  273. if (strlen($orUpdateValues) > 1) {
  274. $orUpdateValues = substr($orUpdateValues, 0, strlen($orUpdateValues) - 2);
  275. }
  276. if (strlen($fields) > 1 && strlen($valuesFields) > 1) {
  277. $sql = $insert . $ignore . "INTO " . $table . " (" . $fields . ") VALUES (" . $valuesFields . ")";
  278. if ($orUpdate) {
  279. $sql .= " ON DUPLICATE KEY UPDATE " . $orUpdateValues . ";";
  280. } else {
  281. $sql .= ";";
  282. }
  283. $this->executeSQL($sql, MigrationsBase::INSERT, $arrayPrepare);
  284. }
  285. }
  286. }
  287. }
  288. /**
  289. * Crea los update a partir de una estructura yaml.
  290. * @param array $arrayInsert Contiene la estructura yaml para los insert.
  291. */
  292. private function createUpdates($arrayInsert)
  293. {
  294. foreach ($arrayInsert as $table => $inserts) {
  295. // recorro las tablas
  296. foreach ($inserts as $key => $valueKey) {
  297. // recorro cada uno de los insert que quiero hacer
  298. $set = "";
  299. $where = "";
  300. // contiene los valores para el bind del stament
  301. $arrayPrepare = array();
  302. foreach ($valueKey as $field => $value) {
  303. // recorro los datos a realizar un update
  304. if (strlen(trim($field)) > 0 && strlen(trim($value)) > 0) {
  305. if ($field === "where") {
  306. $where = $value;
  307. } else {
  308. $arrayPrepare[':' . $field] = $value;
  309. $set = $set . $field . " = :" . $field . ", ";
  310. }
  311. }
  312. }
  313. if (strlen($set) > 1) {
  314. $set = substr($set, 0, strlen($set) - 2);
  315. }
  316. if (strlen($set) > 1) {
  317. $sql = "UPDATE " . $table . " SET " . $set . " WHERE " . $where . ";";
  318. $this->executeSQL($sql, MigrationsBase::UPDATE, $arrayPrepare);
  319. }
  320. }
  321. }
  322. }
  323. /**
  324. * Crea los delete a partir de una estructura yaml.
  325. * @param array $arrayInsert Contiene la estructura yaml para los insert.
  326. */
  327. private function createDeletes($arrayInsert)
  328. {
  329. foreach ($arrayInsert as $table => $inserts) {
  330. // recorro las tablas
  331. foreach ($inserts as $key => $valueKey) {
  332. // recorro cada uno de los insert que quiero hacer
  333. $where = "";
  334. foreach ($valueKey as $field => $value) {
  335. // recorro los datos a realizar un update
  336. if (strlen(trim($field)) > 0 && strlen(trim($value)) > 0) {
  337. if ($field === "where") {
  338. $where = $value;
  339. }
  340. }
  341. }
  342. $sql = "DELETE FROM " . $table . " WHERE " . $where . ";";
  343. $this->executeSQL($sql, MigrationsBase::DELETE);
  344. }
  345. }
  346. }
  347. /**
  348. * Obtiene el contenido de un archivo yaml.
  349. * @param string $dir Contiene el directorio de trabajo. Por defecto "DoctrineMigrations".
  350. * @param string $archivo Contiene el nombre del archivo a incorporar.
  351. * @return bool|string Retorna el contenido del archivo.
  352. */
  353. private function readYaml($dir, $archivo)
  354. {
  355. return Yaml::parse(file_get_contents($dir . $archivo));
  356. }
  357. /**
  358. * Obtiene el contenido de un archivo.
  359. * @param string $dir Contiene el directorio de trabajo. Por defecto "DoctrineMigrations".
  360. * @param string $archivo Contiene el nombre del archivo a incorporar.
  361. * @return bool|string Retorna el contenido del archivo.
  362. */
  363. private function readImportInValues($dir, $archivo)
  364. {
  365. return file_get_contents($dir . $archivo);
  366. }
  367. /**
  368. * Reemplaza el contenido de los imports dentro de los values.
  369. * @param string $dir Contiene el directorio de trabajo. Por defecto "DoctrineMigrations".
  370. * @param array $valores Contiene el array el contenido del yaml.
  371. * @return array Retorna el array con los valores cambiados.
  372. */
  373. private function replaceImportsValue($dir, $valores)
  374. {
  375. try {
  376. foreach ($valores as $key => $value) {
  377. if (is_array($value)) {
  378. if (count($value) == 1 && array_key_exists("import", $value)) {
  379. if (file_exists($dir . $value["import"])) {
  380. $valores[$key] = $this->readImportInValues($dir, $value["import"]);
  381. } else {
  382. $valores[$key] = "FILE NOT FOUND";
  383. }
  384. } else {
  385. $valores[$key] = $this->replaceImportsValue($dir, $value);
  386. }
  387. }
  388. }
  389. } catch (\Symfony\Component\Debug\Exception\ContextErrorException $e) {
  390. var_dump($e);
  391. }
  392. return $valores;
  393. }
  394. /**
  395. * Reemplaza el contenido de los imports dentro de las key.
  396. * @param string $dir Contiene el directorio de trabajo. Por defecto "DoctrineMigrations".
  397. * @param array $valores Contiene el array el contenido del yaml.
  398. * @return array Retorna el array con los valores cambiados.
  399. */
  400. private function replaceImportsKey($dir, $valores)
  401. {
  402. try {
  403. foreach ($valores as $key => $value) {
  404. if (is_array($value)) {
  405. $valores[$key] = $this->replaceImportsKey($dir, $value);
  406. } else {
  407. if (trim($key) === "importkey") {
  408. if (file_exists($dir . $value)) {
  409. $valores = $this->readYaml($dir, $value);
  410. } else {
  411. $valores[$key] = "FILE NOT FOUND";
  412. }
  413. }
  414. }
  415. }
  416. } catch (\Symfony\Component\Debug\Exception\ContextErrorException $e) {
  417. var_dump($e);
  418. }
  419. return $valores;
  420. }
  421. /**
  422. * Funcion ejecuta el YAML en la base de datos dentro de una transaccion.
  423. * @param string $file Contiene el nombre de archivo a procesar.
  424. */
  425. protected function executeYaml($file)
  426. {
  427. $this->connection->beginTransaction();
  428. try {
  429. $this->interpretYaml($file);
  430. if (count($this->getErrorLineExecution()) > 0
  431. ) {
  432. //se produjeron errores
  433. $this->connection->rollBack();
  434. echo "Se produjeron errores.";
  435. } else {
  436. $this->connection->commit();
  437. echo "Migracion correcta.";
  438. }
  439. } catch (\Throwable $e) {
  440. $this->connection->rollBack();
  441. echo "Se produjeron errores.";
  442. }
  443. }
  444. /**
  445. * Funcion que ejecuta una sentencia sql.
  446. * @param string $sql Contiene el sql a ejecutar.
  447. * @param string $type Contiene el tipo de sentencia.
  448. * @param array $arrayPrepare Contiene un array con los valores. La key contiene el valor a
  449. * buscar en la sentencia sql y el value es el valor.
  450. */
  451. private function executeSQL($sql, $type, $arrayPrepare = null)
  452. {
  453. $stmt = $this->connection->prepare($sql);
  454. $param = "";
  455. if ($arrayPrepare != null && count($arrayPrepare) > 0) {
  456. foreach ($arrayPrepare as $keyPrepare => $valuePrepare) {
  457. $stmt->bindValue($keyPrepare, $valuePrepare);
  458. if ($this->isShowParameters()) {
  459. $param .= " [" . $keyPrepare . "]=" . $valuePrepare . " ";
  460. }
  461. }
  462. }
  463. if ($this->isShowParameters()) {
  464. if (strlen($param) > 4) {
  465. $param = " Parameters: " . substr($param, 0, strlen($param) - 4);
  466. }
  467. }
  468. try {
  469. $resp = $stmt->execute();
  470. $this->addLineExecution($type, ($resp ? "OK - " : "ERROR - ") . $sql .
  471. $param);
  472. } catch (\Throwable $ex) {
  473. $this->addLineExecution($type, "????? - " . $sql . $param);
  474. $this->addErrorLineExecution($type, $ex);
  475. }
  476. $this->sumLine();
  477. }
  478. /**
  479. * Borra la migracion de la tabla de migraciones.
  480. * @param string $obj Contiene el objeto this.
  481. */
  482. protected function deleteMigrationsVersion($obj)
  483. {
  484. $arr = explode("\\", get_class($obj));
  485. $this->connection->beginTransaction();
  486. $stmt = $this->connection->prepare("DELETE FROM migration_versions WHERE migration_versions.version = '" .
  487. str_ireplace("version", "", $arr[count($arr) - 1]) . "'");
  488. $stmt->execute();
  489. $this->connection->commit();
  490. }
  491. /**
  492. * Funcion que muestra por pantalla el resultado de la ejecucion y de los errores.
  493. */
  494. protected function showResult()
  495. {
  496. if (count($this->getLineExecution()) > 0) {
  497. echo "-----------------------------------------------\n";
  498. echo " EJECUCIONES\n";
  499. echo "-----------------------------------------------\n";
  500. foreach ($this->getLineExecution() as $key => $value) {
  501. echo $key . "\n";
  502. foreach ($this->getLineExecution()[$key] as $k => $v) {
  503. echo "\t" . $v . "\n";
  504. }
  505. }
  506. }
  507. if (count($this->getErrorLineExecution()) > 0) {
  508. echo "-----------------------------------------------\n";
  509. echo " ERRORES\n";
  510. echo "-----------------------------------------------\n";
  511. foreach ($this->getErrorLineExecution() as $key => $value) {
  512. echo $key . "\n";
  513. foreach ($this->getErrorLineExecution()[$key] as $k => $v) {
  514. echo "\t" . $v . "\n";
  515. }
  516. }
  517. }
  518. }
  519. //-----------------------------------------------------------------------------------------------
  520. // EJEMPLOS DE COMO PUEDO REALIZAR CONSULTAR A LA BASE DE DATOS.
  521. // SE ACONSEJA HACERLO EN LOS preUp/preDown/postUp/preDown
  522. //-----------------------------------------------------------------------------------------------
  523. /**
  524. * Ejemplo de como hacer un select utilizando entidades.
  525. */
  526. private function selectEntityManager()
  527. {
  528. $em = $this->container->get('doctrine.orm.entity_manager');
  529. $users = $em->getRepository("BaseUserBundle:User")->findBy(array('enabled' => 1));
  530. var_dump($users);
  531. }
  532. /**
  533. * Ejemplo de como realizar una consulta a la base de datos a travez de la conexion.
  534. */
  535. private function selectConexion()
  536. {
  537. $users = $this->connection->executeQuery("SELECT * FROM user");
  538. var_dump($users);
  539. }
  540. }