SQL

@param array $options
@param array $cache_tags
@return string
430577
public function sql(array $options, array & $cache_tags = null) : string {
		$options['return_query_only'] = 'wrap';
		$result = $this->get($options);
		if (isset($cache_tags)) {
			$cache_tags = array_merge($cache_tags, $result['cache_tags']);
		}
		return $result['sql'];
	}
1366454
public function query(array $where, array $options = []) {
        $options += [
            'order' => $this->getDefaultOrder(),
            'limit' => $this->getDefaultLimit(),
            Db::OPTION_FETCH_MODE => $this->getFetchArgs()
        ];

        $stmt = $this->db->get($this->name, $where, $options);
        return $stmt;
    }
185258
public function set($cache_id, $data, $expire = null, $tags = []) {
		$result = $this->object->set($cache_id, $data, $expire, $tags);
		// if we are debugging
		if (\Debug::$debug) {
			\Debug::$data['cache'][] = array(
				'type' => 'set',
				'link' => $this->object->cache_link,
				'cache_id' => $cache_id,
				'have_data' => $result['success']
			);
			// todo: log errors
		}
		return $result;
	}
144145
function _Triggers($tabname,$tableoptions)
	{
		if (!$this->seqField) return array();

		if ($this->schema) {
			$t = strpos($tabname,'.');
			if ($t !== false) $tab = substr($tabname,$t+1);
			else $tab = $tabname;
			$seqname = $this->schema.'.'.$this->seqPrefix.$tab;
			$trigname = $this->schema.'.'.$this->trigPrefix.$this->seqPrefix.$tab;
		} else {
			$seqname = $this->seqPrefix.$tabname;
			$trigname = $this->trigPrefix.$seqname;
		}

		if (strlen($seqname) > 30) {
			$seqname = $this->seqPrefix.uniqid('');
		} // end if
		if (strlen($trigname) > 30) {
			$trigname = $this->trigPrefix.uniqid('');
		} // end if

		if (isset($tableoptions['REPLACE'])) $sql[] = "DROP SEQUENCE $seqname";
		$seqCache = '';
		if (isset($tableoptions['SEQUENCE_CACHE'])){$seqCache = $tableoptions['SEQUENCE_CACHE'];}
		$seqIncr = '';
		if (isset($tableoptions['SEQUENCE_INCREMENT'])){$seqIncr = ' INCREMENT BY '.$tableoptions['SEQUENCE_INCREMENT'];}
		$seqStart = '';
		if (isset($tableoptions['SEQUENCE_START'])){$seqIncr = ' START WITH '.$tableoptions['SEQUENCE_START'];}
		$sql[] = "CREATE SEQUENCE $seqname $seqStart $seqIncr $seqCache";
		$sql[] = "CREATE OR REPLACE TRIGGER $trigname BEFORE insert ON $tabname FOR EACH ROW WHEN (NEW.$this->seqField IS NULL OR NEW.$this->seqField = 0) BEGIN select $seqname.nextval into :new.$this->seqField from dual; END;";

		$this->seqField = false;
		return $sql;
	}
1222025
public static function getAllRecords($options = [])
    {
        $options = Util::prepareOptions($options, [
            'indexField' => false,
            'order' => false,
            'limit' => false,
            'calcFoundRows' => false,
            'offset' => 0,
        ]);

        $query = 'SELECT '.($options['calcFoundRows'] ? 'SQL_CALC_FOUND_ROWS' : '').'* FROM `%s`';
        $params = [
            static::$tableName,
        ];

        if ($options['order']) {
            $query .= ' ORDER BY ' . join(',', static::_mapFieldOrder($options['order']));
        }

        if ($options['limit']) {
            $query .= sprintf(' LIMIT %u,%u', $options['offset'], $options['limit']);
        }

        if ($options['indexField']) {
            return DB::table(static::_cn($options['indexField']), $query, $params, null, [static::class,'handleError']);
        } else {
            return DB::allRecords($query, $params, [static::class,'handleError']);
        }
    }
1347040
protected function getTagsFromMySQL()
    {
        $queryParts = $this->getQueryParts();

        $queryBuilder = self::getQueryBuilder('tx_kesearch_index');
        $queryBuilder->getRestrictions()->removeAll();

        $tagRows = $queryBuilder
            ->select('tags')
            ->from($queryParts['FROM'])
            ->add('where', $queryParts['WHERE'])
            ->execute()
            ->fetchAll();

        return array_map(
            function ($row) {
                return $row['tags'];
            },
            $tagRows
        );
    }
683582
public function clear($cache_id, $options = array())
    {
        $result = null;
        $options += array('pattern' => '.cache');
        $this->hook->attach('cache.clear.before', $cache_id, $options, $result, $this);

        if (isset($result)) {
            return $result;
        }

        $result = true;

        if ($cache_id === null) {
            array_map('unlink', glob(GC_DIR_CACHE . '/*.cache'));
            gplcart_static_clear();
        } else {

            if (is_array($cache_id)) {
                $cache_id = gplcart_array_hash($cache_id);
            }

            array_map('unlink', glob(GC_DIR_CACHE . "/$cache_id{$options['pattern']}"));
            gplcart_static_clear($cache_id);
        }

        $this->hook->attach('cache.clear.after', $cache_id, $options, $result, $this);
        return (bool) $result;
    }
681252
public function execute(Session $session, $sql, array $options = [])
    {
        $options += [
            'parameters' => [],
            'types' => [],
            'transactionContext' => null
        ];

        $parameters = $this->pluck('parameters', $options);
        $types = $this->pluck('types', $options);
        $options += $this->mapper->formatParamsForExecuteSql($parameters, $types);

        $context = $this->pluck('transactionContext', $options);

        $call = function ($resumeToken = null) use ($session, $sql, $options) {
            if ($resumeToken) {
                $options['resumeToken'] = $resumeToken;
            }

            return $this->connection->executeStreamingSql([
                'sql' => $sql,
                'session' => $session->name(),
                'database' => $session->info()['database']
            ] + $options);
        };

        return new Result($this, $session, $call, $context, $this->mapper);
    }
5529
public function buildSelectSql($options=array()) {
        if(isset($options['page'])) {
            // 根据页数计算limit
            list($page,$listRows)   =   $options['page'];
            $page    =  $page>0 ? $page : 1;
            $listRows=  $listRows>0 ? $listRows : (is_numeric($options['limit'])?$options['limit']:20);
            $offset  =  $listRows*($page-1);
            $options['limit'] =  $offset.','.$listRows;
        }
        $sql  =   $this->parseSql($this->selectSql,$options);
        return $sql;
    }
229298
public static function select(
        string $content, 
        array $attributes = [],
        array $options = []
    ) : string
    {
        foreach ($options as $key => $val) {
            $content .= $this->option($key, ["value" => $val]);
        }
        return self::tag("select", $content, $attributes);
    }
754989
public function query($sql, $options = [])
    {
        $resultMode = isset($options[self::RESULT_MODE_INDEX]) ? (int) $options[self::RESULT_MODE_INDEX] : MYSQLI_STORE_RESULT;
        /**
         * the RETURN_MODE_INDEX should contain one of the following constants http://php.net/manual/en/mysqli-result.fetch-all.php
         */
        $returnMode = isset($options[self::RESULT_RETURN_MODE_INDEX]) ? (int) $options[self::RESULT_RETURN_MODE_INDEX] : MYSQLI_BOTH;
        try {
            /**
             * @var \mysqli_result $result
             */
            $result = $this->getResource()->query($sql, $resultMode);
            switch($options[self::RESULT_TYPE_INDEX])
            {
                case self::RESULT_TYPE_GENERATOR:
                    return $this->rowGenerator($result, $returnMode);
                    break;

                case self::RESULT_TYPE_NUM_ARRAY:
                case self::RESULT_TYPE_ASSOC_ARRAY;
                    return $result->fetch_all($returnMode);
                    break;

                case self::RESULT_TYPE_ITERATOR:
                    return new \ArrayIterator($result->fetch_all($returnMode));
                    break;

                case self::RESULT_TYPE_OBJECT_ARRAY:
                    $gen = $this->rowGenerator($result, $returnMode);
                    $result = [];
                    foreach ($gen as $row) {
                        $result[] = $row;
                    }
                    return $result;

                default:
                    return $this->getResult()->fetch_all();
                    break;
            }
        } catch (\mysqli_sql_exception $e) {
            return false;
        }
    }
1006863
public function get_select_sql( $tables, $where = null, $fields = null, $limit = null, $offset = null, $order_by = null, $group_by = null, $for_update = false ) {
		$as = null;
		if ( is_array( $tables ) ) {
			if ( empty( $tables ) ) {
				return false;
			}
			$table = array_shift( $tables );
			$join  = $tables;
			if ( count( $table ) > 1 ) {
				$as = $table[1];
			}
			$table = $table[0];
		} else {
			$table = $tables;
			$join  = null;
		}
		if ( ! isset( $this->table_defines[ $table ] ) ) {
			return false;
		}

		$columns = $this->table_defines[ $table ]['columns'];

		! is_array( $where ) and $where = [];
		if ( $this->is_logical( $this->table_defines[ $table ] ) ) {
			$where['deleted_at'] = null;
		}

		list( $conditions, $values ) = $this->build_conditions( $where, $columns );
		$table  = $this->get_table( $table );
		$fields = $this->build_fields( $fields, $columns );
		$sql    = "SELECT {$fields} FROM $table";
		if ( isset( $as ) ) {
			$sql .= " AS $as";
		}
		$sql .= $this->build_join( $join );
		if ( ! empty( $conditions ) ) {
			$sql .= " WHERE $conditions";
		}
		$sql .= $this->build_group_by( $group_by, $columns );
		$sql .= $this->build_order_by( $order_by, $columns );
		$sql .= $this->build_limit( $limit, $offset );
		if ( $for_update ) {
			$sql .= ' FOR UPDATE';
		}

		return $this->prepare( $sql, $values );
	}
456749
public static function Delete ($table_name, array $values = [], array $options = []) {
		return static::GetConnection($options)->delete($table_name, $values, $options);
	}
299394
public function getCache(array $options) {
    array_multisort($options);
    $search = serialize($options);

    $local_cache = &drupal_static('groupex_form_cache_static');
    if (!isset($local_cache[$search])) {
      $result = $this->queryFactory->get(self::ENTITY_TYPE)
        ->condition('field_gfc_options', $search)
        ->condition('field_gfc_created', REQUEST_TIME - $this->config->get('cache_max_age'), '>')
        ->execute();

      $local_cache[$search] = FALSE;
      if (!empty($result)) {
        $id = reset($result);
        $cache = GroupexFormCache::load($id);
        $local_cache[$search] = unserialize($cache->field_gfc_response->value);
      }
    }

    return $local_cache[$search];
  }
490490
public function Query($Sql, $InputParameters = NULL, $Options = array()) {
      if ($Sql == '')
         trigger_error(ErrorMessage('Database was queried with an empty string.', $this->ClassName, 'Query'), E_USER_ERROR);

      // Get the return type.
      if (isset($Options['ReturnType']))
         $ReturnType = $Options['ReturnType'];
      elseif (preg_match('/^\s*"?(insert)\s+/i', $Sql))
         $ReturnType = 'ID';
      elseif (!preg_match('/^\s*"?(update|delete|replace|create|drop|load data|copy|alter|grant|revoke|lock|unlock)\s+/i', $Sql))
         $ReturnType = 'DataSet';
      else
         $ReturnType = NULL;

		if (isset($Options['Cache'])) {
         // Check to see if the query is cached.
         $CacheKeys = (array)GetValue('Cache',$Options,NULL);
         $CacheOperation = GetValue('CacheOperation',$Options,NULL);
         if (is_null($CacheOperation)) {
            switch ($ReturnType) {
               case 'DataSet':
                  $CacheOperation = 'get';
                  break;
               case 'ID':
               case NULL:
                  $CacheOperation = 'remove';
                  break;
            }
         }
         
         switch ($CacheOperation) {
            case 'get':
               foreach ($CacheKeys as $CacheKey) {
                  $Data = Gdn::Cache()->Get($CacheKey);
               }

               // Cache hit. Return.
               if ($Data !== Gdn_Cache::CACHEOP_FAILURE)
                  return new Gdn_DataSet($Data);
               
               // Cache miss. Save later.
               $StoreCacheKey = $CacheKey;
               break;
            
            case 'increment':
            case 'decrement':
               $CacheMethod = ucfirst($CacheOperation);
               foreach ($CacheKeys as $CacheKey) {
                  $CacheResult = Gdn::Cache()->$CacheMethod($CacheKey);
               }
               break;
            
            case 'remove':
               foreach ($CacheKeys as $CacheKey) {
                  $Res = Gdn::Cache()->Remove($CacheKey);
               }
               break;
         }
		}

      // Run the Query
      if (!is_null($InputParameters) && count($InputParameters) > 0) {
         // Make sure other unbufferred queries are not open
         if (is_object($this->_CurrentResultSet)) {
            $this->_CurrentResultSet->Result();
            $this->_CurrentResultSet->FreePDOStatement(FALSE);
         }

         $PDOStatement = $this->Connection()->prepare($Sql);

         if (!is_object($PDOStatement)) {
            trigger_error(ErrorMessage('PDO Statement failed to prepare', $this->ClassName, 'Query', $this->GetPDOErrorMessage($this->Connection()->errorInfo())), E_USER_ERROR);
         } else if ($PDOStatement->execute($InputParameters) === FALSE) {
            trigger_error(ErrorMessage($this->GetPDOErrorMessage($PDOStatement->errorInfo()), $this->ClassName, 'Query', $Sql), E_USER_ERROR);
         }
      } else {
         $PDOStatement = $this->Connection()->query($Sql);
      }

      if ($PDOStatement === FALSE) {
         trigger_error(ErrorMessage($this->GetPDOErrorMessage($this->Connection()->errorInfo()), $this->ClassName, 'Query', $Sql), E_USER_ERROR);
      }
      
      // Did this query modify data in any way?
      if ($ReturnType == 'ID') {
         $this->_CurrentResultSet = $this->Connection()->lastInsertId();
      } else {
         if ($ReturnType == 'DataSet') {
            // Create a DataSet to manage the resultset
            $this->_CurrentResultSet = new Gdn_DataSet();
            $this->_CurrentResultSet->Connection = $this->Connection();
            $this->_CurrentResultSet->PDOStatement($PDOStatement);
         }
      }
      
      if (isset($StoreCacheKey)) {
         if ($CacheOperation == 'get')
            Gdn::Cache()->Store(
               $StoreCacheKey, 
               (($this->_CurrentResultSet instanceof Gdn_DataSet) ? $this->_CurrentResultSet->ResultArray() : $this->_CurrentResultSet),
               GetValue('CacheOptions', $Options, array())
               );
      }
      
      return $this->_CurrentResultSet;
   }
590568
private function buildTableOptions(array $options)
    {
        if (isset($options['table_options'])) {
            return $options['table_options'];
        }

        $tableOptions = [];

        // Collate
        if (! isset($options['collate'])) {
            $options['collate'] = 'utf8_unicode_ci';
        }

        $tableOptions[] = sprintf('COLLATE %s', $options['collate']);

        // Engine
        if (! isset($options['engine'])) {
            $options['engine'] = 'InnoDB';
        }

        $tableOptions[] = sprintf('ENGINE = %s', $options['engine']);

        // Auto increment
        if (isset($options['auto_increment'])) {
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
        }

        // Comment
        if (isset($options['comment'])) {
            $comment = trim($options['comment'], " '");

            $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($comment));
        }

        // Row format
        if (isset($options['row_format'])) {
            $tableOptions[] = sprintf('ROW_FORMAT = %s', $options['row_format']);
        }

        return implode(' ', $tableOptions);
    }
1222586
public function select($options = [])
    {
        $sql = str_replace(
            ['%TABLE%', '%DISTINCT%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'],
            [
                $this->parseTable($options['table'], $options),
                $this->parseDistinct($options['distinct']),
                $this->parseField($options['field'], $options),
                $this->parseJoin($options['join'], $options),
                $this->parseWhere($options['where'], $options),
                $this->parseGroup($options['group']),
                $this->parseHaving($options['having']),
                $this->parseOrder($options['order'], $options),
                $this->parseLimit($options['limit']),
                $this->parseUnion($options['union']),
                $this->parseLock($options['lock']),
                $this->parseComment($options['comment']),
                $this->parseForce($options['force']),
            ], $this->selectSql);
        return $sql;
    }