Compile the lock into SQL

        :param query: A QueryBuilder instance
        :type query: QueryBuilder

        :param value: The lock value
        :type value: bool or str

        :return: The compiled lock
        :rtype: str
497017
def _compile_lock(self, query, value):
        
        if isinstance(value, basestring):
            return value

        if value is True:
            return 'FOR UPDATE'
        elif value is False:
            return 'LOCK IN SHARE MODE'
1245244
def _build_query(self, table, tree, visitor):
        
        kwargs = {}
        index = None
        if tree.using:
            index_name = kwargs["index"] = tree.using[1]
            index = table.get_index(index_name)
        if tree.where:
            constraints = ConstraintExpression.from_where(tree.where)
            possible_hash = constraints.possible_hash_fields()
            possible_range = constraints.possible_range_fields()
            if index is None:
                # See if we can find an index to query on
                indexes = table.get_matching_indexes(possible_hash, possible_range)
                if not indexes:
                    action = "scan"
                    kwargs["filter"] = constraints.build(visitor)
                    kwargs["expr_values"] = visitor.expression_values
                    kwargs["alias"] = visitor.attribute_names
                elif len(indexes) == 1:
                    index = indexes[0]
                    action = "query"
                    add_query_kwargs(kwargs, visitor, constraints, index)
                else:
                    names = ", ".join([index.name for index in indexes])
                    raise SyntaxError(
                        "No index specified with USING <index>, "
                        "but multiple possibilities for query: "
                        "%s" % names
                    )
            else:
                if index.hash_key in possible_hash:
                    action = "query"
                    add_query_kwargs(kwargs, visitor, constraints, index)
                else:
                    action = "scan"
                    if not index.scannable:
                        raise SyntaxError("Cannot scan local index %r" % index_name)
                    kwargs["filter"] = constraints.build(visitor)
                    kwargs["expr_values"] = visitor.expression_values
                    kwargs["alias"] = visitor.attribute_names
        else:
            action = "scan"
        return [action, kwargs, index]
195249
def prepare_query(query):
    

    for name in query:
        value = query[name]

        # None is sent as an empty string.
        if value is None:
            query[name] = ""

        # Booleans are sent as 0 or 1.
        elif isinstance(value, bool):
            query[name] = int(value)

        # XXX shouldn't this just check for basestring instead?
        elif isinstance(value, dict):
            raise ValueError("Invalid query data type %r" %
                             type(value).__name__)
72631
def query(self, sql):
        '''
        
        '''
        try:
            self.connect()
            with self.con.cursor() as cursor:
                cursor.execute(sql)
                self.con.commit()
                res = cursor.fetchall()
                return res
        except Exception as e:
            print(e)
            return -1
        finally:
            self.close()
246233
def compile_delete(self, query):
        
        table = self.wrap_table(query.from__)

        if isinstance(query.wheres, list):
            wheres = self._compile_wheres(query)
        else:
            wheres = ""

        if query.joins:
            joins = " %s" % self._compile_joins(query, query.joins)

            sql = "DELETE %s FROM %s%s %s" % (table, table, joins, wheres)
        else:
            sql = "DELETE FROM %s %s" % (table, wheres)

        sql = sql.strip()

        if query.orders:
            sql += " %s" % self._compile_orders(query, query.orders)

        if query.limit_:
            sql += " %s" % self._compile_limit(query, query.limit_)

        return sql
777392
def compile_query(query: dict) -> PyQuery:
    

    def _pair_to_dict(pair):
        if isinstance(pair, dict):
            return pair
        return {pair[0]: pair[1]}

    def _reduce(pair):
        try:
            return {'and': (_pair_to_dict(pair[0]), _pair_to_dict(pair[1]))}
        except (KeyError, IndexError):
            return _pair_to_dict(pair)

    def _get_first_pair(d: dict):
        return list(query.items())[0]

    if len(query) < 2:
        return compile_single_item(*_get_first_pair(query))
    try:
        reduced = reduce(lambda x, y: _reduce((x, y)), query.items())
    except KeyError:
        print(query)
        reduced = query
        raise
    return compile_single_item(*_get_first_pair(reduced))
1079748
def compile_query(query):
    """"""
    if isinstance(query, dict):
        expressions = []
        for key, value in query.items():
            if key.startswith('$'):
                if key not in query_funcs:
                    raise AttributeError('Invalid operator: {}'.format(key))
                expressions.append(query_funcs[key](value))
            else:
                expressions.append(filter_query(key, value))
        if len(expressions) > 1:
            return boolean_operator_query(operator.and_)(expressions)
        else:
            return (
                expressions[0]
                if len(expressions)
                else lambda query_function: query_function(None, None)
            )
    else:
        return query
857599
def stringify_query(query):
        

        if isinstance(query, QueryBuilder):
            # Get string-representation of the passed :class:`pysnow.QueryBuilder` object
            return str(query)
        elif isinstance(query, dict):
            # Dict-type query
            return '^'.join(['%s=%s' % (k, v) for k, v in six.iteritems(query)])
        elif isinstance(query, six.string_types):
            # Regular string-type query
            return query
        else:
            raise InvalidUsage('Query must be of type string, dict or a QueryBuilder object')
1256241
def apply(self, query, value, alias):
        
        try:
            value = uuid.UUID(value)
            return query.filter(self.column == value)
        except ValueError:
            return query
116860
def compile(self):
        """"""
        sql = ''
        sql += 'DELETE FROM ' + self.dialect.quote_table(self._table)
        if self._where:
            sql += ' WHERE ' + self.compile_condition(self._where)
        if self._order_by:
            sql += ' ' + self.compile_order_by(self._order_by)

        if self._limit:
            sql += ' LIMIT ' + self._limit
        return sql
1205357
def query(self, value=None):
        
        if value is not None:
            return URL._mutate(self, query=value)
        return self._tuple.query
1002612
def iff(self, *args, **kwargs):
        """"""
        if len([x for x in kwargs.values() if x is None]):
            raise CQLEngineException("None values on iff are not allowed")

        clone = copy.deepcopy(self)
        for operator in args:
            if not isinstance(operator, TransactionClause):
                raise QueryException('{} is not a valid query operator'.format(operator))
            clone._transaction.append(operator)

        for col_name, val in kwargs.items():
            exists = False
            try:
                column = self.model._get_column(col_name)
            except KeyError:
                if col_name == 'pk__token':
                    if not isinstance(val, Token):
                        raise QueryException("Virtual column 'pk__token' may only be compared to Token() values")
                    column = columns._PartitionKeysToken(self.model)
                    quote_field = False
                else:
                    raise QueryException("Can't resolve column name: '{}'".format(col_name))

            if isinstance(val, Token):
                if col_name != 'pk__token':
                    raise QueryException("Token() values may only be compared to the 'pk__token' virtual column")
                partition_columns = column.partition_columns
                if len(partition_columns) != len(val.value):
                    raise QueryException(
                        'Token() received {} arguments but model has {} partition keys'.format(
                            len(val.value), len(partition_columns)))
                val.set_columns(partition_columns)

            if isinstance(val, BaseQueryFunction) or exists is True:
                query_val = val
            else:
                query_val = column.to_database(val)

            clone._transaction.append(TransactionClause(col_name, query_val))

        return clone
733409
def compile_select(self, query):
        
        sql = super(MySQLQueryGrammar, self).compile_select(query)

        if query.unions:
            sql = "(%s) %s" % (sql, self._compile_unions(query))

        return sql
563508
def fetch(self, sql, *args, **kwargs):
        
        with self.locked() as conn:
            return conn.query(sql, *args, **kwargs).fetch()
713103
def convert_query_to_sql_statement(query):
    
    context = query._compile_context()
    context.statement.use_labels = False
    return context.statement
535320
def __filter_query(self) -> str:
        
        filter_query = 'WHERE %s'
        bind_values = {}
        if not self.__filters:
            return None
        for filter in self.__filters:
            bind = {
                'name': Security.random_string(5),
                'value': filter['value']}
            filter_str = '%s %s :%s' % \
                (filter['column'], filter['operator'], bind['name'])
            bind_values[bind['name']] = bind['value']
            filter_query = filter_query % (filter_str + ' AND %s')
        return {
            'query': filter_query.replace(' AND %s', ''),
            'binds': bind_values}
953674
def querytime(self, value):
        
        self._querytime = value
        self.query.querytime = value