Odyssey
2019061100_addcorerequestsidx.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 AddCoreRequestsIDX 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 indexes to update
18  $indexNames = array(
19  "cucorerequests_idx01" => array("cols"=>"cu, accountnumber, request_start, request_end"),
20  "cucorerequests_idx02" => array("cols"=>"appliance_ip, accountnumber, request_start, request_end"),
21  "cucorerequests_idx03" => array("cols"=>"cu, request_type, request_start, request_end")
22  );
23 
24  $tableName = "cucorerequests";
25  $tableExists = $this->hasTable( $tableName );
26 
27  foreach ($indexNames as $index => $cols) {
28  $indexName = $tableName . "_" . $index;
29  $indexColumns = $cols['cols'];
30 
31 
32  // check if index exists for this table
33  $sql = "
34  SELECT COUNT(*) FROM pg_class pgc
35  WHERE pgc.relname = '{$indexName}'
36  AND pgc.relkind = 'i'";
37 
38  $idxCount = $this->fetchAll($sql);
39  $idxExists = intval($idxCount[0]['count']);
40 
41  if ($tableExists && $idxExists == 0) {
42  $sql = "CREATE INDEX {$indexName} ON {$tableName} USING btree ($indexColumns)";
43  $sqlRs = $this->query($sql);
44  }
45  }
46  }
47 
48  /* To execute this you need to run the following command:
49  * php vendor/bin/phinx rollback (using correct path to phinx)
50  * Or, to roll back to a specific time:
51  * php vendor/bin/phinx rollback -t 20151123211207
52  */
53  public function down()
54  {
55  // loop through indexes to update
56  $indexNames = array(
57  "cucorerequests_idx01" => array("cols"=>"cu, accountnumber, request_start, request_end"),
58  "cucorerequests_idx02" => array("cols"=>"appliance_ip, accountnumber, request_start, request_end"),
59  "cucorerequests_idx03" => array("cols"=>"cu, request_type, request_start, request_end")
60  );
61 
62  $tableName = "cucorerequests";
63  $tableExists = $this->hasTable( $tableName );
64 
65  foreach ($indexNames as $index => $cols) {
66  $indexName = $tableName . "_" . $index;
67  $indexColumns = $cols['cols'];
68 
69  // check if index exists for this table
70  $sql = "
71  SELECT COUNT(*) FROM pg_class pgc
72  WHERE pgc.relname = '{$indexName}'
73  AND pgc.relkind = 'i'";
74 
75  $idxCount = $this->fetchAll($sql);
76  $idxExists = intval($idxCount[0]['count']);
77 
78  if ($tableExists && $idxExists > 0) {
79  $sql = "DROP INDEX {$indexName}";
80  $sqlRs = $this->query($sql);
81  }
82  }
83  }
84 }