使用 CQL 来构造查询。CQL 语法参考 `这里 <https://cn.avoscloud.com/docs/cql_guide.html>`_。

        :param cql: CQL 语句
        :param pvalues: 查询参数
        :rtype: CQLResult
495914
def do_cloud_query(cls, cql, *pvalues):
        
        params = {'cql': cql}
        if len(pvalues) == 1 and isinstance(pvalues[0], (tuple, list)):
            pvalues = json.dumps(pvalues[0])
        if len(pvalues) > 0:
            params['pvalues'] = json.dumps(pvalues)

        content = client.get('/cloudQuery', params).json()

        objs = []
        query = cls(content['className'])
        for result in content['results']:
            obj = query._new_object()
            obj._update_data(query._process_result(result))
            objs.append(obj)

        return CQLResult(objs, content.get('count'), content.get('className'))
575667
def prepare_cql3_query(self, query, compression):
    
    self._seqid += 1
    d = self._reqs[self._seqid] = defer.Deferred()
    self.send_prepare_cql3_query(query, compression)
    return d
212349
def values(self, *args: str, **kwargs: str) -> "ValuesQuery":
        
        fields_for_select = {}  # type: Dict[str, str]
        for field in args:
            if field in fields_for_select:
                raise FieldError("Duplicate key {}".format(field))
            fields_for_select[field] = field

        for return_as, field in kwargs.items():
            if return_as in fields_for_select:
                raise FieldError("Duplicate key {}".format(return_as))
            fields_for_select[return_as] = field

        return ValuesQuery(
            db=self._db,
            model=self.model,
            q_objects=self._q_objects,
            fields_for_select=fields_for_select,
            distinct=self._distinct,
            limit=self._limit,
            offset=self._offset,
            orderings=self._orderings,
            annotations=self._annotations,
            custom_filters=self._custom_filters,
        )
685918
def execute_cql_query(self, query, compression):
    
    self._seqid += 1
    d = self._reqs[self._seqid] = defer.Deferred()
    self.send_execute_cql_query(query, compression)
    return d
266161
def _gql(cls, query_string, *args, **kwds):
    """"""
    from .query import gql  # Import late to avoid circular imports.
    return gql('SELECT * FROM %s %s' % (cls._class_name(), query_string),
               *args, **kwds)
590717
def is_cql_compatible(self):
        
        if self.virtual:
            return False
        comparator = getattr(self, 'comparator', None)
        if comparator:
            # no compact storage with more than one column beyond PK if there
            # are clustering columns
            incompatible = (self.is_compact_storage and
                            len(self.columns) > len(self.primary_key) + 1 and
                            len(self.clustering_key) >= 1)

            return not incompatible
        return True
666652
public List executeScalarQuery(String cqlQuery) {
        CqlResult cqlResult = null;
        List results = new ArrayList();
        try {
            if (log.isDebugEnabled()) {
                log.debug("Executing query {}.", cqlQuery);
            }
            cqlResult = (CqlResult) executeCQLQuery(cqlQuery, true);

            if (cqlResult != null && (cqlResult.getRows() != null || cqlResult.getRowsSize() > 0)) {
                results = new ArrayList<Object>(cqlResult.getRowsSize());
                Iterator<CqlRow> iter = cqlResult.getRowsIterator();
                while (iter.hasNext()) {
                    Map<String, Object> entity = new HashMap<String, Object>();

                    CqlRow row = iter.next();
                    for (Column column : row.getColumns()) {
                        if (column != null) {
                            String thriftColumnName =
                                PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());

                            if (column.getValue() == null) {
                                entity.put(thriftColumnName, null);
                            } else {
                                entity.put(thriftColumnName,
                                    composeColumnValue(cqlResult.getSchema(), column.getValue(), column.getName()));
                            }
                        }
                    }
                    results.add(entity);
                }
            }
        } catch (Exception e) {
            log.error("Error while executing native CQL query Caused by {}.", e);
            throw new PersistenceException(e);
        }
        return results;
    }
990766
def query(self, query):
    '''
    '''
    self.logger.info('%s: query %s' % (self, query))
    return super(LoggingDatastore, self).query(query)
1155799
private boolean isQueryConvertibleToCQL(KunderaQuery kunderaQuery) {
        EntityMetadata m = kunderaQuery.getEntityMetadata();
        if (kunderaQuery.isUpdateClause() && m.isCounterColumnType())
            return false;

        List<String> opsNotAllowed = Arrays.asList(new String[] { ">", "<", ">=", "<=" });
        boolean result = false;
        if (!kunderaQuery.getFilterClauseQueue().isEmpty()) {
            String idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();
            for (Object o : kunderaQuery.getFilterClauseQueue()) {
                if (o instanceof FilterClause) {
                    FilterClause filterClause = (FilterClause) o;
                    if (!idColumn.equals(filterClause.getProperty())
                        || opsNotAllowed.contains(filterClause.getCondition())) {
                        result = false;
                        break;
                    }
                    result = true;
                }
            }
        }
        return result;
    }
664589
private int preparedStatement(Cassandra.Client client)
        {
            Integer itemId = preparedStatements.get(client);
            if (itemId == null)
            {
                CqlPreparedResult result;
                try
                {
                    result = client.prepare_cql3_query(ByteBufferUtil.bytes(cql), Compression.NONE);
                }
                catch (InvalidRequestException e)
                {
                    throw new RuntimeException("failed to prepare cql query " + cql, e);
                }
                catch (TException e)
                {
                    throw new RuntimeException("failed to prepare cql query " + cql, e);
                }

                Integer previousId = preparedStatements.putIfAbsent(client, Integer.valueOf(result.itemId));
                itemId = previousId == null ? result.itemId : previousId;
            }
            return itemId;
        }
268358
def create_aql_text(*args):
        
        aql_query_text = ""
        for arg in args:
            if isinstance(arg, dict):
                arg = "({})".format(json.dumps(arg))
            elif isinstance(arg, list):
                arg = "({})".format(json.dumps(arg)).replace("[", "").replace("]", "")
            aql_query_text += arg
        return aql_query_text
479777
def build_update_cql_and_params
      assignment_str, update_params = build_update_and_params
      where_str, where_params = build_where_and_params
      condition_str, condition_params = build_condition_and_params

      @cql = %(
        UPDATE #{table}
        SET #{assignment_str}
        #{where_str}
        #{condition_str}
      ).squish + ";"

      @params = update_params + where_params + condition_params
    end
295955
def queryMany(self, query, args):
		
		self.lastError = None
		self.affectedRows = None
		self.rowcount = None
		self.record = None
		cursor = None
		
		try:
			try:
				self._GetConnection()
				self.conn.query = query
				#Execute query and store results
				cursor = self.conn.getCursor()
				self.affectedRows = cursor.executemany(query, args)
				self.conn.updateCheckTime()
			except Exception, e:
				self.lastError = e
		finally:
			if cursor is not None:
				cursor.close()
			self._ReturnConnection()
			if self.lastError is not None:
				raise self.lastError
			else:
				return self.affectedRows
23565
@NonNull
  public static CqlIdentifier fromCql(@NonNull String cql) {
    Preconditions.checkNotNull(cql, "cql must not be null");
    final String internal;
    if (Strings.isDoubleQuoted(cql)) {
      internal = Strings.unDoubleQuote(cql);
    } else {
      internal = cql.toLowerCase();
      Preconditions.checkArgument(
          !Strings.needsDoubleQuotes(internal), "Invalid CQL form [%s]: needs double quotes", cql);
    }
    return fromInternal(internal);
  }
1126680
@Override
    public List executeQuery(Class clazz, List<String> relationalField, boolean isNative, String cqlQuery)
    {
        if (clazz == null)
        {
            return super.executeScalarQuery(cqlQuery);
        }
        return super.executeSelectQuery(clazz, relationalField, dataHandler, isNative, cqlQuery);
    }
484540
def sparql_query(self, query, flush=None, limit=None):
        
        return self.find_statements(query, language='sparql', type='tuples',
            flush=flush, limit=limit)
1193343
def query(params=None):
    '''
    
    '''
    path = 'https://api.qingcloud.com/iaas/'

    access_key_id = config.get_cloud_config_value(
        'access_key_id', get_configured_provider(), __opts__, search_global=False
    )
    access_key_secret = config.get_cloud_config_value(
        'secret_access_key', get_configured_provider(), __opts__, search_global=False
    )

    # public interface parameters
    real_parameters = {
        'access_key_id': access_key_id,
        'signature_version': DEFAULT_QINGCLOUD_SIGNATURE_VERSION,
        'time_stamp': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
        'version': DEFAULT_QINGCLOUD_API_VERSION,
    }

    # include action or function parameters
    if params:
        for key, value in params.items():
            if isinstance(value, list):
                for i in range(1, len(value) + 1):
                    if isinstance(value[i - 1], dict):
                        for sk, sv in value[i - 1].items():
                            if isinstance(sv, dict) or isinstance(sv, list):
                                sv = salt.utils.json.dumps(sv, separators=(',', ':'))
                            real_parameters['{0}.{1}.{2}'.format(key, i, sk)] = sv
                    else:
                        real_parameters['{0}.{1}'.format(key, i)] = value[i - 1]
            else:
                real_parameters[key] = value

    # Calculate the string for Signature
    signature = _compute_signature(real_parameters, access_key_secret, 'GET', '/iaas/')
    real_parameters['signature'] = signature

    # print('parameters:')
    # pprint.pprint(real_parameters)

    request = requests.get(path, params=real_parameters, verify=False)

    # print('url:')
    # print(request.url)

    if request.status_code != 200:
        raise SaltCloudSystemExit(
            'An error occurred while querying QingCloud. HTTP Code: {0}  '
            'Error: \'{1}\''.format(
                request.status_code,
                request.text
            )
        )

    log.debug(request.url)

    content = request.text
    result = salt.utils.json.loads(content)

    # print('response:')
    # pprint.pprint(result)

    if result['ret_code'] != 0:
        raise SaltCloudSystemExit(
            pprint.pformat(result.get('message', {}))
        )

    return result