odoo 是怎样格式化sql 查询语句的

主要还是使用format 来替换变量

# generic INSERT and UPDATE queries
INSERT_QUERY = "INSERT INTO {table} ({cols}) VALUES {rows} RETURNING id"
UPDATE_QUERY = "UPDATE {table} SET {assignment} WHERE {condition} RETURNING id"

def query_insert(cr, table, rows):
    """ Insert rows in a table. ``rows`` is a list of dicts, all with the same
        set of keys. Return the ids of the new rows.
    """
    if isinstance(rows, Mapping):
        rows = [rows]
    cols = list(rows[0])
    query = INSERT_QUERY.format(
        table=table,
        cols=",".join(cols),
        rows=",".join("%s" for row in rows),
    )
    params = [tuple(row[col] for col in cols) for row in rows]
    cr.execute(query, params)
    return [row[0] for row in cr.fetchall()]

def query_update(cr, table, values, selectors):
    """ Update the table with the given values (dict), and use the columns in
        ``selectors`` to select the rows to update.
    """
    setters = set(values) - set(selectors)
    query = UPDATE_QUERY.format(
        table=table,
        assignment=",".join("{0}=%({0})s".format(s) for s in setters),
        condition=" AND ".join("{0}=%({0})s".format(s) for s in selectors),
    )
    cr.execute(query, values)
    return [row[0] for row in cr.fetchall()]
posted @ 2020-07-22 11:09  那时一个人  阅读(307)  评论(0编辑  收藏  举报