async def test_schema(self): if self.is_asyncpg: from asyncpg.exceptions import InvalidSchemaNameError else: from psycopg.errors import InvalidSchemaName as InvalidSchemaNameError self.db_config["connections"]["models"]["credentials"][ "schema"] = "mytestschema" await Tortoise.init(self.db_config, _create_db=True) with self.assertRaises(InvalidSchemaNameError): await Tortoise.generate_schemas() conn = connections.get("models") await conn.execute_script("CREATE SCHEMA mytestschema;") await Tortoise.generate_schemas() tournament = await Tournament.create(name="Test") await connections.close_all() del self.db_config["connections"]["models"]["credentials"]["schema"] await Tortoise.init(self.db_config) with self.assertRaises(OperationalError): await Tournament.filter(name="Test").first() conn = connections.get("models") _, res = await conn.execute_query( "SELECT id, name FROM mytestschema.tournament WHERE name='Test' LIMIT 1" ) self.assertEqual(len(res), 1) self.assertEqual(tournament.id, res[0]["id"]) self.assertEqual(tournament.name, res[0]["name"])
async def run(): await Tortoise.init( { "connections": { "first": { "engine": "tortoise.backends.sqlite", "credentials": {"file_path": "example.sqlite3"}, }, "second": { "engine": "tortoise.backends.sqlite", "credentials": {"file_path": "example1.sqlite3"}, }, }, "apps": { "tournaments": {"models": ["__main__"], "default_connection": "first"}, "events": {"models": ["__main__"], "default_connection": "second"}, }, } ) await Tortoise.generate_schemas() client = connections.get("first") second_client = connections.get("second") tournament = await Tournament.create(name="Tournament") await Event(name="Event", tournament_id=tournament.id).save() try: await client.execute_query('SELECT * FROM "event"') except OperationalError: print("Expected it to fail") results = await second_client.execute_query('SELECT * FROM "event"') print(results)
async def run(): await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]}) await Tortoise.generate_schemas() # Need to get a connection. Unless explicitly specified, the name should be 'default' conn = connections.get("default") # Now we can execute queries in the normal autocommit mode await conn.execute_query("INSERT INTO event (name) VALUES ('Foo')") # You can also you parameters, but you need to use the right param strings for each dialect await conn.execute_query("INSERT INTO event (name) VALUES (?)", ["Bar"]) # To do a transaction you'd need to use the in_transaction context manager async with in_transaction("default") as tconn: await tconn.execute_query("INSERT INTO event (name) VALUES ('Moo')") # Unless an exception happens it should commit automatically # This transaction is rolled back async with in_transaction("default") as tconn: await tconn.execute_query("INSERT INTO event (name) VALUES ('Sheep')") # Rollback to fail transaction await tconn.rollback() # Consider using execute_query_dict to get return values as a dict val = await conn.execute_query_dict("SELECT * FROM event") print(val)
async def asyncSetUp(self): await super().asyncSetUp() # Build large dataset self.intfields = [ await IntFields.create(intnum=val) for val in range(10, 100, 3) ] self.db = connections.get("models")
async def run(): print("SQLite:\n") await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]}) sql = get_schema_sql(connections.get("default"), safe=False) print(sql) print("\n\nMySQL:\n") await Tortoise.init(db_url="mysql://root:@127.0.0.1:3306/", modules={"models": ["__main__"]}) sql = get_schema_sql(connections.get("default"), safe=False) print(sql) print("\n\nPostgreSQL:\n") await Tortoise.init(db_url="postgres://postgres:@127.0.0.1:5432/", modules={"models": ["__main__"]}) sql = get_schema_sql(connections.get("default"), safe=False) print(sql)
async def test_application_name(self): self.db_config["connections"]["models"]["credentials"][ "application_name"] = "mytest_application" await Tortoise.init(self.db_config, _create_db=True) conn = connections.get("models") _, res = await conn.execute_query( "SELECT application_name FROM pg_stat_activity WHERE pid = pg_backend_pid()" ) self.assertEqual(len(res), 1) self.assertEqual("mytest_application", res[0]["application_name"])
async def asyncSetUp(self): await super().asyncSetUp() if Tortoise._inited: await self._tearDownDB() first_db_config = test.getDBConfig(app_label="models", modules=["tests.testmodels"]) second_db_config = test.getDBConfig(app_label="events", modules=["tests.testmodels"]) merged_config = { "connections": { **first_db_config["connections"], **second_db_config["connections"] }, "apps": { **first_db_config["apps"], **second_db_config["apps"] }, } await Tortoise.init(merged_config, _create_db=True) await Tortoise.generate_schemas() self.db = connections.get("models") self.second_db = connections.get("events")
async def test_db_url_init(self): await Tortoise.init({ "connections": { "default": f"sqlite://{':memory:'}" }, "apps": { "models": { "models": ["tests.testmodels"], "default_connection": "default" } }, }) self.assertIn("models", Tortoise.apps) self.assertIsNotNone(connections.get("default"))
async def test_default_connection_init(self): await Tortoise.init({ "connections": { "default": { "engine": "tortoise.backends.sqlite", "credentials": { "file_path": ":memory:" }, } }, "apps": { "models": { "models": ["tests.testmodels"] } }, }) self.assertIn("models", Tortoise.apps) self.assertIsNotNone(connections.get("default"))
async def init_for(self, module: str, safe=False) -> None: if self.engine != "tortoise.backends.sqlite": raise test.SkipTest("sqlite only") with patch( "tortoise.backends.sqlite.client.SqliteClient.create_connection", new=AsyncMock()): await Tortoise.init({ "connections": { "default": { "engine": "tortoise.backends.sqlite", "credentials": { "file_path": ":memory:" }, } }, "apps": { "models": { "models": [module], "default_connection": "default" } }, }) self.sqls = get_schema_sql(connections.get("default"), safe).split(";\n")
async def test_init_yaml_file(self): await Tortoise.init(config_file=os.path.dirname(__file__) + "/init.yaml") self.assertIn("models", Tortoise.apps) self.assertIsNotNone(connections.get("default"))
async def test_shorthand_init(self): await Tortoise.init(db_url=f"sqlite://{':memory:'}", modules={"models": ["tests.testmodels"]}) self.assertIn("models", Tortoise.apps) self.assertIsNotNone(connections.get("default"))
async def asyncSetUp(self): await super().asyncSetUp() self.intfields = [ await IntFields.create(intnum=val) for val in range(10) ] self.db = connections.get("models")
async def asyncSetUp(self) -> None: await super(TestCapabilities, self).asyncSetUp() self.db = connections.get("models") self.caps = self.db.capabilities