1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 from mediagoblin
.tools
.common
import simple_printer
18 from sqlalchemy
import Table
20 class TableAlreadyExists(Exception):
24 class MigrationManager(object):
26 Migration handling tool.
28 Takes information about a database, lets you update the database
29 to the latest migrations, etc.
32 def __init__(self
, name
, models
, foundations
, migration_registry
, session
,
33 printer
=simple_printer
):
36 - name: identifier of this section of the database
37 - session: session we're going to migrate
38 - migration_registry: where we should find all migrations to
41 self
.name
= unicode(name
)
43 self
.foundations
= foundations
44 self
.session
= session
45 self
.migration_registry
= migration_registry
46 self
._sorted
_migrations
= None
47 self
.printer
= printer
50 from mediagoblin
.db
.models
import MigrationData
52 self
.migration_model
= MigrationData
53 self
.migration_table
= MigrationData
.__table
__
56 def sorted_migrations(self
):
58 Sort migrations if necessary and store in self._sorted_migrations
60 if not self
._sorted
_migrations
:
61 self
._sorted
_migrations
= sorted(
62 self
.migration_registry
.items(),
63 # sort on the key... the migration number
64 key
=lambda migration_tuple
: migration_tuple
[0])
66 return self
._sorted
_migrations
69 def migration_data(self
):
71 Get the migration row associated with this object, if any.
73 return self
.session
.query(
74 self
.migration_model
).filter_by(name
=self
.name
).first()
77 def latest_migration(self
):
79 Return a migration number for the latest migration, or 0 if
80 there are no migrations.
82 if self
.sorted_migrations
:
83 return self
.sorted_migrations
[-1][0]
85 # If no migrations have been set, we start at 0.
89 def database_current_migration(self
):
91 Return the current migration in the database.
93 # If the table doesn't even exist, return None.
94 if not self
.migration_table
.exists(self
.session
.bind
):
97 # Also return None if self.migration_data is None.
98 if self
.migration_data
is None:
101 return self
.migration_data
.version
103 def set_current_migration(self
, migration_number
=None):
105 Set the migration in the database to migration_number
106 (or, the latest available)
108 self
.migration_data
.version
= migration_number
or self
.latest_migration
109 self
.session
.commit()
111 def migrations_to_run(self
):
113 Get a list of migrations to run still, if any.
115 Note that this will fail if there's no migration record for
118 assert self
.database_current_migration
is not None
120 db_current_migration
= self
.database_current_migration
123 (migration_number
, migration_func
)
124 for migration_number
, migration_func
in self
.sorted_migrations
125 if migration_number
> db_current_migration
]
128 def init_tables(self
):
130 Create all tables relative to this package
132 # sanity check before we proceed, none of these should be created
133 for model
in self
.models
:
134 # Maybe in the future just print out a "Yikes!" or something?
135 if model
.__table
__.exists(self
.session
.bind
):
136 raise TableAlreadyExists(
137 u
"Intended to create table '%s' but it already exists" %
138 model
.__table
__.name
)
140 self
.migration_model
.metadata
.create_all(
142 tables
=[model
.__table
__ for model
in self
.models
])
144 def populate_table_foundations(self
):
146 Create the table foundations (default rows) as layed out in FOUNDATIONS
147 in mediagoblin.db.models
149 for Model
, rows
in self
.foundations
.items():
150 self
.printer(u
' + Laying foundations for %s table\n' %
152 for parameters
in rows
:
153 new_row
= Model(**parameters
)
154 self
.session
.add(new_row
)
156 def create_new_migration_record(self
):
158 Create a new migration record for this migration set
160 migration_record
= self
.migration_model(
162 version
=self
.latest_migration
)
163 self
.session
.add(migration_record
)
164 self
.session
.commit()
168 Print out a dry run of what we would have upgraded.
170 if self
.database_current_migration
is None:
172 u
'~> Woulda initialized: %s\n' % self
.name_for_printing())
175 migrations_to_run
= self
.migrations_to_run()
176 if migrations_to_run
:
178 u
'~> Woulda updated %s:\n' % self
.name_for_printing())
180 for migration_number
, migration_func
in migrations_to_run():
182 u
' + Would update %s, "%s"\n' % (
183 migration_number
, migration_func
.func_name
))
187 def name_for_printing(self
):
188 if self
.name
== u
'__main__':
189 return u
"main mediagoblin tables"
191 return u
'plugin "%s"' % self
.name
193 def init_or_migrate(self
):
195 Initialize the database or migrate if appropriate.
197 Returns information about whether or not we initialized
198 ('inited'), migrated ('migrated'), or did nothing (None)
200 assure_migrations_table_setup(self
.session
)
202 # Find out what migration number, if any, this database data is at,
203 # and what the latest is.
204 migration_number
= self
.database_current_migration
206 # Is this our first time? Is there even a table entry for
209 # - create all tables
210 # - create record in migrations registry
211 # - print / inform the user
213 if migration_number
is None:
214 self
.printer(u
"-> Initializing %s... " % self
.name_for_printing())
217 # auto-set at latest migration number
218 self
.create_new_migration_record()
219 self
.printer(u
"done.\n")
220 self
.populate_table_foundations()
221 self
.set_current_migration()
224 # Run migrations, if appropriate.
225 migrations_to_run
= self
.migrations_to_run()
226 if migrations_to_run
:
228 u
'-> Updating %s:\n' % self
.name_for_printing())
229 for migration_number
, migration_func
in migrations_to_run
:
231 u
' + Running migration %s, "%s"... ' % (
232 migration_number
, migration_func
.func_name
))
233 migration_func(self
.session
)
234 self
.set_current_migration(migration_number
)
235 self
.printer('done.\n')
239 # Otherwise return None. Well it would do this anyway, but
244 class RegisterMigration(object):
246 Tool for registering migrations
250 @RegisterMigration(33)
251 def update_dwarves(database):
254 This will register your migration with the default migration
255 registry. Alternately, to specify a very specific
256 migration_registry, you can pass in that as the second argument.
258 Note, the number of your migration should NEVER be 0 or less than
259 0. 0 is the default "no migrations" state!
261 def __init__(self
, migration_number
, migration_registry
):
262 assert migration_number
> 0, "Migration number must be > 0!"
263 assert migration_number
not in migration_registry
, \
264 "Duplicate migration numbers detected! That's not allowed!"
266 self
.migration_number
= migration_number
267 self
.migration_registry
= migration_registry
269 def __call__(self
, migration
):
270 self
.migration_registry
[self
.migration_number
] = migration
274 def assure_migrations_table_setup(db
):
276 Make sure the migrations table is set up in the database.
278 from mediagoblin
.db
.models
import MigrationData
280 if not MigrationData
.__table
__.exists(db
.bind
):
281 MigrationData
.metadata
.create_all(
282 db
.bind
, tables
=[MigrationData
.__table
__])
285 def inspect_table(metadata
, table_name
):
286 """Simple helper to get a ref to an already existing table"""
287 return Table(table_name
, metadata
, autoload
=True,
288 autoload_with
=metadata
.bind
)