Ejemplo n.º 1
0
 public function __toString()
 {
     $data = $this->_compile();
     foreach ($data['values'] as $v) {
         $data['sql'] = preg_replace('/\\?/', $this->_database->quote($v), $data['sql'], 1);
     }
     return $data['sql'];
 }
Ejemplo n.º 2
0
 /**
  * Compiles the current object into a string.
  *
  * @param	string	The column name.
  * @param	string	The operator used in the conditional statement.
  * @param	object	The value to compare the column with.
  * @return	Database_Constraint_Check	The current object.
  */
 protected function _compile_check(array $data, Database $db)
 {
     // We have a keyword
     if (is_array(reset($data))) {
         // AND or OR
         $keyword = key(reset($data));
         // Compile the check params into a single string
         return $keyword . ' ' . $db->quote_identifier($data[0]) . ' ' . $data[1] . ' ' . $db->quote($data[2]);
     } else {
         // Compile the check params into a single string
         return $db->quote_identifier($data[0]) . ' ' . $data[1] . ' ' . $db->quote($data[2]);
     }
 }
 private function startQuery($search_string)
 {
     $database = new Database();
     $database->Create(new EventTable());
     /*
                 
                $sqlFullText= "CREATE FULLTEXT INDEX If Not Exists search ON ".EventTable::TableName.
                        "(".EventTable::Title.",".
                         EventTable::Description.",".
                         EventTable::SeachableKeywords.",".
                         EventTable::Venue.")";
                 
                  * ".EventTable::Title, "(".EventTable::Title.","
                           .EventTable::Description.",".EventTable::SeachableKeywords.",".EventTable::Venue."
                  * 
                 $database->runCommand($sqlFullText);
                  * */
     $query_string = $database->quote($search_string);
     $squery = "select *from " . EventTable::TableName . " WHERE ( MATCH (" . EventTable::Title . "," . EventTable::Description . "," . EventTable::SeachableKeywords . "," . EventTable::Venue . ") AGAINST ({$query_string} IN BOOLEAN MODE)) AND " . EventTable::Status . " > :zero";
     $stmt = $database->prepare($squery);
     $stmt->bindValue(":zero", 0);
     $status = $stmt->execute();
     if ($status) {
         $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
         for ($i = 0; $i < count($rows); $i++) {
             $rows[$i][EventTable::Image] = IMAGE_EVENT_PATHS . $rows[$i][EventTable::Image];
         }
         return $rows;
     } else {
         print_r($stmt->errorInfo());
         return null;
     }
 }
Ejemplo n.º 4
0
 /**
  * Compiles an array of conditions into an SQL partial. Used for WHERE
  * and HAVING.
  *
  * @param   object  Database instance
  * @param   array   condition statements
  * @return  string
  */
 public static function compile_conditions(Database $db, array $conditions)
 {
     $last_condition = NULL;
     $sql = '';
     foreach ($conditions as $group) {
         // Process groups of conditions
         foreach ($group as $logic => $condition) {
             if ($condition === '(') {
                 if (!empty($sql) and $last_condition !== '(') {
                     // Include logic operator
                     $sql .= ' ' . $logic . ' ';
                 }
                 $sql .= '(';
             } elseif ($condition === ')') {
                 $sql .= ')';
             } else {
                 if (!empty($sql) and $last_condition !== '(') {
                     // Add the logic operator
                     $sql .= ' ' . $logic . ' ';
                 }
                 // Split the condition
                 list($column, $op, $value) = $condition;
                 // Append the statement to the query
                 $sql .= $db->quote_identifier($column) . ' ' . strtoupper($op) . ' ' . $db->quote($value);
             }
             $last_condition = $condition;
         }
     }
     return $sql;
 }
Ejemplo n.º 5
0
 /**
  * Check if a table exists in the (sqlite) database.
  *
  * @param string $table
  * @return bool
  */
 private function tableExists($table)
 {
     static $tables = array();
     if (isset($tables[$table]) === false) {
         $tables[$table] = (bool) self::$database->fetchValue('SELECT count(*) FROM sqlite_master WHERE type="table" AND name=' . self::$database->quote($table));
     }
     return $tables[$table];
 }
Ejemplo n.º 6
0
 /**
  * Compiles an array of conditions into an SQL partial. Used for WHERE
  * and HAVING.
  *
  * @param   object  Database instance
  * @param   array   condition statements
  * @return  string
  */
 public static function compile_conditions(Database $db, array $conditions)
 {
     $last_condition = NULL;
     $sql = '';
     foreach ($conditions as $group) {
         // Process groups of conditions
         foreach ($group as $logic => $condition) {
             if ($condition === '(') {
                 if (!empty($sql) and $last_condition !== '(') {
                     // Include logic operator
                     $sql .= ' ' . $logic . ' ';
                 }
                 $sql .= '(';
             } elseif ($condition === ')') {
                 $sql .= ')';
             } else {
                 if (!empty($sql) and $last_condition !== '(') {
                     // Add the logic operator
                     $sql .= ' ' . $logic . ' ';
                 }
                 // Split the condition
                 list($column, $op, $value) = $condition;
                 // Database operators are always uppercase
                 $op = strtoupper($op);
                 if ($op === 'BETWEEN' and is_array($value)) {
                     // BETWEEN always has exactly two arguments
                     list($min, $max) = $value;
                     // Quote the min and max value
                     $value = $db->quote($min) . ' AND ' . $db->quote($max);
                 } else {
                     // Quote the entire value normally
                     $value = $db->quote($value);
                 }
                 // Append the statement to the query
                 $sql .= $db->quote_identifier($column) . ' ' . $op . ' ' . $value;
             }
             $last_condition = $condition;
         }
     }
     return $sql;
 }
Ejemplo n.º 7
0
 /**
  * Insere um autor no banco de dados
  * @return mixed O resultado da query
  */
 public function insert()
 {
     $db = new Database();
     $data = [];
     if (!empty($this->id_autor)) {
         $data['id_autor'] = (int) $this->id_autor;
     }
     if (!empty($this->nome)) {
         $data['nome'] = $db->quote($this->nome);
     }
     return $db->insert('autor', $data);
 }
Ejemplo n.º 8
0
 protected function _compile_set(Database $db, array $values)
 {
     $set = array();
     foreach ($values as $group) {
         list($column, $value) = $group;
         $column = $db->quote_column($column);
         if ((is_string($value) and array_key_exists($value, $this->_parameters)) === FALSE) {
             $value = $db->quote($value);
         }
         $set[$column] = $column . ' = ' . $value;
     }
     return implode(', ', $set);
 }
Ejemplo n.º 9
0
 /**
  * Replaces any parameter placeholders in a query with the value of that
  * parameter. Useful for debugging. Assumes anonymous parameters from
  * $params are are in the same order as specified in $query.
  *
  * @param string $query  The sql query with parameter placeholders
  * @param array  $params The array of substitution parameters
  *
  * @return string The interpolated query
  */
 private function interpolate($query, $params)
 {
     $keys = [];
     // build a regular expression for each parameter
     foreach ($params as $key => $value) {
         if (is_string($key)) {
             $keys[] = '/:' . preg_quote($key) . '/';
         } else {
             $keys[] = '/[?]/';
         }
         $params[$key] = $this->database->quote($value, \PDO::PARAM_STR);
     }
     return preg_replace($keys, $params, $query, 1);
 }
Ejemplo n.º 10
0
 public function compile(Database $db)
 {
     switch ($this->_drop_type) {
         case 'database':
             return 'DROP DATABASE ' . $db->quote($this->_object->name);
         case 'table':
             return 'DROP TABLE ' . $db->quote_table($this->_object->name);
         case 'column':
             return 'DROP COLUMN ' . $db->quote_identifier($this->_object->name);
         default:
             throw new Database_Exception('Invalid drop object');
     }
     return $query;
 }
Ejemplo n.º 11
0
 /**
  * Compile the SQL query and return it.
  *
  * @param   object  Database instance
  * @return  string
  */
 public function compile(Database $db)
 {
     // Start an update query
     $query = 'UPDATE ' . $db->quote_table($this->_table);
     $update = array();
     foreach ($this->_set as $set) {
         // Split the set
         list($column, $value) = $set;
         // Quote the column name
         $column = $db->quote_identifier($column);
         $update[$column] = $column . ' = ' . $db->quote($value);
     }
     // Add the columns to update
     $query .= ' SET ' . implode(', ', $update);
     if (!empty($this->_where)) {
         // Add selection conditions
         $query .= ' WHERE ' . Database_Query_Builder::compile_conditions($db, $this->_where);
     }
     return $query;
 }
Ejemplo n.º 12
0
 public function compile(Database $db)
 {
     // Lets identify the type
     switch (strtolower($this->_drop_type)) {
         // We're dropping an entire database!
         case 'database':
             return 'DROP DATABASE ' . $db->quote($this->_name);
             // Just a table to be dropped.
         // Just a table to be dropped.
         case 'table':
             return 'DROP TABLE ' . $db->quote_table($this->_name);
             // A column to be dropped.
         // A column to be dropped.
         case 'column':
         case 'constraint':
         case 'index':
             return 'DROP ' . strtoupper($this->_drop_type) . ' ' . $db->quote_identifier($this->_name);
             // Something we did not recognise.
         // Something we did not recognise.
         default:
             return 'DROP ' . strtoupper($this->_drop_type) . ' ' . $this->_name;
     }
 }
Ejemplo n.º 13
0
                         $db->query($query);
                     } else {
                         if (isset($_GET['insert'])) {
                             $query = "INSERT INTO " . $_GET['table'] . " (";
                             $i = 0;
                             foreach ($_POST as $vblname => $value) {
                                 $query .= $vblname . ",";
                             }
                             $query = substr($query, 0, sizeof($query) - 2);
                             $query .= ") VALUES (";
                             $i = 0;
                             foreach ($_POST as $vblname => $value) {
                                 if ($value == "") {
                                     $query .= "NULL,";
                                 } else {
                                     $query .= $db->quote($value) . ",";
                                 }
                             }
                             $query = substr($query, 0, sizeof($query) - 2);
                             $query .= ")";
                             $db->query($query);
                             $insertQuery = $query;
                         }
                     }
                 }
             }
         }
     }
 }
 echo "<div id='container'>";
 echo "<div id='leftNav'>";
Ejemplo n.º 14
0
 /**
  * Appends a WHERE statement to the {@link $query}.
  * The $column parameter holds a string that looks something like "table.datecolumn"
  *
  * The DTO parameter specified by $name will be compared against the column
  *
  * @param Database $db     The database
  * @param Query    $query  The Query
  * @param DTO      $dto    The DTO
  * @param string   $name   The name of the DTO parameter that holds the value
  * @param string   $column A string that will be used in the WHERE query
  *
  * @return void
  */
 public function buildEqualsFilter($db, $query, $dto, $name, $column = null)
 {
     if ($dto->getParameter($name) != null) {
         if (empty($column)) {
             $column = $name;
         }
         $value = $dto->getParameter($name);
         if (is_array($value)) {
             if (in_array('NULL', $value)) {
                 $query->WHERE("{$column} IS NULL OR {$column} IN (" . $db->joinQuote($value) . ")");
             } else {
                 $query->WHERE("{$column} IN (" . $db->joinQuote($value) . ")");
             }
         } else {
             if (is_null($value)) {
                 $query->WHERE("{$column} IS NULL");
             } else {
                 $query->WHERE("{$column} = {$db->quote($value)}");
             }
         }
     }
 }
Ejemplo n.º 15
0
 /**
  * database connection test.
  */
 public function test_database_connection()
 {
     $name = "test_database_connection";
     $db = new Database();
     test($db->getDatabaseObject());
     if ($db->tableExists($name)) {
         $db->dropTable($name);
     }
     // table exists
     test($db->tableExists($name) == FALSE);
     $db->createTable($name);
     test($db->tableExists($name));
     // quote
     // @Attention 반드시 아래의 quote 가 통과를 해야 한다.
     $ret_str = $db->quote("str");
     test($ret_str == "'str'", '', 'Quote failed...');
     $ret_str = $db->quote("st'r");
     test($ret_str == "'st''r'", '', 'Quote failed...');
     // table drop
     $db->dropTable($name);
     test($db->tableExists($name) == FALSE);
 }
Ejemplo n.º 16
0
 /**
  * Don't put quotes around number for columns that are assumend to be integers ('id' or ending in '_id').
  *
  * @param Database $db
  * @param string   $column
  * @param mixed    $value
  */
 private function quote($db, $column, $value)
 {
     if (($column == 'id' || substr($column, -3) == '_id') && (is_int($value) || preg_match('/^[123456789]{1}[0-9]*$/', $value))) {
         return $value;
     }
     return $db->quote($value);
 }
Ejemplo n.º 17
0
 /**
  * Compile the SQL partial for a JOIN statement and return it.
  *
  * @param   \Gleez\Database\Database  $db  Database instance or name of instance
  * @param   array  The array of join condition
  * @return  string
  */
 protected function compileJoin(Database $db, $join)
 {
     if (!empty($join['type'])) {
         $query = strtoupper($join['type']) . ' JOIN';
     } else {
         $query = 'JOIN';
     }
     // Quote the table name that is being joined
     $query .= ' ' . $db->getConnection()->quoteTable($join['table']);
     if (!empty($this->using)) {
         $quote_column = array($db->getConnection(), 'quoteIdentifier');
         // Quote and concat the columns
         $query .= ' USING (' . implode(', ', array_map($quote_column, $this->using)) . ')';
     } elseif (isset($join['on']) && !empty($join['on'])) {
         $conditions = array();
         foreach ($join['on'] as $k => $condition) {
             // Split the condition
             list($c1, $op, $c2) = $condition;
             if ($op) {
                 // Make the operator uppercase and spaced
                 $op = ' ' . strtoupper($op);
             }
             // Quote each of the columns used for the condition
             $conditions[] = $db->getConnection()->quoteIdentifier($c1) . $op . ' ' . $db->quoteIdentifier($c2);
         }
         // Concat the conditions "... AND ..."
         $query .= ' ON (' . implode(' AND ', $conditions) . ')';
         if (isset($join['and']) && !empty($join['and'])) {
             $and_conditions = array();
             foreach ($join['and'] as $icondition) {
                 // Split the condition
                 list($c1, $op, $v1) = $icondition;
                 if ($op) {
                     // Make the operator uppercase and spaced
                     $op = ' ' . strtoupper($op);
                 }
                 // Quote each of the columns used for the condition. v1 is quote value not column
                 $and_conditions[] = $db->getConnection()->quoteIdentifier($c1) . $op . ' ' . $db->quote($v1);
             }
             if (!empty($and_conditions)) {
                 // Concat the conditions "... AND ..."
                 $query .= ' AND ' . implode(' AND ', $and_conditions) . '';
             }
         }
     }
     return $query;
 }
Ejemplo n.º 18
0
 //row actions
 /////////////////////////////////////////////// create row
 case "row_create":
     $query = "INSERT INTO " . $_GET['table'] . " (";
     $i = 0;
     foreach ($_POST as $vblname => $value) {
         $query .= $vblname . ",";
     }
     $query = substr($query, 0, sizeof($query) - 2);
     $query .= ") VALUES (";
     $i = 0;
     foreach ($_POST as $vblname => $value) {
         if ($value == "") {
             $query .= "NULL,";
         } else {
             $query .= $db->quote($value) . ",";
         }
     }
     $query = substr($query, 0, sizeof($query) - 2);
     $query .= ")";
     $result = $db->query($query);
     if (!$result) {
         $error = true;
     }
     $completed = "1 row(s) inserted.<br/><span style='font-size:11px;'>" . $query . "</span>";
     break;
     /////////////////////////////////////////////// delete row
 /////////////////////////////////////////////// delete row
 case "row_delete":
     $pks = explode(":", $_GET['pk']);
     $str = $pks[0];
Ejemplo n.º 19
0
 /**
  * Compiles an array of set values into an SQL partial. Used for UPDATE.
  *
  * @param   object $db     Database instance
  * @param   array  $values updated values
  *
  * @return  string
  */
 protected function _compile_set(Database $db, array $values)
 {
     $set = [];
     foreach ($values as $group) {
         // Split the set
         list($column, $value) = $group;
         // Quote the column name
         $column = $db->quote_column($column);
         if ((is_string($value) and array_key_exists($value, $this->_parameters)) === false) {
             // Quote the value, it is not a parameter
             $value = $db->quote($value);
         }
         $set[$column] = $column . ' = ' . $value;
     }
     return implode(', ', $set);
 }
Ejemplo n.º 20
0
 /**
  * Compile the SQL query and return it.
  *
  * @param   object  Database instance
  * @return  string
  */
 public function compile(Database $db)
 {
     // Start an insertion query
     $query = 'INSERT INTO ' . $db->quote_table($this->_table);
     // Add the column names
     $query .= ' (' . implode(', ', array_map(array($db, 'quote_column'), $this->_columns)) . ') ';
     if (is_array($this->_values)) {
         // Callback for quoting values
         $quote = array($db, 'quote');
         $groups = array();
         foreach ($this->_values as $group) {
             foreach ($group as $offset => $value) {
                 if ((is_string($value) and array_key_exists($value, $this->_parameters)) === FALSE) {
                     // Quote the value, it is not a parameter
                     $group[$offset] = $db->quote($value);
                 }
             }
             $groups[] = '(' . implode(', ', $group) . ')';
         }
         // Add the values
         $query .= 'VALUES ' . implode(', ', $groups);
     } else {
         // Add the sub-query
         $query .= (string) $this->_values;
     }
     $this->_sql = $query;
     return parent::compile($db);
 }
Ejemplo n.º 21
0
 public function quote($value)
 {
     if ($this->config['escape']) {
         // This format works in boolean and integer columns
         if ($value === TRUE) {
             return "'1'";
         }
         if ($value === FALSE) {
             return "'0'";
         }
     }
     return parent::quote($value);
 }
Ejemplo n.º 22
0
 /**
  * Returns condition code for sql query
  *
  * @param bool should returned condition code start with WHERE (false) or AND (true)?
  * @return string the condition code
  */
 public function getSqlWhere($append = false)
 {
     if ($this->searchtext != '') {
         if ($append == true) {
             $condition = ' AND ';
         } else {
             $condition = ' WHERE ';
         }
         $searchfield = explode('.', $this->searchfield);
         foreach ($searchfield as $id => $field) {
             if (substr($field, -1, 1) != '`') {
                 $field .= '`';
             }
             if ($field[0] != '`') {
                 $field = '`' . $field;
             }
             $searchfield[$id] = $field;
         }
         $searchfield = implode('.', $searchfield);
         $ops = array('<', '>', '=');
         // check if we use an operator or not
         $useOper = 0;
         $oper = "=";
         if (in_array(substr($this->searchtext, 0, 1), $ops)) {
             $useOper = 1;
             $oper = substr($this->searchtext, 0, 1);
         }
         // check for diskspace and whether searchtext is a number
         // in any other case the logical-operators would make no sense
         if (strpos($searchfield, 'diskspace') > 0 && is_numeric(substr($this->searchtext, $useOper))) {
             // anything with diskspace is *1024
             $searchtext = (int) substr($this->searchtext, $useOper) * 1024;
             $useOper = 1;
         } elseif (strpos($searchfield, 'traffic') > 0 && is_numeric(substr($this->searchtext, $useOper))) {
             // anything with traffic is *1024*1024
             $searchtext = (int) substr($this->searchtext, $useOper) * 1024 * 1024;
             $useOper = 1;
         } else {
             // any other field
             $searchtext = substr($this->searchtext, $useOper);
         }
         if ($useOper == 1 && is_numeric(substr($this->searchtext, $useOper))) {
             // now as we use >, < or = we use the given operator and not LIKE
             $condition .= $searchfield . " " . $oper . " " . Database::quote($searchtext);
         } else {
             $searchtext = str_replace('*', '%', $this->searchtext);
             $condition .= $searchfield . " LIKE " . Database::quote($searchtext);
         }
     } else {
         $condition = '';
     }
     return $condition;
 }
Ejemplo n.º 23
0
 for ($j = 0; $j < sizeof($fields); $j++) {
     $query .= $fields[$j] . ",";
 }
 $query = substr($query, 0, sizeof($query) - 2);
 $query .= ") VALUES (";
 for ($j = 0; $j < sizeof($fields); $j++) {
     $value = $_POST[$i . ":" . $fields[$j]];
     $null = isset($_POST[$i . ":" . $fields[$j] . "_null"]);
     $type = $result[$j][2];
     $function = $_POST["function_" . $i . "_" . $fields[$j]];
     if ($function != "") {
         $query .= $function . "(";
     }
     //di - messed around with this logic for null values
     if (($type == "TEXT" || $type == "BLOB") && $null == false) {
         $query .= $db->quote($value);
     } else {
         if (($type == "INTEGER" || $type == "REAL") && $null == false && $value == "") {
             $query .= "NULL";
         } else {
             if ($null == true) {
                 $query .= "NULL";
             } else {
                 $query .= $db->quote($value);
             }
         }
     }
     if ($function != "") {
         $query .= ")";
     }
     $query .= ",";
Ejemplo n.º 24
0
if (isset($_GET['offset'])) {
    $temp_offset = $_GET['offset'];
    if (is_numeric($temp_offset)) {
        if ($temp_offset >= 0 && $temp_offset < 25000) {
            $list_offset = (int) $temp_offset;
        }
    }
}
$where_track_count = "";
$where_release_date = "";
$where_availability = "";
$where_genres = "";
if (isset($_GET['genres'])) {
    $where_genres = "(";
    foreach ($_GET['genres'] as $g) {
        $where_genres .= ' genres LIKE ' . $database->quote('%"' . $g . '"%') . ' OR';
    }
    $where_genres = rtrim($where_genres, ' OR');
    $where_genres .= ")";
} else {
    $where_track_count = "( tracks > 3 AND tracks < 25 ) AND ";
    $where_release_date = "( release_date BETWEEN :lastfriday AND :thisfriday ) AND ";
    $where_availability = "( availability LIKE '%US%' OR availability='ANY' )";
}
$query = $database->prepare("SELECT * FROM albums WHERE " . $where_track_count . $where_release_date . $where_availability . $where_genres . " ORDER BY popularity DESC LIMIT :offset, :limit");
if (!isset($_GET['genres'])) {
    $query->bindParam(':lastfriday', $previous_date, PDO::PARAM_STR);
    $query->bindParam(':thisfriday', $next_date, PDO::PARAM_STR);
}
$query->bindParam(':offset', $list_offset, PDO::PARAM_INT);
$query->bindParam(':limit', $limit, PDO::PARAM_INT);
Ejemplo n.º 25
0
 /**
  * Compiles an array of set values into an SQL partial. Used for UPDATE.
  *
  * @param   object  Database instance
  * @param   array   updated values
  * @return  string
  */
 protected function _compile_set(Database $db, array $values)
 {
     $set = array();
     foreach ($values as $group) {
         // Split the set
         list($column, $value) = $group;
         // Quote the column name
         $column = $db->quote_identifier($column);
         if (is_string($value) and array_key_exists($value, $this->_parameters)) {
             // Use the parameter value
             $value = $this->_parameters[$value];
         }
         $set[$column] = $column . ' = ' . $db->quote($value);
     }
     return implode(', ', $set);
 }
Ejemplo n.º 26
0
 /**
  * Extract the Database schema from a MySQL database.
  *
  * @param Database $db
  *
  * @return array schema definition
  */
 private function getSchemaMySql($db, $prefix = '')
 {
     $schema = [];
     if ($prefix != '') {
         $tables = $db->query('SHOW TABLES LIKE ' . $db->quote($prefix . '%'));
     } else {
         $tables = $db->query('SHOW TABLES');
     }
     foreach ($tables as $row) {
         $table = current($row);
         $referencedBy = isset($schema[$table]) ? $schema[$table]['referencedBy'] : [];
         $schema[$table] = ['table' => $table, 'columns' => [], 'primaryKeys' => [], 'referencedBy' => $referencedBy];
         $config =& $schema[$table];
         $showCreate = $db->fetchRow('SHOW CREATE TABLE ' . $db->quoteIdentifier($table));
         $createSyntax = $showCreate['Create Table'];
         $lines = explode("\n", $createSyntax);
         unset($lines[0]);
         // CREATE TABLE * (
         unset($lines[count($lines)]);
         // ) ENGINE=*
         foreach ($lines as $line) {
             $line = preg_replace('/^  |,$/', '', $line);
             // "  " & "," weghalen
             $line = str_replace('NOT ', 'NOT_', $line);
             $line = str_replace(' KEY', '_KEY', $line);
             $line = str_ireplace('CHARACTER SET', 'CHARACTER_SET', $line);
             $line = str_ireplace('ON UPDATE', 'ON_UPDATE', $line);
             $line = str_replace('  ', ' ', $line);
             $parts = explode(' ', $line);
             if (substr($parts[0], 0, 1) == '`') {
                 // Column description
                 $column = substr($parts[0], 1, -1);
                 $config['columns'][$column] = ['type' => $parts[1], 'null' => true];
                 $columnConfig =& $config['columns'][$column];
                 for ($i = 2; $i < count($parts); ++$i) {
                     $part = $parts[$i];
                     switch (strtoupper($part)) {
                         case 'NOT_NULL':
                             $columnConfig['null'] = false;
                             break;
                         case 'NULL':
                             $columnConfig['null'] = true;
                             break;
                         case 'AUTO_INCREMENT':
                             break;
                         case 'DEFAULT':
                             $default = '';
                             while ($part = $parts[$i + 1]) {
                                 ++$i;
                                 $default .= $part;
                                 if (substr($default, 0, 1) != "'") {
                                     // Not a quoted string value?
                                     break;
                                     // end for loop
                                 }
                                 if (substr($default, -1) == "'") {
                                     // End of quoted string?
                                     break;
                                     // end for loop
                                 }
                                 $default .= ' ';
                             }
                             if (substr($default, 0, 1) == "'") {
                                 $config['columns'][$column]['default'] = substr($default, 1, -1);
                                 // remove quotes
                             } else {
                                 switch ($default) {
                                     case 'NULL':
                                         $default = null;
                                         break;
                                     case 'CURRENT_TIMESTAMP':
                                         $default = null;
                                         break;
                                     default:
                                         notice('Unknown default "' . $default . '" in "' . $line . '"');
                                         break;
                                 }
                                 $config['columns'][$column]['default'] = $default;
                             }
                             break;
                         case 'UNSIGNED':
                             $config['columns'][$column]['type'] = 'unsigned ' . $config['columns'][$column]['type'];
                             break;
                         case 'COMMENT':
                             $i += $this->stripQuotedValue($parts, $comment, $i);
                             $config['columns'][$column]['comment'] = $comment;
                             break;
                         case 'ON_UPDATE':
                         case 'CHARACTER_SET':
                         case 'COLLATE':
                             $i++;
                             // ignore value
                             break;
                         default:
                             notice('Unknown part "' . $part . '" in "' . $line . '"');
                             break;
                     }
                 }
             } else {
                 // Key description
                 $exploded = explode(' ', $line);
                 $parts = [];
                 for ($i = 0; $i < count($exploded); ++$i) {
                     $part = $exploded[$i];
                     if (substr($part, 0, 1) === '`') {
                         --$i;
                         $i += $this->stripQuotedValue($exploded, $value, $i, '`');
                         $parts[] = $value;
                     } else {
                         $parts[] = str_replace('`', '', $part);
                         // @todo Parse the "(`id`)" parts. Spaces in columnnames are unlikely but possible.
                     }
                 }
                 switch ($parts[0]) {
                     case 'PRIMARY_KEY':
                         $config['primaryKeys'] = explode(',', substr($parts[1], 1, -1));
                         break;
                     case 'KEY':
                     case 'UNIQUE_KEY':
                     case 'FULLTEXT_KEY':
                         break;
                         // Skip
                     // Skip
                     case 'CONSTRAINT':
                         if ($parts[2] != 'FOREIGN_KEY') {
                             notice('Unknown constraint: "' . $line . '"');
                             break;
                         }
                         if ($parts[4] != 'REFERENCES') {
                             notice('Unknown foreign key: "' . $line . '"');
                             break;
                         }
                         $column = substr($parts[3], 1, -1);
                         $foreignTable = $parts[5];
                         $foreignColumn = substr($parts[6], 1, -1);
                         $config['columns'][$column]['foreignKeys'][] = ['table' => $foreignTable, 'column' => $foreignColumn];
                         $schema[$foreignTable]['referencedBy'][] = ['table' => $table, 'column' => $column];
                         break;
                     default:
                         notice('Unknown metadata "' . $parts[0] . '" in "' . $line . '"', $lines);
                         break;
                 }
             }
         }
         unset($config);
     }
     return $schema;
 }
Ejemplo n.º 27
0
$target_table = isset($_GET['table']) ? $_GET['table'] : null;
//- Switch on $_GET['action'] for operations without output
if (isset($_GET['action']) && isset($_GET['confirm'])) {
    switch ($_GET['action']) {
        //- Table actions
        //- Create table (=table_create)
        case "table_create":
            $num = intval($_POST['rows']);
            $name = $_POST['tablename'];
            $primary_keys = array();
            for ($i = 0; $i < $num; $i++) {
                if ($_POST[$i . '_field'] != "" && isset($_POST[$i . '_primarykey'])) {
                    $primary_keys[] = $_POST[$i . '_field'];
                }
            }
            $query = "CREATE TABLE " . $db->quote($name) . " (";
            for ($i = 0; $i < $num; $i++) {
                if ($_POST[$i . '_field'] != "") {
                    $query .= $db->quote($_POST[$i . '_field']) . " ";
                    $query .= $_POST[$i . '_type'] . " ";
                    if (isset($_POST[$i . '_primarykey'])) {
                        if (count($primary_keys) == 1) {
                            $query .= "PRIMARY KEY ";
                            if (isset($_POST[$i . '_autoincrement']) && $db->getType() != "SQLiteDatabase") {
                                $query .= "AUTOINCREMENT ";
                            }
                        }
                        $query .= "NOT NULL ";
                    }
                    if (!isset($_POST[$i . '_primarykey']) && isset($_POST[$i . '_notnull'])) {
                        $query .= "NOT NULL ";
Ejemplo n.º 28
0
}
$db->query('CREATE INDEX end_ix ON ip2country (end)');
// Kolomnamen toevoegen
//ini_set('memory_limit', '128M');
file_put_contents($csvFile, "begin_ip,end_ip,begin_num,end_num,code,country\n" . file_get_contents($csvFile));
// Eerst de countries importeren
$csv = new CSV($csvFile, null, ',');
$countries = array();
$rowCount = 0;
foreach ($csv as $row) {
    $countries[$row['code']] = $row['country'];
    $rowCount++;
}
$db->beginTransaction();
foreach ($countries as $code => $country) {
    $db->query('INSERT INTO country (code, name) VALUES (' . $db->quote($code) . ', ' . $db->quote($country) . ')');
}
echo " done.\n";
echo "  Importing data (";
// Daarna alle ip-ranges importeren.
echo $rowCount . " records)\n    ";
$previousTs = microtime(true);
if ($VERBOSE) {
    $statement = $db->prepare('INSERT INTO ip2country (begin, end, ip_begin, ip_end, country_code) VALUES (:begin, :end, :ip_begin, :ip_end, :country_code)');
} else {
    $statement = $db->prepare('INSERT INTO ip2country (begin, end, country_code) VALUES (:begin, :end, :country_code)');
}
foreach ($csv as $index => $row) {
    $now = microtime(true);
    if ($previousTs < $now - 1) {
        echo round($index / $rowCount * 100), '% ';