Пример #1
0
    def bind(self, provider_name, *args, **kwargs):
        if self.real_provider_name is not None:
            provider_name = self.real_provider_name
        self.provider_name = provider_name
        provider_module = import_module('pony.orm.dbproviders.' + provider_name)
        provider_cls = provider_module.provider_cls
        raw_server_version = self.raw_server_version

        if raw_server_version is None:
            if provider_name == 'sqlite': raw_server_version = '3.7.17'
            elif provider_name in ('postgres', 'pygresql'): raw_server_version = '9.2'
            elif provider_name == 'oracle': raw_server_version = '11.2.0.2.0'
            elif provider_name == 'mysql': raw_server_version = '5.6.11'
            else: assert False, provider_name  # pragma: no cover

        t = [ int(component) for component in raw_server_version.split('.') ]
        if len(t) == 2: t.append(0)
        server_version = tuple(t)
        if provider_name in ('postgres', 'pygresql'):
            server_version = int('%d%02d%02d' % server_version)

        class TestProvider(provider_cls):
            def inspect_connection(provider, connection):
                pass
        TestProvider.server_version = server_version

        kwargs['pony_check_connection'] = False
        kwargs['pony_pool_mockup'] = TestPool(self)
        Database.bind(self, TestProvider, *args, **kwargs)
Пример #2
0
    def bind(self, provider_name, *args, **kwargs):
        if self.real_provider_name is not None:
            provider_name = self.real_provider_name
        self.provider_name = provider_name
        provider_module = import_module('pony.orm.dbproviders.' +
                                        provider_name)
        provider_cls = provider_module.provider_cls
        raw_server_version = self.raw_server_version

        if raw_server_version is None:
            if provider_name == 'sqlite': raw_server_version = '3.7.17'
            elif provider_name in ('postgres', 'pygresql'):
                raw_server_version = '9.2'
            elif provider_name == 'oracle':
                raw_server_version = '11.2.0.2.0'
            elif provider_name == 'mysql':
                raw_server_version = '5.6.11'
            else:
                assert False, provider_name  # pragma: no cover

        t = [int(component) for component in raw_server_version.split('.')]
        if len(t) == 2: t.append(0)
        server_version = tuple(t)
        if provider_name in ('postgres', 'pygresql'):
            server_version = int('%d%02d%02d' % server_version)

        class TestProvider(provider_cls):
            def inspect_connection(provider, connection):
                pass

        TestProvider.server_version = server_version

        kwargs['pony_check_connection'] = False
        kwargs['pony_pool_mockup'] = TestPool(self)
        Database.bind(self, TestProvider, *args, **kwargs)
class TestSQLAST(unittest.TestCase):
    def setUp(self):
        self.db = Database('sqlite', ':memory:')
        with db_session:
            conn = self.db.get_connection()
            conn.executescript("""
            create table if not exists T1(
                a integer primary key,
                b varchar(20) not null
                );
            insert or ignore into T1 values(1, 'abc');
            """)

    @db_session
    def test_alias(self):
        sql_ast = [
            SELECT, [ALL, [COLUMN, "Group", "a"]],
            [FROM, ["Group", TABLE, "T1"]]
        ]
        sql, adapter = self.db._ast2sql(sql_ast)
        cursor = self.db._exec_sql(sql)

    @db_session
    def test_alias2(self):
        sql_ast = [
            SELECT, [ALL, [COLUMN, None, "a"]], [FROM, [None, TABLE, "T1"]]
        ]
        sql, adapter = self.db._ast2sql(sql_ast)
        cursor = self.db._exec_sql(sql)
Пример #4
0
 def setUp(self):
     self.db = Database('sqlite', ':memory:')
     conn = self.db.get_connection()
     conn.executescript("""
     create table if not exists T1(
         a integer primary key,
         b varchar(20) not null
         );
     insert or ignore into T1 values(1, 'abc');
     """)
Пример #5
0
 def setUp(self):
     self.db = Database()
     setup_database(self.db)
     with db_session:
         conn = self.db.get_connection()
         conn.executescript("""
         create table if not exists T1(
             a integer primary key,
             b varchar(20) not null
             );
         insert or ignore into T1 values(1, 'abc');
         """)
Пример #6
0
 def generate_mapping(database,
                      filename=None,
                      check_tables=True,
                      create_tables=False):
     return Database.generate_mapping(database,
                                      filename,
                                      create_tables=False)
 def setUp(self):
     self.db = Database('sqlite', ':memory:')
     with db_session:
         conn = self.db.get_connection()
         conn.executescript("""
         create table if not exists T1(
             a integer primary key,
             b varchar(20) not null
             );
         insert or ignore into T1 values(1, 'abc');
         """)
class TestSQLAST(unittest.TestCase):
    def setUp(self):
        self.db = Database('sqlite', ':memory:')
        with db_session:
            conn = self.db.get_connection()
            conn.executescript("""
            create table if not exists T1(
                a integer primary key,
                b varchar(20) not null
                );
            insert or ignore into T1 values(1, 'abc');
            """)
    @db_session
    def test_alias(self):
        sql_ast = [SELECT, [ALL, [COLUMN, "Group", "a"]],
                           [FROM, ["Group", TABLE, "T1" ]]]
        sql, adapter = self.db._ast2sql(sql_ast)
        cursor = self.db._exec_sql(sql)
    @db_session
    def test_alias2(self):
        sql_ast = [SELECT, [ALL, [COLUMN, None, "a"]],
                            [FROM, [None, TABLE, "T1"]]]
        sql, adapter = self.db._ast2sql(sql_ast)
        cursor = self.db._exec_sql(sql)
Пример #9
0
 def generate_mapping(database, filename=None, check_tables=True, create_tables=False):
     return Database.generate_mapping(database, filename, create_tables=False)
Пример #10
0
def temporary_binding():
  db = Database()
  db.bind(**config.database)
  InstalledComponentEntity = InstalledComponent.create_database_entity(db.Entity)
  db.generate_mapping(create_tables=True)
  return db, InstalledComponentEntity
Пример #11
0
  result = []
  checked = set()

  config.loader.load_components(config.components)
  for name, component in database_components():
    checked.add(name)
    curr_revision = component.__component_meta__['database_revision']
    have = InstalledComponent.get(component=name)
    have_revision = have.revision if have else None
    yield (name, component, have_revision, curr_revision)
  for have in InstalledComponent.select():
    if have.component not in checked:
      yield (have.component, None, have.revision, None)


def bind():
  """
  Binds the global Pony database *db* to a provider from the database
  configuration and permanently binds all real entities for this database
  to the #DelayedEntity subclasses.
  """

  db.bind(**config.database)
  for cls in DelayedEntity.delayed_entity_subclasses():
    cls.create_database_entity(db.Entity, bind=True)
  db.generate_mapping(create_tables=True)


db = Database()
Пример #12
0
import os

from pony.orm.core import Database, PrimaryKey, Required, Optional

# create database instance
database: Database = Database()


# define models needed for extension
class CustomCommandModel(database.Entity):
    _table_ = "custom_commands"
    command = PrimaryKey(str)
    emit = Required(str)
    counter = Optional(int)


# connect to database and generate needed tables
database.bind(
    provider="mysql",
    host=os.getenv("PAPERBOT.DATABASE.HOST"),
    user=os.getenv("PAPERBOT.DATABASE.USER"),
    passwd=os.getenv("PAPERBOT.DATABASE.PASSWD"),
    db=os.getenv("PAPERBOT.DATABASE.DB"),
)
database.generate_mapping(create_tables=True)
Пример #13
0
 def __init__(self, provider_name, *args, **kwargs):
     kwargs['pony_check_connection'] = False
     kwargs['pony_pool_mockup'] = TestPool()
     Database.__init__(self, self.real_provider_name or provider_name, *args, **kwargs)
Пример #14
0
from flask import Blueprint
from flask import Flask
from flask_jwt import JWT
from flask_restful import Api
from pony.orm.core import Database

from config import config, userid_table, username_table
from methods.Authentication import ConnectionAuth
from sql.Connection import DbAuth

app = Flask(__name__)
app.config = config()
# blueprint api
api_bp = Blueprint('api', __name__)
api = Api(api_bp)
app.register_blueprint(api_bp, url_prefix='/api')

# Authentication to server
auth = ConnectionAuth(username_table, userid_table)
jwt = JWT(app, auth.authenticate, auth.identity)

# Authentication/connection config.yaml to database
# import cryptography
db = Database()
dbAuth = dict(DbAuth('config.yaml').load())
db.bind(**dbAuth['mysql'])