From: Mike Bayer Date: Fri, 25 Feb 2011 18:00:54 +0000 (-0500) Subject: - clean up whitespace X-Git-Tag: rel_0_1_0~88 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=7fdf1e342369280883a50aa556378960b06e7e6f;p=thirdparty%2Fsqlalchemy%2Falembic.git - clean up whitespace - can't import sqlalchemy.test anymore --- diff --git a/alembic/command.py b/alembic/command.py index 3a4bff42..c1147593 100644 --- a/alembic/command.py +++ b/alembic/command.py @@ -5,7 +5,7 @@ import functools def list_templates(config): """List available templates""" - + print "Available templates:\n" for tempname in os.listdir(config.get_template_directory()): readme = os.path.join( @@ -14,13 +14,13 @@ def list_templates(config): 'README') synopsis = open(readme).next() print util.format_opt(tempname, synopsis) - + print "\nTemplates are used via the 'init' command, e.g.:" print "\n alembic init --template pylons ./scripts" - + def init(config, directory, template='generic'): """Initialize a new scripts directory.""" - + if os.access(directory, os.F_OK): raise util.CommandError("Directory %s already exists" % directory) @@ -31,7 +31,7 @@ def init(config, directory, template='generic'): util.status("Creating directory %s" % os.path.abspath(directory), os.makedirs, directory) - + versions = os.path.join(directory, 'versions') util.status("Creating directory %s" % os.path.abspath(versions), os.makedirs, versions) @@ -64,7 +64,7 @@ def revision(config, message=None): script = ScriptDirectory.from_config(config) script.generate_rev(util.rev_id(), message) - + def upgrade(config, revision, sql=False): """Upgrade to a later version.""" @@ -75,10 +75,10 @@ def upgrade(config, revision, sql=False): as_sql = sql ) script.run_env() - + def downgrade(config, revision, sql=False): """Revert to a previous version.""" - + script = ScriptDirectory.from_config(config) context.opts( config, @@ -102,10 +102,10 @@ def branches(config): for sc in script.walk_revisions(): if sc.is_branch_point: print sc - + def current(config): """Display the current revision for each database.""" - + script = ScriptDirectory.from_config(config) def display_version(rev): print "Current revision for %s: %s" % ( @@ -113,14 +113,14 @@ def current(config): context.get_context().connection.engine.url), script._get_rev(rev)) return [] - + context.opts( config, fn = display_version - ) + ) script.run_env() - + def splice(config, parent, child): """'splice' two branches, creating a new revision file.""" - - + + diff --git a/alembic/config.py b/alembic/config.py index f8673381..1cbe1f0a 100644 --- a/alembic/config.py +++ b/alembic/config.py @@ -4,17 +4,17 @@ import ConfigParser import inspect import os import sys - + class Config(object): def __init__(self, file_): self.config_file_name = file_ - + @util.memoized_property def file_config(self): file_config = ConfigParser.ConfigParser() file_config.read([self.config_file_name]) return file_config - + def get_template_directory(self): # TODO: what's the official way to get at # setuptools-installed datafiles ? diff --git a/alembic/context.py b/alembic/context.py index 6978bbaa..711d1cd4 100644 --- a/alembic/context.py +++ b/alembic/context.py @@ -22,15 +22,15 @@ _version = Table('alembic_version', _meta, class DefaultContext(object): __metaclass__ = ContextMeta __dialect__ = 'default' - + transactional_ddl = False as_sql = False - + def __init__(self, connection, fn, as_sql=False): self.connection = connection self._migrations_fn = fn self.as_sql = as_sql - + def _current_rev(self): if self.as_sql: if not self.connection.dialect.has_table(self.connection, 'alembic_version'): @@ -39,18 +39,18 @@ class DefaultContext(object): else: _version.create(self.connection, checkfirst=True) return self.connection.scalar(_version.select()) - + def _update_current_rev(self, old, new): if old == new: return - + if new is None: self._exec(_version.delete()) elif old is None: self._exec(_version.insert().values(version_num=literal_column("'%s'" % new))) else: self._exec(_version.update().values(version_num=literal_column("'%s'" % new))) - + def run_migrations(self, **kw): log.info("Context class %s.", self.__class__.__name__) log.info("Will assume %s DDL.", @@ -67,13 +67,13 @@ class DefaultContext(object): if not self.transactional_ddl: self._update_current_rev(prev_rev, rev) prev_rev = rev - + if self.transactional_ddl: self._update_current_rev(current_rev, rev) - + if self.as_sql and self.transactional_ddl: print "COMMIT;\n" - + def _exec(self, construct): if isinstance(construct, basestring): construct = text(construct) @@ -81,24 +81,24 @@ class DefaultContext(object): print unicode(construct.compile(dialect=self.connection.dialect)).replace("\t", " ") + ";" else: self.connection.execute(construct) - + def execute(self, sql): self._exec(sql) - + def alter_column(self, table_name, column_name, nullable=util.NO_VALUE, server_default=util.NO_VALUE, name=util.NO_VALUE, type=util.NO_VALUE ): - + if nullable is not util.NO_VALUE: self._exec(base.ColumnNullable(table_name, column_name, nullable)) if server_default is not util.NO_VALUE: self._exec(base.ColumnDefault(table_name, column_name, server_default)) - + # ... etc - + def add_constraint(self, const): self._exec(schema.AddConstraint(const)) @@ -106,12 +106,12 @@ def opts(cfg, **kw): global _context_opts, config _context_opts = kw config = cfg - + def configure_connection(connection): global _context from alembic.ddl import base _context = _context_impls.get(connection.dialect.name, DefaultContext)(connection, **_context_opts) - + def run_migrations(**kw): _context.run_migrations(**kw) diff --git a/alembic/ddl/base.py b/alembic/ddl/base.py index ff86f1f6..3c50bf12 100644 --- a/alembic/ddl/base.py +++ b/alembic/ddl/base.py @@ -4,10 +4,10 @@ from sqlalchemy.schema import DDLElement class AlterTable(DDLElement): """Represent an ALTER TABLE statement. - + Only the string name and optional schema name of the table is required, not a full Table object. - + """ def __init__(self, table_name, schema=None): self.table_name = table_name @@ -37,7 +37,7 @@ class ColumnDefault(AlterColumn): def __init__(self, name, column_name, default, schema=None): super(ColumnDefault, self).__init__(name, column_name, schema=schema) self.default = default - + class AddColumn(AlterTable): def __init__(self, name, column, schema=None): super(AddColumn, self).__init__(name, schema=schema) @@ -60,7 +60,7 @@ def visit_column_nullable(element, compiler, **kw): def quote_dotted(name, quote): """quote the elements of a dotted name""" - + result = '.'.join([quote(x) for x in name.split('.')]) return result diff --git a/alembic/ddl/mysql.py b/alembic/ddl/mysql.py index 0b60bf2a..f7b7b30d 100644 --- a/alembic/ddl/mysql.py +++ b/alembic/ddl/mysql.py @@ -2,4 +2,4 @@ from alembic.context import DefaultContext class MySQLContext(DefaultContext): __dialect__ = 'mysql' - + diff --git a/alembic/ddl/postgresql.py b/alembic/ddl/postgresql.py index ebd2f00c..79d6f1a0 100644 --- a/alembic/ddl/postgresql.py +++ b/alembic/ddl/postgresql.py @@ -3,4 +3,3 @@ from alembic.context import DefaultContext class PostgresqlContext(DefaultContext): __dialect__ = 'postgresql' transactional_ddl = True - \ No newline at end of file diff --git a/alembic/op.py b/alembic/op.py index d2b1083d..74acb26a 100644 --- a/alembic/op.py +++ b/alembic/op.py @@ -16,7 +16,7 @@ def alter_column(table_name, column_name, type_=util.NO_VALUE ): """Issue ALTER COLUMN using the current change context.""" - + context.alter_column(table_name, column_name, nullable=nullable, server_default=server_default, @@ -38,7 +38,7 @@ def _foreign_key_constraint(name, source, referent, local_cols, remote_cols): name=name ) t1.append_constraint(f) - + return f def _unique_constraint(name, source, local_cols): @@ -56,7 +56,7 @@ def _table(name, *columns, **kw): def _ensure_table_for_fk(metadata, fk): """create a placeholder Table object for the referent of a ForeignKey. - + """ if isinstance(fk._colspec, basestring): table_key, cname = fk._colspec.split('.') diff --git a/alembic/script.py b/alembic/script.py index ede4c050..888d4cae 100644 --- a/alembic/script.py +++ b/alembic/script.py @@ -12,23 +12,23 @@ class ScriptDirectory(object): def __init__(self, dir): self.dir = dir self.versions = os.path.join(self.dir, 'versions') - + if not os.access(dir, os.F_OK): raise util.CommandError("Path doesn't exist: %r. Please use " "the 'init' command to create a new " "scripts folder." % dir) - + @classmethod def from_config(cls, config): return ScriptDirectory( config.get_main_option('script_location')) - + def walk_revisions(self): """Iterate through all revisions. - + This is actually a breadth-first tree traversal, with leaf nodes being heads. - + """ heads = set(self._get_heads()) base = self._get_rev("base") @@ -44,7 +44,7 @@ class ScriptDirectory(object): break else: yield sc - + def _get_rev(self, id_): if id_ == 'head': id_ = self._current_head() @@ -54,7 +54,7 @@ class ScriptDirectory(object): return self._revision_map[id_] except KeyError: raise util.CommandError("No such revision %s" % id_) - + def _revs(self, upper, lower): lower = self._get_rev(lower) upper = self._get_rev(upper) @@ -62,19 +62,19 @@ class ScriptDirectory(object): while script != lower: yield script script = self._revision_map[script.down_revision] - + def upgrade_from(self, destination, current_rev): return [ (script.module.upgrade, script.revision) for script in reversed(list(self._revs(destination, current_rev))) ] - + def downgrade_to(self, destination, current_rev): return [ (script.module.downgrade, script.down_revision) for script in self._revs(current_rev, destination) ] - + def run_env(self): util.load_python_file(self.dir, 'env.py') @@ -99,11 +99,11 @@ class ScriptDirectory(object): map_[rev.down_revision].add_nextrev(rev.revision) map_[None] = None return map_ - + def _rev_path(self, rev_id): filename = "%s.py" % rev_id return os.path.join(self.versions, filename) - + def write(self, rev_id, content): path = self._rev_path(rev_id) file(path, 'w').write(content) @@ -115,7 +115,7 @@ class ScriptDirectory(object): raise Exception("Can't change down_revision on a refresh operation.") self._revision_map[script.revision] = script script.nextrev = old.nextrev - + def _current_head(self): current_heads = self._get_heads() if len(current_heads) > 1: @@ -124,14 +124,14 @@ class ScriptDirectory(object): return current_heads[0] else: return None - + def _get_heads(self): heads = [] for script in self._revision_map.values(): if script and script.is_head: heads.append(script.revision) return heads - + def _get_origin(self): for script in self._revision_map.values(): if script.down_revision is None \ @@ -139,7 +139,7 @@ class ScriptDirectory(object): return script else: return None - + def generate_template(self, src, dest, **kw): util.status("Generating %s" % os.path.abspath(dest), util.template_to_file, @@ -147,12 +147,12 @@ class ScriptDirectory(object): dest, **kw ) - + def copy_file(self, src, dest): util.status("Generating %s" % os.path.abspath(dest), shutil.copy, src, dest) - + def generate_rev(self, revid, message): current_head = self._current_head() path = self._rev_path(revid) @@ -169,30 +169,30 @@ class ScriptDirectory(object): if script.down_revision: self._revision_map[script.down_revision].add_nextrev(script.revision) return script - + class Script(object): nextrev = frozenset() - + def __init__(self, module, rev_id): self.module = module self.revision = rev_id self.down_revision = getattr(module, 'down_revision', None) - + @property def doc(self): return re.split(r"\n\n", self.module.__doc__)[0] def add_nextrev(self, rev): self.nextrev = self.nextrev.union([rev]) - + @property def is_head(self): return not bool(self.nextrev) - + @property def is_branch_point(self): return len(self.nextrev) > 1 - + def __str__(self): return "%s -> %s%s%s, %s" % ( self.down_revision, @@ -200,12 +200,12 @@ class Script(object): " (head)" if self.is_head else "", " (branchpoint)" if self.is_branch_point else "", self.doc) - + @classmethod def from_path(cls, path): dir_, filename = os.path.split(path) return cls.from_filename(dir_, filename) - + @classmethod def from_filename(cls, dir_, filename): m = _rev_file.match(filename) @@ -213,4 +213,3 @@ class Script(object): return None module = util.load_python_file(dir_, filename) return Script(module, m.group(1)) - \ No newline at end of file diff --git a/alembic/util.py b/alembic/util.py index 087e189e..f333bf16 100644 --- a/alembic/util.py +++ b/alembic/util.py @@ -15,7 +15,7 @@ NO_VALUE = util.symbol("NO_VALUE") class CommandError(Exception): pass - + try: width = int(os.environ['COLUMNS']) except (KeyError, ValueError): @@ -48,10 +48,10 @@ def obfuscate_url_pw(u): if u.password: u.password = 'XXXXX' return str(u) - + def warn(msg): warnings.warn(msg) - + def msg(msg, newline=True): lines = textwrap.wrap(msg, width) if len(lines) > 1: @@ -61,7 +61,7 @@ def msg(msg, newline=True): def load_python_file(dir_, filename): """Load a file from the given path as a Python module.""" - + module_id = re.sub(r'\W', "_", filename) path = os.path.join(dir_, filename) module = imp.load_source(module_id, path, open(path, 'rb')) @@ -71,7 +71,7 @@ def load_python_file(dir_, filename): def rev_id(): val = int(uuid.uuid4()) % 100000000000000 return hex(val)[2:-1] - + class memoized_property(object): """A read-only @property that is only evaluated once.""" def __init__(self, fget, doc=None): diff --git a/setup.py b/setup.py index e2813621..2462ba39 100644 --- a/setup.py +++ b/setup.py @@ -13,14 +13,14 @@ def datafiles(): if files: out.append((root, [os.path.join(root, f) for f in files])) return out - + setup(name='alembic', version=VERSION, description="A database migration tool for SQLAlchemy.", long_description="""\ Alembic is an open ended migrations tool. Basic operation involves the creation of script files, -each representing a version transition for one or more databases. +each representing a version transition for one or more databases. The scripts execute within the context of a particular connection and transactional configuration that is explicitly constructed. @@ -49,7 +49,7 @@ Key goals of Alembic are: * The ability to integrate configuration with other frameworks. A Pylons template is included which pulls all configuration from the Pylons project environment. - + """, classifiers=[ 'Development Status :: 3 - Alpha', diff --git a/tests/__init__.py b/tests/__init__.py index 64ebcb5e..60869318 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,4 +1,3 @@ -from sqlalchemy.test.testing import eq_, ne_ from sqlalchemy.util import defaultdict from sqlalchemy.engine import url, default import shutil @@ -14,8 +13,8 @@ def _get_dialect(name): return default.DefaultDialect() else: return _dialects[name] - - + + def assert_compiled(element, assert_string, dialect=None): dialect = _get_dialect(dialect) eq_( @@ -23,6 +22,14 @@ def assert_compiled(element, assert_string, dialect=None): assert_string.replace("\n", "").replace("\t", "") ) +def eq_(a, b, msg=None): + """Assert a == b, with repr messaging on failure.""" + assert a == b, msg or "%r != %r" % (a, b) + +def ne_(a, b, msg=None): + """Assert a != b, with repr messaging on failure.""" + assert a != b, msg or "%r == %r" % (a, b) + def _testing_config(): from alembic.config import Config if not os.access(staging_directory, os.F_OK): @@ -62,21 +69,20 @@ format = %%(levelname)-5.5s [%%(name)s] %%(message)s datefmt = %%H:%%M:%%S """ % (dir_, dir_)) return cfg - + def sqlite_db(): # sqlite caches table pragma info # per connection, so create a new # engine for each assertion dir_ = os.path.join(staging_directory, 'scripts') return create_engine('sqlite:///%s/foo.db' % dir_) - + def staging_env(create=True): from alembic import command, script cfg = _testing_config() if create: command.init(cfg, os.path.join(staging_directory, 'scripts')) return script.ScriptDirectory.from_config(cfg) - + def clear_staging_env(): shutil.rmtree(staging_directory, True) - \ No newline at end of file diff --git a/tests/test_revision_create.py b/tests/test_revision_create.py index 9ad6e03b..6c8163b3 100644 --- a/tests/test_revision_create.py +++ b/tests/test_revision_create.py @@ -14,10 +14,10 @@ def test_002_rev_ids(): abc = util.rev_id() def_ = util.rev_id() ne_(abc, def_) - + def test_003_heads(): eq_(env._get_heads(), []) - + def test_004_rev(): script = env.generate_rev(abc, "this is a message") eq_(script.doc, "this is a message") @@ -26,7 +26,7 @@ def test_004_rev(): assert os.access(os.path.join(env.dir, 'versions', '%s.py' % abc), os.F_OK) assert callable(script.module.upgrade) eq_(env._get_heads(), [abc]) - + def test_005_nextrev(): script = env.generate_rev(def_, "this is the next rev") eq_(script.revision, def_) @@ -40,7 +40,7 @@ def test_005_nextrev(): def test_006_from_clean_env(): # test the environment so far with a # new ScriptDirectory instance. - + env = staging_env(create=False) abc_rev = env._revision_map[abc] def_rev = env._revision_map[def_] @@ -48,10 +48,10 @@ def test_006_from_clean_env(): eq_(abc_rev.revision, abc) eq_(def_rev.down_revision, abc) eq_(env._get_heads(), [def_]) - + def setup(): global env env = staging_env() - + def teardown(): clear_staging_env() \ No newline at end of file diff --git a/tests/test_revision_paths.py b/tests/test_revision_paths.py index c891dab0..c477c0b0 100644 --- a/tests/test_revision_paths.py +++ b/tests/test_revision_paths.py @@ -11,13 +11,13 @@ def setup(): c = env.generate_rev(util.rev_id(), None) d = env.generate_rev(util.rev_id(), None) e = env.generate_rev(util.rev_id(), None) - + def teardown(): clear_staging_env() def test_upgrade_path(): - + eq_( env.upgrade_from(e.revision, c.revision), [ @@ -34,7 +34,7 @@ def test_upgrade_path(): (c.module.upgrade, c.revision), ] ) - + def test_downgrade_path(): eq_( diff --git a/tests/test_schema.py b/tests/test_schema.py index 84bff84d..f5bcb8e3 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -11,14 +11,14 @@ def test_foreign_key(): AddConstraint(fk), "ALTER TABLE t1 ADD CONSTRAINT hoho FOREIGN KEY(foo, bar) REFERENCES t2 (bat, hoho)" ) - + def test_unique_constraint(): uc = op._unique_constraint('uk_test', 't1', ['foo', 'bar']) assert_compiled( AddConstraint(uc), "ALTER TABLE t1 ADD CONSTRAINT uk_test UNIQUE (foo, bar)" ) - + def test_table(): tb = op._table("some_table", @@ -50,7 +50,7 @@ def test_table(): "FOREIGN KEY(foo_id) REFERENCES foo (id), " "FOREIGN KEY(foo_bar) REFERENCES foo (bar))" ) - + m = MetaData() foo = Table('foo', m, Column('id', Integer, primary_key=True)) tb = op._table("some_table", diff --git a/tests/test_versioning.py b/tests/test_versioning.py index bb2f29f7..94065686 100644 --- a/tests/test_versioning.py +++ b/tests/test_versioning.py @@ -8,7 +8,7 @@ def test_001_revisions(): a = util.rev_id() b = util.rev_id() c = util.rev_id() - + script = ScriptDirectory.from_config(cfg) script.generate_rev(a, None) script.write(a, """ @@ -51,8 +51,8 @@ def downgrade(): execute("DROP TABLE bat") """ % b) - - + + def test_002_upgrade(): command.upgrade(cfg, c) db = sqlite_db() @@ -88,7 +88,7 @@ def setup(): global cfg, env env = staging_env() cfg = _sqlite_testing_config() - - + + def teardown(): clear_staging_env() \ No newline at end of file