MCPcopy Create free account
hub / github.com/tortoise/tortoise-orm / run

Function run

examples/manual_sql.py:16–43  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

14
15
16async 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
46if __name__ == "__main__":

Callers 1

manual_sql.pyFile · 0.70

Calls 7

in_transactionFunction · 0.90
initMethod · 0.45
generate_schemasMethod · 0.45
getMethod · 0.45
execute_queryMethod · 0.45
rollbackMethod · 0.45
execute_query_dictMethod · 0.45

Tested by

no test coverage detected