File: utils.py

package info (click to toggle)
ormar 0.22.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,952 kB
  • sloc: python: 24,085; makefile: 34; sh: 14
file content (34 lines) | stat: -rw-r--r-- 1,191 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import functools

import ormar


def create_drop_database(base_config: ormar.OrmarConfig) -> None:
    # create all tables in the database before execution
    # and drop them after, note that in production you should use migrations
    def wrapper(func):
        @functools.wraps(func)
        async def wrapped(*args):
            # Connect database if not already connected
            if not base_config.database.is_connected:
                await base_config.database.connect()

            # Drop and create tables
            async with base_config.database.engine.begin() as conn:
                await conn.run_sync(base_config.metadata.drop_all)
                await conn.run_sync(base_config.metadata.create_all)

            try:
                await func(*args)
            finally:
                # Drop tables and cleanup
                async with base_config.database.engine.begin() as conn:
                    await conn.run_sync(base_config.metadata.drop_all)

                # Disconnect and dispose engine
                if base_config.database.is_connected:
                    await base_config.database.disconnect()

        return wrapped

    return wrapper