Esempio n. 1
0
 public static function makeSql($statement, array $criteria)
 {
     $statements = [Database::SELECT => 'SELECT', Database::DELETE => 'DELETE'];
     $action = $statements[$statement];
     isset($criteria['OFFSET']) or $criteria['OFFSET'] = 0;
     isset($criteria['params']) or $criteria['params'] = [];
     if (!isset($criteria[$action])) {
         $criteria[$action] = $statement === Database::SELECT ? ['*'] : [];
     }
     $select = is_array($criteria[$action]) ? implode(",\n\t", $criteria[$action]) : $criteria[$action];
     $from = is_array($criteria['FROM']) ? implode(', ', $criteria['FROM']) : $criteria['FROM'];
     $join = isset($criteria['JOIN']) ? is_array($criteria['JOIN']) ? "\n" . implode("\n", $criteria['JOIN']) : "\n" . $criteria['JOIN'] : '';
     $group_by = isset($criteria['GROUP_BY']) ? "\nGROUP BY \n\t" . (is_array($criteria['GROUP_BY']) ? implode(",\n\t", $criteria['GROUP_BY']) : $criteria['GROUP_BY']) : '';
     $having = isset($criteria['HAVING']) ? "\nHAVING \n\t(" . implode(") \n\tAND (", $criteria['HAVING']) . ')' : '';
     $where = !empty($criteria['WHERE']) ? is_array($criteria['WHERE']) ? "\nWHERE \n\t(" . implode(") \n\tAND (", $criteria['WHERE']) . ')' : "\nWHERE " . $criteria['WHERE'] : '';
     $order_by = isset($criteria['ORDER_BY']) ? "\nORDER BY " . (is_array($criteria['ORDER_BY']) ? implode(', ', $criteria['ORDER_BY']) : $criteria['ORDER_BY']) : '';
     $limit = isset($criteria['LIMIT']) ? "\nLIMIT {$criteria['LIMIT']} OFFSET {$criteria['OFFSET']}" : '';
     $sql = "{$statements[$statement]} \n\t{$select} \nFROM {$from} {$join} {$where} {$group_by} {$having} {$order_by} {$limit}";
     return \DB::query($statement, $sql)->parameters($criteria['params']);
 }
 protected function _find($multiple, $key = null, $value = null)
 {
     $query = \DB::find($this->_criteria);
     $start_time = microtime(true);
     $result = $query->execute($this->_database_instance);
     if (static::$profiling) {
         $sql = (string) $query;
         $time_delta = sprintf('%.3F', microtime(true) - $start_time);
         file_put_contents(APPPATH . 'logs/ActiveRecord.log', "Time: {$time_delta}\n---\n{$sql}\n---\nPage url: {$_SERVER['REQUEST_URI']}\n=========================\n", FILE_APPEND);
     }
     if (!$multiple) {
         $result = $result->current();
         if (!$result) {
             // Nothing found
             return null;
         }
         return static::_createObject($result);
     }
     if ($key !== null or $value !== null) {
         $result = $result->as_array($key, $value);
         if ($value !== null) {
             return $result;
         }
     }
     if (!count($result)) {
         return [];
     }
     $arr = [];
     foreach ($result as $key => $row) {
         $arr[$key] = static::_createObject($row);
     }
     return $arr;
 }