odoo 是怎樣格式化sql 查詢語句的
阿新 • • 發佈:2020-07-22
主要還是使用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()]