async def test_multiple_primary_key_order(): import gino db1 = gino.Gino() await db1.set_bind(MYSQL_URL) class NameCard(db1.Model): __tablename__ = "name_cards" first_name = db1.Column(db1.Unicode(255), primary_key=True) last_name = db1.Column(db1.Unicode(255), primary_key=True) await db1.gino.create_all() try: await NameCard.create(first_name="first", last_name="last") nc = await NameCard.get(("first", "last")) assert nc.first_name == "first" assert nc.last_name == "last" with pytest.raises(ValueError, match="expected 2, got 3"): await NameCard.get(dict(a=1, first_name="first", last_name="last")) with pytest.raises(KeyError, match="first_name"): await NameCard.get(dict(first="first", last_name="last")) nc = await NameCard.get(dict(first_name="first", last_name="last")) assert nc.first_name == "first" assert nc.last_name == "last" nc = await NameCard.get({0: "first", 1: "last"}) assert nc.first_name == "first" assert nc.last_name == "last" finally: await db1.gino.drop_all() await db1.pop_bind().close() db2 = gino.Gino(MYSQL_URL) await db2.set_bind(MYSQL_URL) class NameCard(db2.Model): __tablename__ = "name_cards" last_name = db2.Column(db2.Unicode(255), primary_key=True) first_name = db2.Column(db2.Unicode(255), primary_key=True) await db2.gino.create_all() try: await NameCard.create(first_name="first", last_name="last") nc = await NameCard.get(("last", "first")) assert nc.first_name == "first" assert nc.last_name == "last" nc = await NameCard.get(dict(first_name="first", last_name="last")) assert nc.first_name == "first" assert nc.last_name == "last" nc = await NameCard.get({1: "first", "last_name": "last"}) assert nc.first_name == "first" assert nc.last_name == "last" finally: await db2.gino.drop_all() await db2.pop_bind().close()
async def test_mixin_crud(engine): db = gino.Gino() db.bind = engine class Mixin: id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text) class MixinCrud(db.Model, Mixin): __tablename__ = "mixin_crud" await db.gino.create_all() try: mc = await MixinCrud.create(name="mctest") assert mc.name == "mctest" await mc.update(name="updated").apply() mc = await MixinCrud.query.gino.first() assert mc.name == "updated" await mc.delete() mc = await MixinCrud.query.gino.first() assert mc is None finally: await db.gino.drop_all()
async def test(engine, define=True): db = gino.Gino() class Blog(db.Model): __tablename__ = "s_blog" id = db.Column(db.BigInteger(), primary_key=True) title = db.Column(db.Unicode(), index=True, comment="Title Comment") visits = db.Column(db.BigInteger(), default=0) comment_id = db.Column(db.ForeignKey("s_comment.id")) number = db.Column(db.Enum(MyEnum), nullable=False, default=MyEnum.TWO) number2 = db.Column(AsyncEnum(MyEnum), nullable=False, default=MyEnum.TWO) class Comment(db.Model): __tablename__ = "s_comment" id = db.Column(db.BigInteger(), primary_key=True) blog_id = db.Column(db.ForeignKey("s_blog.id", name="blog_id_fk")) blog_seq = db.Sequence("blog_seq", metadata=db, schema="schema_test") try: async with engine.acquire() as conn: assert not await engine.dialect.has_schema(conn, "schema_test") assert not await engine.dialect.has_table(conn, "non_exist") assert not await engine.dialect.has_sequence(conn, "non_exist") assert not await engine.dialect.has_type(conn, "non_exist") assert not await engine.dialect.has_type( conn, "non_exist", schema="schema_test" ) await engine.status("create schema schema_test") Blog.__table__.schema = "schema_test" Blog.__table__.comment = "Blog Comment" Comment.__table__.schema = "schema_test" db.bind = engine await db.gino.create_all() await Blog.number.type.create_async(engine, checkfirst=True) await Blog.number2.type.create_async(engine, checkfirst=True) await db.gino.create_all(tables=[Blog.__table__], checkfirst=True) await blog_seq.gino.create(checkfirst=True) await Blog.__table__.gino.create(checkfirst=True) await db.gino.drop_all() await db.gino.drop_all(tables=[Blog.__table__], checkfirst=True) await Blog.__table__.gino.drop(checkfirst=True) await blog_seq.gino.drop(checkfirst=True) if define: class Comment2(db.Model): __tablename__ = "s_comment_2" id = db.Column(db.BigInteger(), primary_key=True) blog_id = db.Column(db.ForeignKey("s_blog.id")) Comment2.__table__.schema = "schema_test" await db.gino.create_all() await db.gino.drop_all() finally: await engine.status("drop schema schema_test cascade")
async def get_postgres_ref(self): """Grabs the main DB reference. This doesn't follow a singleton pattern (use bot.db instead). """ await self.logger.debug("Obtaining and binding to Gino instance") db_ref = gino.Gino() db_url = self.generate_db_url() await db_ref.set_bind(db_url) db_ref.Model.__table_args__ = {"extend_existing": True} return db_ref
from enum import Enum import pytest import gino from gino.dialects.asyncpg import AsyncEnum pytestmark = pytest.mark.asyncio db = gino.Gino() class MyEnum(Enum): ONE = "one" TWO = "two" class Blog(db.Model): __tablename__ = "s_blog" id = db.Column(db.BigInteger(), primary_key=True) title = db.Column(db.Unicode(), index=True, comment="Title Comment") visits = db.Column(db.BigInteger(), default=0) comment_id = db.Column(db.ForeignKey("s_comment.id")) number = db.Column(db.Enum(MyEnum), nullable=False, default=MyEnum.TWO) number2 = db.Column(AsyncEnum(MyEnum), nullable=False, default=MyEnum.TWO) class Comment(db.Model): __tablename__ = "s_comment" id = db.Column(db.BigInteger(), primary_key=True)
import gino db: gino.api.Gino = gino.Gino() from .task_provider import TaskProvider from . import entities # Чтобы при импорте db исполнялся модуль entities __all__ = ["TaskProvider", "entities"]
import gino import settings DB = gino.Gino() async def init_pg(app): dsn = 'postgresql://{user}:{password}@{host}:{port}/{database}' await DB.set_bind(dsn.format(**settings.config['db'])) app['db'] = DB async def close_pg(app): await app['db'].pop_bind().close() if __name__ == '__main__': import asyncio import users.models import auctions.models async def main(): dsn = 'postgresql://{user}:{password}@{host}:{port}/{database}' await DB.set_bind(dsn.format(**settings.config['db'])) await DB.gino.create_all(tables=( users.models.User.__table__, auctions.models.Auction.__table__, auctions.models.Bid.__table__, )) await DB.pop_bind().close()
# flake8: noqa import logging import gino from config import DATABASE_CONFIG, DATABASE_POOL_SIZE_MAX, DATABASE_POOL_SIZE_MIN logger = logging.getLogger(__name__) db: gino.Gino = gino.Gino( naming_convention={ # passed to sqlalchemy.MetaData "ix": "ix_%(column_0_label)s", "uq": "uq_%(table_name)s_%(column_0_name)s", "ck": "ck_%(table_name)s_%(constraint_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", "pk": "pk_%(table_name)s", } ) async def startup( pool_min_size: int = DATABASE_POOL_SIZE_MIN, pool_max_size: int = DATABASE_POOL_SIZE_MAX, ): # nocover (implicitly tested with test client) if not db.is_bound(): await db.set_bind(db.url, min_size=pool_min_size, max_size=pool_max_size) logger.debug( f"Connected to {db.url.__to_string__(hide_password=True)}")
def __init__(self, engine): self.engine = engine self.metadata = gino.Gino() self.loop = asyncio.get_event_loop()