Inserts `values` into `tablename`. Returns current sequence ID. Set `seqname` to the ID if it's not the default, or to `False` if there isn't one. >>> db = DB(None, {}) >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=Tr
(self, tablename, seqname=None, _test=False, **values)
| 942 | return xjoin(sql, nout) |
| 943 | |
| 944 | def insert(self, tablename, seqname=None, _test=False, **values): |
| 945 | """ |
| 946 | Inserts `values` into `tablename`. Returns current sequence ID. |
| 947 | Set `seqname` to the ID if it's not the default, or to `False` |
| 948 | if there isn't one. |
| 949 | |
| 950 | >>> db = DB(None, {}) |
| 951 | >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) |
| 952 | >>> q |
| 953 | <sql: "INSERT INTO foo (age, created, name) VALUES (2, NOW(), 'bob')"> |
| 954 | >>> q.query() |
| 955 | 'INSERT INTO foo (age, created, name) VALUES (%s, NOW(), %s)' |
| 956 | >>> q.values() |
| 957 | [2, 'bob'] |
| 958 | """ |
| 959 | |
| 960 | def q(x): |
| 961 | return "(" + x + ")" |
| 962 | |
| 963 | if values: |
| 964 | # needed for Py3 compatibility with the above doctests |
| 965 | sorted_values = sorted(values.items(), key=lambda t: t[0]) |
| 966 | |
| 967 | _keys = SQLQuery.join(map(lambda t: t[0], sorted_values), ", ") |
| 968 | _values = SQLQuery.join( |
| 969 | [sqlparam(v) for v in map(lambda t: t[1], sorted_values)], ", " |
| 970 | ) |
| 971 | sql_query = ( |
| 972 | "INSERT INTO %s " % tablename + q(_keys) + " VALUES " + q(_values) |
| 973 | ) |
| 974 | else: |
| 975 | sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) |
| 976 | |
| 977 | if _test: |
| 978 | return sql_query |
| 979 | |
| 980 | db_cursor = self._db_cursor() |
| 981 | if seqname is not False: |
| 982 | sql_query = self._process_insert_query(sql_query, tablename, seqname) |
| 983 | |
| 984 | if isinstance(sql_query, tuple): |
| 985 | # for some databases, a separate query has to be made to find |
| 986 | # the id of the inserted row. |
| 987 | q1, q2 = sql_query |
| 988 | self._db_execute(db_cursor, q1) |
| 989 | self._db_execute(db_cursor, q2) |
| 990 | else: |
| 991 | self._db_execute(db_cursor, sql_query) |
| 992 | |
| 993 | try: |
| 994 | out = db_cursor.fetchone()[0] |
| 995 | except Exception: |
| 996 | out = None |
| 997 | |
| 998 | if not self.ctx.transactions: |
| 999 | self.ctx.commit() |
| 1000 | |
| 1001 | return out |