()
| 14 | |
| 15 | |
| 16 | async def run(): |
| 17 | await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]}) |
| 18 | await Tortoise.generate_schemas() |
| 19 | |
| 20 | # Need to get a connection. Unless explicitly specified, the name should be 'default' |
| 21 | conn = connections.get("default") |
| 22 | |
| 23 | # Now we can execute queries in the normal autocommit mode |
| 24 | await conn.execute_query("INSERT INTO event (name) VALUES ('Foo')") |
| 25 | |
| 26 | # You can also you parameters, but you need to use the right param strings for each dialect |
| 27 | await conn.execute_query("INSERT INTO event (name) VALUES (?)", ["Bar"]) |
| 28 | |
| 29 | # To do a transaction you'd need to use the in_transaction context manager |
| 30 | async with in_transaction("default") as tconn: |
| 31 | await tconn.execute_query("INSERT INTO event (name) VALUES ('Moo')") |
| 32 | # Unless an exception happens it should commit automatically |
| 33 | |
| 34 | # This transaction is rolled back |
| 35 | async with in_transaction("default") as tconn: |
| 36 | await tconn.execute_query("INSERT INTO event (name) VALUES ('Sheep')") |
| 37 | # Rollback to fail transaction |
| 38 | await tconn.rollback() |
| 39 | |
| 40 | # Consider using execute_query_dict to get return values as a dict |
| 41 | val = await conn.execute_query_dict("SELECT * FROM event") |
| 42 | print(val) |
| 43 | # Note that the result doesn't contain the rolled-back "Sheep" entry. |
| 44 | |
| 45 | |
| 46 | if __name__ == "__main__": |
no test coverage detected