Odyssey
2018041000_globalidxupdate.php
1 <?php
2 /* Notes:
3  * 1. Anything complicated needs to be done with SQL.
4  * 2. Always have a check to know if the migration needs to occur (up or down).
5  * 3. Use up() and down(), not change(), because of the SQL
6  */
7 use Phinx\Migration\AbstractMigration;
8 
9 class GlobalIdxUpdate extends AbstractMigration
10 {
11  /* This is the process for moving forward. We are re-creating the table so if there is
12  * existing data will need to create a temporary table, copy the data, drop the old table,
13  * rename the temporary table.
14  */
15  public function up()
16  {
17  // loop through tables to update
18  $tableNames = array(
19  "scheduledtxn" => array("title"=>"cuuser_idx", "cols"=>"cu, user_id, id"),
20  "alerts" => array("title"=>"cuuser_idx", "cols"=>"cu, user_id, alerttype")
21  );
22 
23  foreach ($tableNames as $table => $index) {
24  $tableName = "cu_" . $table;
25  $tableExists = $this->hasTable( $tableName );
26  $indexName = "cu_" . $table . "_" . $index['title'];
27  $indexColumns = $index['cols'];
28 
29  // check if index exists for this table
30  $sql = "
31  SELECT COUNT(*) FROM pg_class pgc
32  WHERE pgc.relname = '{$indexName}'
33  AND pgc.relkind = 'i'";
34 
35  $idxCount = $this->fetchAll($sql);
36  $idxExists = intval($idxCount[0]['count']);
37 
38  if ($tableExists && $idxExists == 0) {
39  $sql = "CREATE INDEX {$indexName} ON {$tableName} USING btree ($indexColumns)";
40  $sqlRs = $this->query($sql);
41  }
42  }
43  }
44 
45  /* To execute this you need to run the following command:
46  * php vendor/bin/phinx rollback (using correct path to phinx)
47  * Or, to roll back to a specific time:
48  * php vendor/bin/phinx rollback -t 20151123211207
49  */
50  public function down()
51  {
52  // loop through tables to update
53  $tableNames = array(
54  "scheduledtxn" => array("title"=>"cuuser_idx", "cols"=>"cu, user_id, id"),
55  "alerts" => array("title"=>"cuuser_idx", "cols"=>"cu, user_id, alerttype")
56  );
57 
58  foreach ($tableNames as $table => $index) {
59  $tableName = "cu_" . $table;
60  $tableExists = $this->hasTable( $tableName );
61  $indexName = "cu_" . $table . "_" . $index['title'];
62  $indexColumns = $index['cols'];
63 
64  // check if index exists for this table
65  $sql = "
66  SELECT COUNT(*) FROM pg_class pgc
67  WHERE pgc.relname = '{$indexName}'
68  AND pgc.relkind = 'i'";
69 
70  $idxCount = $this->fetchAll($sql);
71  $idxExists = intval($idxCount[0]['count']);
72 
73  if ($tableExists && $idxExists > 0) {
74  $sql = "DROP INDEX {$indexName}";
75  $sqlRs = $this->query($sql);
76  }
77  }
78  }
79 }