MigrationsBase.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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 <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. $this->connection->beginTransaction();
  430. try {
  431. $this->interpretYaml($dir, $file);
  432. if (count($this->getErrorLineExecution()) > 0
  433. ) {
  434. //se produjeron errores
  435. $this->connection->rollBack();
  436. echo "\nSe produjeron errores de sql.\n";
  437. } else {
  438. $this->connection->commit();
  439. echo "\nMigracion correcta.\n";
  440. }
  441. } catch (\Throwable $e) {
  442. $this->connection->rollBack();
  443. echo "\nSe produjeron errores por una excepcion. " . $e->getMessage() . "\n";
  444. }
  445. }
  446. /**
  447. * Funcion que ejecuta una sentencia sql.
  448. * @param string $sql Contiene el sql a ejecutar.
  449. * @param string $type Contiene el tipo de sentencia.
  450. * @param array $arrayPrepare Contiene un array con los valores. La key contiene el valor a
  451. * buscar en la sentencia sql y el value es el valor.
  452. */
  453. private function executeSQL($sql, $type, $arrayPrepare = null)
  454. {
  455. $stmt = $this->connection->prepare($sql);
  456. $param = "";
  457. if ($arrayPrepare != null && count($arrayPrepare) > 0) {
  458. foreach ($arrayPrepare as $keyPrepare => $valuePrepare) {
  459. $stmt->bindValue($keyPrepare, $valuePrepare);
  460. if ($this->isShowParameters()) {
  461. $param .= " [" . $keyPrepare . "]=" . $valuePrepare . " ";
  462. }
  463. }
  464. }
  465. if ($this->isShowParameters()) {
  466. if (strlen($param) > 4) {
  467. $param = " Parameters: " . substr($param, 0, strlen($param) - 4);
  468. }
  469. }
  470. try {
  471. $resp = $stmt->execute();
  472. $this->addLineExecution($type, ($resp ? "OK - " : "ERROR - ") . $sql .
  473. $param);
  474. } catch (\Throwable $ex) {
  475. $this->addLineExecution($type, "????? - " . $sql . $param);
  476. $this->addErrorLineExecution($type, $ex);
  477. }
  478. $this->sumLine();
  479. }
  480. /**
  481. * Borra la migracion de la tabla de migraciones.
  482. * @param string $obj Contiene el objeto this.
  483. */
  484. protected function deleteMigrationsVersion($obj)
  485. {
  486. $arr = explode("\\", get_class($obj));
  487. $this->connection->beginTransaction();
  488. $stmt = $this->connection->prepare("DELETE FROM migration_versions WHERE migration_versions.version = '" .
  489. str_ireplace("version", "", $arr[count($arr) - 1]) . "'");
  490. $stmt->execute();
  491. $this->connection->commit();
  492. }
  493. /**
  494. * Funcion que muestra por pantalla el resultado de la ejecucion y de los errores.
  495. */
  496. protected function showResult()
  497. {
  498. if (count($this->getLineExecution()) > 0) {
  499. echo "-----------------------------------------------\n";
  500. echo " EJECUCIONES\n";
  501. echo "-----------------------------------------------\n";
  502. foreach ($this->getLineExecution() as $key => $value) {
  503. echo $key . "\n";
  504. foreach ($this->getLineExecution()[$key] as $k => $v) {
  505. echo "\t" . $v . "\n";
  506. }
  507. }
  508. }
  509. if (count($this->getErrorLineExecution()) > 0) {
  510. echo "-----------------------------------------------\n";
  511. echo " ERRORES\n";
  512. echo "-----------------------------------------------\n";
  513. foreach ($this->getErrorLineExecution() as $key => $value) {
  514. echo $key . "\n";
  515. foreach ($this->getErrorLineExecution()[$key] as $k => $v) {
  516. echo "\t" . $v . "\n";
  517. }
  518. }
  519. }
  520. }
  521. //-----------------------------------------------------------------------------------------------
  522. // EJEMPLOS DE COMO PUEDO REALIZAR CONSULTAR A LA BASE DE DATOS.
  523. // SE ACONSEJA HACERLO EN LOS preUp/preDown/postUp/preDown
  524. //-----------------------------------------------------------------------------------------------
  525. /**
  526. * Ejemplo de como hacer un select utilizando entidades.
  527. */
  528. private function selectEntityManager()
  529. {
  530. $em = $this->container->get('doctrine.orm.entity_manager');
  531. $users = $em->getRepository("BaseUserBundle:User")->findBy(array('enabled' => 1));
  532. var_dump($users);
  533. }
  534. /**
  535. * Ejemplo de como realizar una consulta a la base de datos a travez de la conexion.
  536. */
  537. private function selectConexion()
  538. {
  539. $users = $this->connection->executeQuery("SELECT * FROM user");
  540. var_dump($users);
  541. }
  542. }