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