Exemplo n.º 1
0
def test_Column():
    """ _column.Column() works as expected """
    meta = _sa.MetaData()
    table = _sa.Table(
        u'mytable',
        meta,
        _sa.Column(u'Lala',
                   _mysql.VARCHAR(255),
                   nullable=True,
                   server_default='""'),
        _sa.Column(u'lolo',
                   _mysql.INTEGER,
                   primary_key=True,
                   autoincrement=False),
    )
    meta.bind = _test.Bunch(dialect=_test.Bunch(name='mysql'))
    symbols = _symbols.Symbols(symbols=dict(type="TT"))

    inst = _column.Column.from_sa(table.c.Lala, symbols)
    if bytes is str:
        assert repr(inst) == ('C(\'Lala\', TT.VARCHAR(255), '
                              'server_default=D(u\'""\'))')
    else:
        assert repr(inst) == ('C(\'Lala\', TT.VARCHAR(255), '
                              'server_default=D(\'""\'))')

    inst = _column.Column.from_sa(table.c.lolo, symbols)
    assert repr(inst) == ("C('lolo', TT.INTEGER, nullable=False, "
                          "autoincrement=False)")
Exemplo n.º 2
0
def test_table(tmpdir):
    """ _table.Table() works as expected """
    tmpdir = str(tmpdir)
    filename = _os.path.join(tmpdir, 'tabletest.db')

    db = _sa.create_engine('sqlite:///%s' % (filename, ))
    meta = _sa.MetaData(db)
    db.execute("""
        CREATE TABLE stocks
        (date DATE, trans text, symbol varchar(12), qty real, price real,
         primary key (date))
    """)
    table = _table.Table.by_name('main.stocks', 'STOCKS', meta, {},
                                 _symbols.Symbols())

    expected = ("T(u'stocks', m,\n"
                "    C('date', t.DATE, nullable=False),\n"
                "    C('trans', t.TEXT),\n"
                "    C('symbol', t.VARCHAR(12)),\n"
                "    C('qty', t.REAL),\n"
                "    C('price', t.REAL),\n"
                "    schema=u'main',\n"
                ")\n"
                "PrimaryKey(STOCKS.c.date)")
    if bytes is not str:
        expected = expected.replace("u'", "'")
    assert repr(table) == expected
Exemplo n.º 3
0
def test_Column_identity():
    """ _column.Column() works ith identity """
    if not getattr(_sa, 'Identity', None):
        skip("Identity not defined")

    meta = _sa.MetaData()
    table = _sa.Table(
        u'mytable',
        meta,
        _sa.Column(u'Lala', _mysql.VARCHAR(255), _sa.Identity()),
        _sa.Column(u'lolo',
                   _mysql.INTEGER,
                   primary_key=True,
                   autoincrement=False),
    )
    meta.bind = _test.Bunch(dialect=_test.Bunch(name='mysql'))
    symbols = _symbols.Symbols(symbols=dict(type="TT"))

    inst = _column.Column.from_sa(table.c.Lala, symbols)
    if bytes is str:
        assert repr(inst) == ('C(\'Lala\', TT.VARCHAR(255), '
                              'nullable=False, '
                              'server_default=_sa.Identity())')
    else:
        assert repr(inst) == ('C(\'Lala\', TT.VARCHAR(255), '
                              'nullable=False, '
                              'server_default=_sa.Identity())')

    inst = _column.Column.from_sa(table.c.lolo, symbols)
    assert repr(inst) == ("C('lolo', TT.INTEGER, nullable=False, "
                          "autoincrement=False)")
Exemplo n.º 4
0
def test_schema(tmpdir):
    """ _schema.Schema() works as expected """
    _warnings.simplefilter('error', _sa.exc.SAWarning)

    tmpdir = str(tmpdir)
    filename = _os.path.join(tmpdir, 'tabletest.db')

    db = _sa.create_engine('sqlite:///%s' % (filename, )).connect()
    try:
        db.execute('''
            CREATE TABLE names (
                id  INT(11) PRIMARY KEY,
                first  VARCHAR(128) DEFAULT NULL,
                last   VARCHAR(129) NOT NULL
            );
        ''')
        db.execute('''
            CREATE TABLE emails (
                id  INT(11) PRIMARY KEY,
                address  VARCHAR(127) NOT NULL,

                UNIQUE (address)
            );
        ''')
        db.execute('''
            CREATE TABLE addresses (
                id  INT(11) PRIMARY KEY,
                zip_code  VARCHAR(32) DEFAULT NULL,
                place     VARCHAR(78) NOT NULL,
                street    VARCHAR(64) DEFAULT NULL
            );
        ''')
        db.execute('''
            CREATE TABLE persons (
                id  INT(11) PRIMARY KEY,
                address  INT(11) NOT NULL,
                name  INT(11) NOT NULL,
                email  INT(11) DEFAULT NULL,

                FOREIGN KEY (address) REFERENCES addresses (id),
                FOREIGN KEY (name) REFERENCES names (id),
                FOREIGN KEY (email) REFERENCES emails (id)
            );
        ''')
        db.execute('''
            ALTER TABLE addresses
                ADD COLUMN owner INT(11) DEFAULT NULL REFERENCES persons (id);
        ''')
        db.execute('''
            CREATE TABLE temp.blub (id INT PRIMARY KEY);
        ''')
        schema = _schema.Schema(db, [('persons', 'persons'),
                                     ('blah', 'temp.blub')],
                                {'temp': 'foo.bar.baz'},
                                _symbols.Symbols(dict(type='t')),
                                dbname='foo')
    finally:
        db.close()

    with open(_os.path.join(tmpdir, "schema.py"), 'w') as fp:
        schema.dump(fp)

    with open(_os.path.join(tmpdir, "schema.py")) as fp:
        result = fp.read()

    expected = '''
# -*- coding: ascii -*-
# flake8: noqa pylint: skip-file
"""
==============================
 SQLAlchemy schema definition
==============================

SQLAlchemy schema definition for foo.

:Warning: DO NOT EDIT, this file is generated
"""

import sqlalchemy as _sa
from sqlalchemy.dialects import sqlite as t
from foo.bar import baz as _baz
from gensaschema.constraints import ForeignKey as ForeignKey
from gensaschema.constraints import PrimaryKey as PrimaryKey
from gensaschema.constraints import Unique as Unique

m = _sa.MetaData()
T = _sa.Table
C = _sa.Column
D = _sa.DefaultClause

# Table "addresses"
addresses = T(u'addresses', m,
    C('id', t.INTEGER%(nullable)s),
    C('zip_code', t.VARCHAR(32), server_default=D(u'NULL')),
    C('place', t.VARCHAR(78), nullable=False),
    C('street', t.VARCHAR(64), server_default=D(u'NULL')),
    C('owner', t.INTEGER, server_default=D(u'NULL')),
)
PrimaryKey(addresses.c.id)

# Defined at table 'persons':
# ForeignKey(
#     [addresses.c.owner],
#     [persons.c.id],
# )


# Table "emails"
emails = T(u'emails', m,
    C('id', t.INTEGER%(nullable)s),
    C('address', t.VARCHAR(127), nullable=False),
)
PrimaryKey(emails.c.id)
Unique(emails.c.address)


# Table "names"
names = T(u'names', m,
    C('id', t.INTEGER%(nullable)s),
    C('first', t.VARCHAR(128), server_default=D(u'NULL')),
    C('last', t.VARCHAR(129), nullable=False),
)
PrimaryKey(names.c.id)


# Table "persons"
persons = T(u'persons', m,
    C('id', t.INTEGER%(nullable)s),
    C('address', t.INTEGER, nullable=False),
    C('name', t.INTEGER, nullable=False),
    C('email', t.INTEGER, server_default=D(u'NULL')),
)
PrimaryKey(persons.c.id)
ForeignKey(
    [persons.c.address],
    [addresses.c.id],
)
ForeignKey(
    [persons.c.email],
    [emails.c.id],
)
ForeignKey(
    [persons.c.name],
    [names.c.id],
)

# Foreign key belongs to 'addresses':
ForeignKey(
    [addresses.c.owner],
    [persons.c.id],
)


del _sa, T, C, D, m

# vim: nowrap tw=0
    '''.strip() + '\n'
    if bytes is not str:
        expected = expected.replace("u'", "'")
    expected %= dict(
        nullable=("" if sa_version >= (1, 4) else ", nullable=False"))
    assert result == expected

    result = result.replace('from foo.bar import baz as _baz', '')
    glob, loc = {}, {}
    code = compile(result, "schema.py", "exec")
    # pylint: disable = exec-used, eval-used
    if _sys.version_info >= (3, ):
        exec(code, glob, loc)
    else:
        exec("exec result in glob, loc")