Example #1
0
 /**
  * Get the Query string
  * 
  * @throws Exception
  * @return string
  */
 protected function getQuery()
 {
     $this->bindings = array();
     if (sizeof($this->data) == 0 && $this->select === null) {
         throw new Exception('Can not execute Insert query, no records to insert');
     }
     $hasFields = count($this->fields) > 0;
     $query = "INSERT INTO {$this->table}";
     if ($hasFields) {
         $query .= ' (';
         foreach ($this->fields as $field) {
             $query .= $field . ',';
         }
         $query = substr($query, 0, -1) . ')';
     }
     if ($this->select !== null) {
         $query .= "\n(\n\t" . str_replace("\n", "\n\t", $this->select->__toString()) . "\n)";
         $this->bindings = $this->select->getBindings();
     } else {
         $query .= "\nVALUES\n";
         foreach ($this->data as $index => $row) {
             $query .= "\t(";
             if ($hasFields) {
                 foreach ($this->fields as $field) {
                     if (isset($row[$field])) {
                         $val = $row[$field];
                         if ($val instanceof Expr) {
                             $query .= "{$val},";
                         } else {
                             $key = 'field' . $index . static::getKeyIndex();
                             $query .= ":{$key},";
                             $this->bindings[$key] = $val;
                         }
                     } else {
                         $query .= 'NULL,';
                     }
                 }
                 $query = substr($query, 0, -1);
             } else {
                 $values = array_values($row);
                 if ($index == 0) {
                     $targetCount = count($row);
                 } else {
                     if (sizeof($row) != $targetCount) {
                         throw new Exception('Can not build INSERT query, column count is not the same in all data records');
                     }
                 }
                 foreach ($values as $i => $val) {
                     if ($val instanceof Expr) {
                         $query .= "{$val},";
                     } else {
                         $key = 'field' . $i . static::getKeyIndex();
                         $query .= ":{$key},";
                         $this->bindings[$key] = $val;
                     }
                 }
                 $query = substr($query, 0, -1);
             }
             $query .= "),\n";
         }
         $query = substr($query, 0, -2);
     }
     return $query;
 }