Solar_Sql_Adapter::createIndex PHP Method

createIndex() public method

Creates a portable index on a table.
public createIndex ( string $table, string $name, boolean $unique = false, array $cols = null ) : void
$table string The name of the table for the index.
$name string The name of the index.
$unique boolean Whether or not the index is unique.
$cols array The columns in the index. If empty, uses the $name parameters as the column name.
return void
    public function createIndex($table, $name, $unique = false, $cols = null)
    {
        // are there any columns for the index?
        if (empty($cols)) {
            // take the column name from the index name
            $cols = $name;
        }
        // check the table and index names
        $this->_checkIdentifier('table', $table);
        $this->_checkIdentifier('index', $name);
        // modify the index name as-needed
        $name = $this->_modIndexName($table, $name);
        // quote identifiers
        $name = $this->quoteName($name);
        $table = $this->quoteName($table);
        $cols = $this->quoteName($cols);
        // create a string of column names
        $cols = implode(', ', (array) $cols);
        // create index entry statement
        if ($unique) {
            $stmt = "CREATE UNIQUE INDEX {$name} ON {$table} ({$cols})";
        } else {
            $stmt = "CREATE INDEX {$name} ON {$table} ({$cols})";
        }
        return $this->query($stmt);
    }

Usage Example

Example #1
0
 /**
  * 
  * Creates the table and indexes in the database using $this->_table_cols
  * and $this->_index.
  * 
  * @return void
  * 
  */
 protected function _createTableAndIndexes()
 {
     /**
      * Create the table.
      */
     $this->_sql->createTable($this->_table_name, $this->_table_cols);
     /**
      * Create the indexes.
      */
     foreach ($this->_index as $name => $info) {
         try {
             // create this index
             $this->_sql->createIndex($this->_table_name, $info['name'], $info['type'] == 'unique', $info['cols']);
         } catch (Exception $e) {
             // cancel the whole deal.
             $this->_sql->dropTable($this->_table_name);
             throw $e;
         }
     }
 }