예제 #1
0
    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"])
예제 #2
0
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)
예제 #3
0
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)
예제 #4
0
 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")
예제 #5
0
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)
예제 #6
0
    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"])
예제 #7
0
 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")
예제 #8
0
 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"))
예제 #9
0
 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"))
예제 #10
0
 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")
예제 #11
0
 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"))
예제 #12
0
 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"))
예제 #13
0
 async def asyncSetUp(self):
     await super().asyncSetUp()
     self.intfields = [
         await IntFields.create(intnum=val) for val in range(10)
     ]
     self.db = connections.get("models")
예제 #14
0
 async def asyncSetUp(self) -> None:
     await super(TestCapabilities, self).asyncSetUp()
     self.db = connections.get("models")
     self.caps = self.db.capabilities