Converts a dictionary of keyword arguments into a tuple
        of SQL select statements and the list of SQL arguments
186892
def featuresQuery(self, **kwargs):
        
        # TODO: Optimize by refactoring out string concatenation
        sql = ""
        sql_rows = "SELECT * FROM FEATURE WHERE id > 1 "
        sql_args = ()
        if 'name' in kwargs and kwargs['name']:
            sql += "AND name = ? "
            sql_args += (kwargs.get('name'),)
        if 'geneSymbol' in kwargs and kwargs['geneSymbol']:
            sql += "AND gene_name = ? "
            sql_args += (kwargs.get('geneSymbol'),)
        if 'start' in kwargs and kwargs['start'] is not None:
            sql += "AND end > ? "
            sql_args += (kwargs.get('start'),)
        if 'end' in kwargs and kwargs['end'] is not None:
            sql += "AND start < ? "
            sql_args += (kwargs.get('end'),)
        if 'referenceName' in kwargs and kwargs['referenceName']:
            sql += "AND reference_name = ?"
            sql_args += (kwargs.get('referenceName'),)
        if 'parentId' in kwargs and kwargs['parentId']:
            sql += "AND parent_id = ? "
            sql_args += (kwargs['parentId'],)
        if kwargs.get('featureTypes') is not None \
                and len(kwargs['featureTypes']) > 0:
            sql += "AND type IN ("
            sql += ", ".join(["?", ] * len(kwargs.get('featureTypes')))
            sql += ") "
            sql_args += tuple(kwargs.get('featureTypes'))
        sql_rows += sql
        sql_rows += " ORDER BY reference_name, start, end ASC "
        return sql_rows, sql_args
242351
def args_as_tuple(self):
        """"""
        result = ("currentdate", )
        result += (
            ":zone",
            self.extra_arguments["zone"].strip('"'),
            self.arguments["match-type"],
        )
        if self.arguments["match-type"] in [":count", ":value"]:
            result += (self.extra_arguments["match-type"].strip('"'), )
        result += (self.arguments["date-part"].strip('"'), )
        value = self.arguments["key-list"]
        if isinstance(value, list):
            # FIXME
            value = "[{}]".format(
                ",".join('"{}"'.format(item) for item in value))
        if value.startswith("["):
            result = result + tuple(tools.to_list(value))
        else:
            result = result + (value.strip('"'),)
        return result
400217
def getAllText(cls, where=None, SEPERATOR=' ', orderBy=None):
        
        (sql, fields) = cls._prepareSQL("SELECTALL", where, orderBy=orderBy)
        curs = cls.cursor()
        curs.execute(sql)
        # We might start eating memory at this point
        rows = curs.fetchall()
        curs.close()
        result = []
        idPositions = [fields.index(key) for key in cls._sqlPrimary]
        shortPos = [fields.index(short) for short in cls._shortView]
        for row in rows:
            ids = [row[pos] for pos in idPositions]
            if len(idPositions) > 1:
                ids = tuple(ids)
            else:
                ids = ids[0]
            text = SEPERATOR.join([str(row[pos]) for pos in shortPos])
            result.append((ids, text))
        return result
305050
def get_join_parameters(join_kwargs):
    

    by = join_kwargs.get('by', None)
    suffixes = join_kwargs.get('suffixes', ('_x', '_y'))
    if isinstance(by, tuple):
        left_on, right_on = by
    elif isinstance(by, list):
        by = [x if isinstance(x, tuple) else (x, x) for x in by]
        left_on, right_on = (list(x) for x in zip(*by))
    else:
        left_on, right_on = by, by
    return left_on, right_on, suffixes
690941
def list_keywords(self):
        '''  '''
        names = []
        try:
            for n in self.cur.execute("SELECT keyword FROM keyword;").fetchall():
                # Strip out leading and trailing whitespaces (can be artifacts of old data)
                k = n[0].strip()
                if len(k):
                    names.extend([k])
        except:
            self.error("ERROR: cannot find database table 'keyword'")
        names = list(set(names)) # remove duplicates
        names = sorted(names, key=lambda s: s.lower())
        return(names)
1010004
def quote_sql(value, param=None):
    
    try:
        if isinstance(value, SQL):
            if not param:
                return value
            param = {k: quote_sql(v) for k, v in param.items()}
            return SQL(expand_template(value, param))
        elif is_text(value):
            return SQL(value)
        elif is_data(value):
            return quote_value(json_encode(value))
        elif hasattr(value, '__iter__'):
            return quote_list(value)
        else:
            return text_type(value)
    except Exception as e:
        Log.error("problem quoting SQL", e)
751959
def sqliteRowsToDicts(sqliteRows):
    
    return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)
1172030
def get_query_kwargs(**kwargs):
    """"""
    query_kwargs = {}

    query = kwargs.pop("query")
    if query:
        query_kwargs["query"] = query

    return query_kwargs
155193
def _sqlfile_to_statements(sql):
    
    statements = (sqlparse.format(stmt, strip_comments=True).strip() for stmt in sqlparse.split(sql))
    return [stmt for stmt in statements if stmt]
1206386
def execute_sql(self, query):
        
        c = self.con.cursor()
        c.execute(query)
        result = []
        if c.rowcount > 0:
            try:
                result = c.fetchall()
            except psycopg2.ProgrammingError:
                pass
        return result
895491
def _setop(self, query):
        
        if isinstance(query.select, list):
            # RETURN BORING RESULT SET
            selects = FlatList()
            for s in listwrap(query.select):
                if isinstance(s.value, Mapping):
                    for k, v in s.value.items:
                        selects.append(sql_alias(v, quote_column(s.name + "." + k)))
                if isinstance(s.value, list):
                    for i, ss in enumerate(s.value):
                        selects.append(sql_alias(s.value, quote_column(s.name + "," + str(i))))
                else:
                    selects.append(sql_alias(s.value, quote_column(s.name)))

            sql = expand_template("""
                SELECT
                    {{selects}}
                FROM
                    {{table}}
                {{where}}
                {{sort}}
                {{limit}}
            """, {
                "selects": SQL(",\n".join(selects)),
                "table": self._subquery(query["from"])[0],
                "where": self._where2sql(query.where),
                "limit": self._limit2sql(query.limit),
                "sort": self._sort2sql(query.sort)
            })

            def post_process(sql):
                result = self.db.query(sql)
                for s in listwrap(query.select):
                    if isinstance(s.value, Mapping):
                        for r in result:
                            r[s.name] = {}
                            for k, v in s.value:
                                r[s.name][k] = r[s.name + "." + k]
                                r[s.name + "." + k] = None

                    if isinstance(s.value, list):
                        # REWRITE AS TUPLE
                        for r in result:
                            r[s.name] = tuple(r[s.name + "," + str(i)] for i, ss in enumerate(s.value))
                            for i, ss in enumerate(s.value):
                                r[s.name + "," + str(i)] = None

                expand_json(result)
                return result

            return sql, post_process  # RETURN BORING RESULT SET
        else:
            # RETURN LIST OF VALUES
            if query.select.value == ".":
                select = "*"
            else:
                name = query.select.name
                select = sql_alias(query.select.value, quote_column(name))

            sql = expand_template("""
                SELECT
                    {{selects}}
                FROM
                    {{table}}
                {{where}}
                {{sort}}
                {{limit}}
            """, {
                "selects": SQL(select),
                "table": self._subquery(query["from"])[0],
                "where": self._where2sql(query.where),
                "limit": self._limit2sql(query.limit),
                "sort": self._sort2sql(query.sort)
            })

            if query.select.value == ".":
                def post(sql):
                    result = self.db.query(sql)
                    expand_json(result)
                    return result

                return sql, post
            else:
                return sql, lambda sql: [r[name] for r in self.db.query(sql)]
1205239
def query_args(self, name):
        
        sql = 'select type, id from code_items ' \
              'where kind = 22 and name = ?'
        logging.debug('%s %s', sql, (name,))
        self.cursor.execute(sql, (name,))
        func = self.cursor.fetchone()
        if func:
            sql = 'select param_number, type, name ' \
                  'from code_items where parent_id = ?'
            logging.debug('%s %s', sql, (func[1],))
            self.cursor.execute(sql, (func[1],))
            args = self.cursor.fetchall()
            ret_type = clean_ret_type(func[0])
            args = [
                (arg_number, sanitize_type(arg_type), arg_name)
                for arg_number, arg_type, arg_name in args
            ]
            return ret_type, name, args
        return None
715058
def sql_to_dict(self, query, param):
        
        cursor = connection.cursor()
        cursor.execute(query, param)
        fieldnames = [name[0] for name in cursor.description]
        result = []
        for row in cursor.fetchall():
            rowset = []
            for field in zip(fieldnames, row):
                rowset.append(field)
            result.append(dict(rowset))
        return result
968144
def query(self, sql, *args, **kwargs):
        
        with self.locked() as conn:
            for row in conn.query(sql, *args, **kwargs):
                yield row
16241
def schema(self):
        
        c = self.conn.cursor()
        c.execute(
            '''
            SELECT sql FROM sqlite_master
            ''')
        results = []
        for i, in c:
            if i is not None:
                results.append(i)
        return '\n'.join(results)
200227
def load_keys(database, parameters):
    """"""
    keys = []
    with database.snapshot() as snapshot:
        results = snapshot.execute_sql(
            'SELECT u.id FROM %s u' % parameters['table'])

    for row in results:
        keys.append(row[0])

    return keys
1309420
def select(*queries, **kwargs):
    
    def make_query(*args):
        def simple_query(nodes):
            if len(args) == 0:
                return nodes
            pred = args[0]
            results = []
            if isinstance(pred, list):
                funcs = [make_query(q) for q in pred]
                return __or(funcs, nodes)
            elif isinstance(pred, tuple):
                name, attrs = pred[0], pred[1:]
                name_pred = __make_name_pred(name)
                attrs_pred = __make_attrs_pred(attrs)
                for n in nodes:
                    if name_pred(n.name) and attrs_pred(n.attrs):
                        results.append(n)
            else:
                name_pred = __make_name_pred(pred)
                for n in nodes:
                    if name_pred(n.name):
                        results.append(n)
            return results
        if len(args) > 1:
            return __compose(make_query(*args[1:]), simple_query)
        return simple_query

    def deep_query(query, nodes):
        """ Slide the query down the branches. """
        def inner(children):
            results = []
            for c in children:
                if query([c]):
                    results.append(c)
                results.extend(inner(c.children))
            return results
        return inner(nodes)

    def unique(roots):
        seen = set()
        results = []
        for r in roots:
            if r not in seen:
                seen.add(r)
                results.append(r)
        return results

    def compiled_query(nodes):
        """
        This is the compiled query that can be run against a configuration.
        """
        query = make_query(*queries)

        roots = kwargs.get("roots", True)
        if kwargs.get("deep", False):
            results = deep_query(query, nodes)
            if roots:
                results = unique([r.root for r in results])
        elif roots:
            results = unique([n.root for n in query(nodes)])
        else:
            results = query(nodes)

        one = kwargs.get("one")
        if one is None:
            return SearchResult(children=results)
        return results[one] if results else None
    return compiled_query