The DQL query that will construct this table's schema
351040
def schema(self):
        
        attrs = self.attrs.copy()
        parts = ["CREATE", "TABLE", self.name, "(%s," % self.hash_key.schema]
        del attrs[self.hash_key.name]
        if self.range_key:
            parts.append(self.range_key.schema + ",")
            del attrs[self.range_key.name]
        if attrs:
            attr_def = ", ".join([attr.schema for attr in itervalues(attrs)])
            parts.append(attr_def + ",")

        parts.append(
            "THROUGHPUT (%d, %d))" % (self.read_throughput, self.write_throughput)
        )
        parts.extend([g.schema for g in itervalues(self.global_indexes)])
        return " ".join(parts) + ";"
1088766
protected function createObjectStateFindQuery()
    {
        $query = $this->dbHandler->createSelectQuery();
        $query->select(
            // Object state
            $this->dbHandler->aliasedColumn($query, 'default_language_id', 'ezcobj_state'),
            $this->dbHandler->aliasedColumn($query, 'group_id', 'ezcobj_state'),
            $this->dbHandler->aliasedColumn($query, 'id', 'ezcobj_state'),
            $this->dbHandler->aliasedColumn($query, 'identifier', 'ezcobj_state'),
            $this->dbHandler->aliasedColumn($query, 'language_mask', 'ezcobj_state'),
            $this->dbHandler->aliasedColumn($query, 'priority', 'ezcobj_state'),
            // Object state language
            $this->dbHandler->aliasedColumn($query, 'description', 'ezcobj_state_language'),
            $this->dbHandler->aliasedColumn($query, 'language_id', 'ezcobj_state_language'),
            $this->dbHandler->aliasedColumn($query, 'name', 'ezcobj_state_language')
        )->from(
            $this->dbHandler->quoteTable('ezcobj_state')
        )->innerJoin(
            $this->dbHandler->quoteTable('ezcobj_state_language'),
            $query->expr->eq(
                $this->dbHandler->quoteColumn('id', 'ezcobj_state'),
                $this->dbHandler->quoteColumn('contentobject_state_id', 'ezcobj_state_language')
            )
        );

        return $query;
    }
135096
final protected function build_query(){
        $select = empty($this->_select) ? $this->default_select() : implode(', ', $this->_select);
        $calc = $this->_calc_rows ? ' SQL_CALC_FOUND_ROWS' : '';
        $distinct = $this->_distinct ? sprintf('DISTINCT(%s)', $this->escape_column_name($this->_distinct)) : '';
        $from = empty($this->_from) ? $this->table : $this->_from;
        // Build query
        $sql = <<<SQL
          SELECT{$calc} {$distinct} {$select} FROM {$from}
SQL;
        // Add join
        $join = [];
        if( !empty($this->_join) ){
            $join = $this->_join;
        }else{
            $default_join = $this->default_join();
            if( !empty($default_join) ){
                $join = $default_join;
            }
        }
        foreach($join as list($table, $on, $method)){
            $method = 'INNER' === strtoupper($method) ? 'INNER' : 'LEFT';
            $sql .= <<<SQL
            {$method} JOIN {$table}
            ON {$on}
SQL;
        }
        // Add where
        if( !empty($this->_wheres) ){
            $where_clause = $this->build_where($this->_wheres);
            $sql .= <<<SQL
            WHERE {$where_clause}
SQL;
        }
        // Add group by
        if( !empty($this->_group_by) ){
            $group_by = implode(', ', $this->_group_by);
            $sql .= <<<SQL
            GROUP BY {$group_by}
SQL;
        }
        // Add order by
        if( !empty($this->_order_by) ){
            $order_by = implode(', ', $this->_order_by);
            $sql .= <<<SQL
            ORDER BY {$order_by}
SQL;
        }
        // Add limit
        if( !empty($this->_limit) ){
            list($per_page, $offset) = $this->_limit;
            $limit = <<<SQL
            LIMIT %d, %d
SQL;
            $sql .= sprintf($limit, $offset, $per_page);
        }
        return $sql;
    }
1256079
protected function buildSelect()
	{
		//define a container fields array
		$fields = array();

		//
		$where = $order = $limit = $join ="";

		//
		$template = "SELECT %s %s FROM %s %s %s %s %s";

		//loop through the fields
		foreach ($this->fields as $table => $tableFields) 
		{
			//loop through the fields checking for aliases
			foreach ($tableFields as $field => $alias) 
			{
				//if field is string, return field name
				if ( is_string($field) && $field != 'COUNT(1)')
				{
					//add to fields array
					$fields[] = "{$table}.{$field} AS {$alias}";

				}
				elseif (is_string($field) && $field == 'COUNT(1)') 
				{
					//add to fields array
					$fields[] = "{$field} AS {$alias}";

				}
				//not an array, return alias
				else
				{
					//get alias as field name
					$fields[] = "{$table}.{$alias}";

				}

			}

		}

		//turn the fields into a string
		$fields = join(", ", $fields);

		//get the query joins
		$queryJoin = $this->joins;

		//check if the join parameter is empty
		if ( ! empty($queryJoin) ) 
		{
			$joinTables = "(" . join(", ", $queryJoin['tables']) . ")";
			$joinConditions = "(" . join(" AND ", $queryJoin['conditions']) . ")";
			//add the joins
			$join = " LEFT JOIN $joinTables ON $joinConditions";

		}

		//get the where clause
		$queryWhere = $this->wheres;

		//check if the wheres clause is empty
		if ( ! empty($queryWhere) ) 
		{
			//append where clause
			$joined = join(" AND ", $queryWhere);

			//assign string to $where var
			$where = "WHERE {$joined}";

		}

		//get the order clause
		$queryOrder = $this->orders;

		//check if the orders clause is empty
		if ( ! empty($queryOrder) ) 
		{
			//get the direction if order
			$orderDirection = $this->directions;

			//assign string to order variable
			$order = "ORDER BY {$queryOrder} {$orderDirection}";

		}

		//get the limits clause
		$queryLimit = $this->limits;

		//check if the limits clause is empty
		if ( ! empty($queryLimit) ) 
		{
			//get the offset
			$limitOffset = $this->offset;

			//if offset has been defined
			if ( $limitOffset ) 
			{
				//get the limit string with offset
				$limit = "LIMIT {$limitOffset}, {$queryLimit}";

			}
			//limit offset undefined
			else
			{
				//get the limit string
				$limit = "LIMIT {$queryLimit}";

			}

		}

		//return the formated query string in the format of $template
		return sprintf($template, $this->distinct, $fields, $this->froms, $join, $where, $order, $limit);

	}
1147496
private function getCreateQueryFromSchema(GetSchema\Schema $schema)
    {
        $definition = $schema->getTableDefinition($this->fromExpr);
        $defSchema = $definition->getSchema();
        $parser = new PHPSQLParser(false, false, [Options::CONSISTENT_SUB_TREES => true]);
        $query = new CreateQuery(new Query($defSchema, $parser->parse($defSchema)));

        return $query->getObjectExpression();
    }
866964
function schema($table,$fields=NULL,$ttl=0) {
		$fw=\Base::instance();
		$cache=\Cache::instance();
		if ($fw->CACHE && $ttl &&
			($cached=$cache->exists(
				$hash=$fw->hash($this->dsn.$table).'.schema',$result)) &&
			$cached[0]+$ttl>microtime(TRUE))
			return $result;
		if (strpos($table,'.'))
			list($schema,$table)=explode('.',$table);
		// Supported engines
		$cmd=[
			'sqlite2?'=>[
				'PRAGMA table_info(`'.$table.'`)',
				'name','type','dflt_value','notnull',0,'pk',TRUE],
			'mysql'=>[
				'SHOW columns FROM `'.$this->dbname.'`.`'.$table.'`',
				'Field','Type','Default','Null','YES','Key','PRI'],
			'mssql|sqlsrv|sybase|dblib|pgsql|odbc'=>[
				'SELECT '.
					'C.COLUMN_NAME AS field,'.
					'C.DATA_TYPE AS type,'.
					'C.COLUMN_DEFAULT AS defval,'.
					'C.IS_NULLABLE AS nullable,'.
					'T.CONSTRAINT_TYPE AS pkey '.
				'FROM INFORMATION_SCHEMA.COLUMNS AS C '.
				'LEFT OUTER JOIN '.
					'INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K '.
					'ON '.
						'C.TABLE_NAME=K.TABLE_NAME AND '.
						'C.COLUMN_NAME=K.COLUMN_NAME AND '.
						'C.TABLE_SCHEMA=K.TABLE_SCHEMA '.
						($this->dbname?
							('AND C.TABLE_CATALOG=K.TABLE_CATALOG '):'').
				'LEFT OUTER JOIN '.
					'INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS T ON '.
						'K.TABLE_NAME=T.TABLE_NAME AND '.
						'K.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND '.
						'K.TABLE_SCHEMA=T.TABLE_SCHEMA '.
						($this->dbname?
							('AND K.TABLE_CATALOG=T.TABLE_CATALOG '):'').
				'WHERE '.
					'C.TABLE_NAME='.$this->quote($table).
					($this->dbname?
						(' AND C.TABLE_CATALOG='.
							$this->quote($this->dbname)):''),
				'field','type','defval','nullable','YES','pkey','PRIMARY KEY'],
			'oci'=>[
				'SELECT c.column_name AS field, '.
					'c.data_type AS type, '.
					'c.data_default AS defval, '.
					'c.nullable AS nullable, '.
					'(SELECT t.constraint_type '.
						'FROM all_cons_columns acc '.
						'LEFT OUTER JOIN all_constraints t '.
						'ON acc.constraint_name=t.constraint_name '.
						'WHERE acc.table_name='.$this->quote($table).' '.
						'AND acc.column_name=c.column_name '.
						'AND constraint_type='.$this->quote('P').') AS pkey '.
				'FROM all_tab_cols c '.
				'WHERE c.table_name='.$this->quote($table),
				'FIELD','TYPE','DEFVAL','NULLABLE','Y','PKEY','P']
		];
		if (is_string($fields))
			$fields=\Base::instance()->split($fields);
		$conv=[
			'int\b|integer'=>\PDO::PARAM_INT,
			'bool'=>\PDO::PARAM_BOOL,
			'blob|bytea|image|binary'=>\PDO::PARAM_LOB,
			'float|real|double|decimal|numeric'=>self::PARAM_FLOAT,
			'.+'=>\PDO::PARAM_STR
		];
		foreach ($cmd as $key=>$val)
			if (preg_match('/'.$key.'/',$this->engine)) {
				$rows=[];
				foreach ($this->exec($val[0],NULL) as $row)
					if (!$fields || in_array($row[$val[1]],$fields)) {
						foreach ($conv as $regex=>$type)
							if (preg_match('/'.$regex.'/i',$row[$val[2]]))
								break;
						$rows[$row[$val[1]]]=[
							'type'=>$row[$val[2]],
							'pdo_type'=>$type,
							'default'=>is_string($row[$val[3]])?
								preg_replace('/^\s*([\'"])(.*)\1\s*/','\2',
								$row[$val[3]]):$row[$val[3]],
							'nullable'=>$row[$val[4]]==$val[5],
							'pkey'=>$row[$val[6]]==$val[7]
						];
					}
				if ($fw->CACHE && $ttl)
					// Save to cache backend
					$cache->set($hash,$rows,$ttl);
				return $rows;
			}
		user_error(sprintf(self::E_PKey,$table),E_USER_ERROR);
		return FALSE;
	}
855190
public function buildQuery() 
    {
        $qb = $this->dataGrid->getQueryBuilder();

        if (!$qb instanceof QueryBuilder){
            throw new \InvalidArgumentException('Value must be instance of Doctrine\ORM\QueryBuilder.');
        }
        
        $options = $this->getOptions();
        
        // Is dependant grid ?
        if ($this->dataGrid->isDependentGrid()) {
            $qb->setParameter('masterGridRowId', $options['masterGridRowId']);
        }
        
        // Orders the records
        if ($options['orderBy']) {
            $qb->addOrderBy($options['orderBy'], $options['sort']);
        }
        
        // Applying search filters
        if ($options['search'] && !empty($options['filters'])) {
            $this->applyFilters($qb, $options['filters']);
        }
        
        // dispatch should onQueryBuilderReady event here
        
        if (!$this->dataGrid->isSortableEnabled() && $options['page'] && $options['records']){
            $qb->setMaxResults($options['records']);
            $qb->setFirstResult(($options['page'] - 1) * $options['records']);
        }

        $this->setQuery($qb->getQuery());
        
        // Getting count
        $paginator = new Paginator($this->getQuery());
        //$paginator->setUseOutputWalkers(false);
        $this->setCount($paginator->count());
        
        return $this;
    }
1324264
public function build(AbstractQuery $query, Schema &$schema) {
		$from = '';
		
		//obtain table/alias from query
		$table = $query->getTable();
		$alias = $query->getAlias();
		
		if (isset($alias))
			$from .= '@@' . $table . ' ' . $alias . ' ';
		else
			$from .= '@@' . $table . ' ';
		
		//add joins
		$joins = $query->getJoins();
		foreach ($joins as $join)
			$from .= $this->translateJoin($join, $schema);
		
		return $from;
	}
385341
function makeQuery()
    {
        $query = array();
        foreach($this->query as $paramater) {
            $operator = ($paramater[1] != '=') ? $paramater[1] : '' ;
            $query[$paramater[0] . $operator] = $paramater[2];
        }
        return $query;
    }
144459
public function getSchema()
    {
        $schema = new Schema(['adapter' => $this->_adapter]);
        $tables = $this->getTables();
        foreach ($tables as $tableName) {
            $schema->addTable($this->getTable($tableName));
        }

        return $schema;
    }
51630
function generateAlterFieldSql( $table, $field_name, $changed_field, $params )
    {
        return $this->OtherSchema->generateAlterFieldSql( $table, $field_name, $changed_field, $params );
    }
1163533
public function createSQL()
	{
		try {

			$lines = array();

			$indices = array();

			$columns = $this->columns;

			$template = "CREATE TABLE %s (\n%s,\n%s\n) ENGINE=%s DEFAULT CHARSET=%s;";

			foreach ($this->columns as $column_name => $column)
			{

				//$column_name = $column["name"];//set the column name

				$data_type = $column["type"];//set the column data type

				$length = $column["length"];//set the lenght of the data type

				if ($column["primary"])	$indices[] = "PRIMARY KEY ({$column_name})"; //add primary key field

				if ($column["index"]) $indices[] = "KEY {$column_name} ({$column_name})"; //add index field

				switch ($data_type)
				{
					case "autonumber":

						$lines[] = "{$column_name} INT(11) NOT NULL AUTO_INCREMENT";

						break;

					case "text":

						if ($length !== null && $length <= 255)	$lines[] = "{$column_name} VARCHAR({$length}) DEFAULT NULL";

						else $lines[] = "{$column_name} text";

						break;

					case "integer":

						$lines[] = "{$column_name} INT(11) DEFAULT NULL";

						break;

					case "decimal":

						$lines[] = "{$column_name} FLOAT DEFAULT NULL";

						break;

					case "boolean":

						$lines[] = "{$column_name} TINYINT(4) DEFAULT NULL";

						break;

					case "datetime":

						$lines[] = "{$column_name} DATETIME DEFAULT NULL";

						break;

				}

			}

			$this->query_string = sprintf($template, $this->table, join(",\n", $lines), join(",\n", $indices), 'InnoDB', 'utf8');//$this->connection->character_set_name()
			
			return $this;

		} catch (MySQLException $e) {

			$e->errorShow();

		}
		
	}
840152
public function queryDQL ($dql, array $bound_parameters = array()) {
		$statement = $this -> entity_manager -> createQuery($dql);

		foreach ($bound_parameters as $parameter => $value) {
			$statement -> setParameter($parameter, $value);
		}

		return $statement -> getResult();
	}
857950
public function setDQL($dqlQuery)
    {
        if ($dqlQuery !== null) {
            $this->dql   = $dqlQuery;
            $this->state = self::STATE_DIRTY;
        }

        return $this;
    }
652307
public function getSchemaTables(): array
    {
        if (empty($this->db)) {
            return [];
        }
        $schemaTable = self::SCHEMA_TABLES;
        $where[]     = "TABLE_TYPE = 'BASE TABLE'";
        $where[]     = "TABLE_SCHEMA = '{$this->db}'";
        if (!empty($this->tablesEnabled)) {
            $tablesEnabled = array_map(function ($item) {
                return "'{$item}'";
            }, $this->tablesEnabled);
            $where[]       = 'TABLE_NAME IN (' . implode(',', $tablesEnabled) . ')';
        }
        if (!empty($this->tablesDisabled)) {
            $tablesDisabled = array_map(function ($item) {
                return "'{$item}'";
            }, $this->tablesDisabled);
            $where[]        = 'TABLE_NAME NOT IN (' . implode(',', $tablesDisabled) . ')';
        }
        $where = !empty($where) ? ' WHERE ' . implode(' AND ', $where) : null;

        $querySql = "SELECT `TABLE_NAME` AS `name`,`TABLE_COMMENT` as `comment` FROM {$schemaTable} {$where}";
        $this->dbHandler->prepare($querySql);
        $this->dbHandler->execute([]);
        $this->tables = $this->dbHandler->fetch();

        return !empty($this->tables) ? $this->tables : [];
    }
105506
public function makeQuery()
    {
        $data = $this->q;

        $params = array();
        $query = "SELECT ";

        if (isset($data['from']['columns'])) {
            foreach ($data['from']['columns'] as $key => $value) {
                $query .= "$value, ";
            }

            $query = substr($query, 0, -2);
        } else {
            $query .= "{$data['from']['table']}.* ";
        }

        // Join columns
        if (isset($data['join'])) {
            foreach ($data['join'] as $join) {
                if (isset($join['columns'])) {
                    foreach ($join['columns'] as $col) {
                        $query .= ", {$join['table']}.{$col}";
                    }
                } else {
                    $query .= ", {$join['table']}.*";
                }

            }
        }

        $query .= " FROM {$data['from']['table']}";

        // Join
        if (isset($data['join'])) {
            foreach ($data['join'] as $join) {
                $query .= " JOIN {$join['table']} ON {$join['conditions']}";

            }
        }

        if (isset($data['where'])) {
            $query .= " WHERE (";

            $iWhere = 0;
            foreach ($data['where'] as $key => $value) {
                if (!is_int($key)) {
                    $query .= "$key = :where$iWhere AND ";
                    $params[":where$iWhere"] = $value;
                    $iWhere++;
                } else {
                    $query .= "$value AND";
                }

            }

            $query = substr($query, 0, -4);

            $iWhereO = 0;
            if (isset($data['orwhere'])) {
                foreach ($data['orwhere'] as $key => $value) {
                    if (!is_int($key)) {
                        $query .= " OR $key = :whereO$iWhereO ";
                        $params[":whereO$iWhereO"] = $value;
                        $iWhereO++;
                    } else {
                        $query .= "OR $value ";
                    }
                }
            }
            $query .= ")";
        }

        if (isset($data['group'])) {
            $query .= " GROUP BY :group";
            $params[':group'] = $data['group'];
        }

        $iOrder = 0;
        if (isset($data['order'])) {
            $query .= " ORDER BY ";
            foreach ($data['order'] as $key => $value) {
                $query .= ":order$iOrder $value";
                $params[":order$iOrder"] = $key;
                $iOrder++;
            }
        }

        if (isset($data['limit'])) {
            $query .= " LIMIT :limit";
            $params[":limit"] = $data['limit']['limit'];
            if (isset($data['limit']['offset'])) {
                $query .= ", :offset";
                $params[":offset"] = $data['limit']['offset'];
            }
        }

        return ['query' => $query, 'params' => $params];
    }
64782
def _BuildQuery(self,
                  subject,
                  attribute=None,
                  timestamp=None,
                  limit=None,
                  is_prefix=False):
    """"""
    args = []
    subject = utils.SmartUnicode(subject)
    criteria = "WHERE aff4.subject_hash=unhex(md5(%s))"
    args.append(subject)
    sorting = ""
    tables = "FROM aff4"

    # Set fields, tables, and criteria and append args
    if attribute is not None:
      if is_prefix:
        tables += " JOIN attributes ON aff4.attribute_hash=attributes.hash"
        prefix = attribute + "%"
        criteria += " AND attributes.attribute like %s"
        args.append(prefix)
      else:
        criteria += " AND aff4.attribute_hash=unhex(md5(%s))"
        args.append(attribute)

    # Limit to time range if specified
    if isinstance(timestamp, (tuple, list)):
      criteria += " AND aff4.timestamp >= %s AND aff4.timestamp <= %s"
      args.append(int(timestamp[0]))
      args.append(int(timestamp[1]))

    fields = "aff4.value, aff4.timestamp"
    if is_prefix:
      fields += ", attributes.attribute"

    # Modify fields and sorting for timestamps.
    if timestamp is None or timestamp == self.NEWEST_TIMESTAMP:
      tables += (" JOIN (SELECT attribute_hash, MAX(timestamp) timestamp "
                 "%s %s GROUP BY attribute_hash) maxtime ON "
                 "aff4.attribute_hash=maxtime.attribute_hash AND "
                 "aff4.timestamp=maxtime.timestamp") % (tables, criteria)
      criteria = "WHERE aff4.subject_hash=unhex(md5(%s))"
      args.append(subject)
    else:
      # Always order results.
      sorting = "ORDER BY aff4.timestamp DESC"
    # Add limit if set.
    if limit:
      sorting += " LIMIT %s" % int(limit)

    query = " ".join(["SELECT", fields, tables, criteria, sorting])

    return (query, args)