MigrationsBase.php 17 KB

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