2014-02-26 21:50:36 +01:00
|
|
|
import re
|
|
|
|
import time
|
|
|
|
|
|
|
|
def timed_ddl(db, stmt):
|
|
|
|
print
|
|
|
|
print time.asctime()
|
|
|
|
print stmt
|
|
|
|
t = time.time()
|
|
|
|
db.execute(stmt)
|
|
|
|
delay = time.time() - t
|
|
|
|
print 'Took %.2fs' % (delay,)
|
|
|
|
|
|
|
|
def validate(sql_thingy):
|
|
|
|
# Do basic validation that table/col name is safe.
|
|
|
|
if not re.match('^[a-z][a-z\d_]+$', sql_thingy):
|
|
|
|
raise Exception('Invalid SQL object: %s' % (sql_thingy,))
|
|
|
|
|
2014-03-01 17:20:04 +01:00
|
|
|
def do_batch_update(db, table, cols, vals, batch_size=10000, sleep=0.1):
|
2014-02-26 21:50:36 +01:00
|
|
|
validate(table)
|
2014-03-01 17:20:04 +01:00
|
|
|
for col in cols:
|
|
|
|
validate(col)
|
2014-02-26 21:50:36 +01:00
|
|
|
stmt = '''
|
|
|
|
UPDATE %s
|
2014-03-01 17:20:04 +01:00
|
|
|
SET (%s) = (%s)
|
2014-02-26 21:50:36 +01:00
|
|
|
WHERE id >= %%s AND id < %%s
|
2014-03-01 17:20:04 +01:00
|
|
|
''' % (table, ', '.join(cols), ', '.join(['%s'] * len(cols)))
|
|
|
|
print stmt
|
2014-02-26 21:50:36 +01:00
|
|
|
(min_id, max_id) = db.execute("SELECT MIN(id), MAX(id) FROM %s" % (table,))[0]
|
|
|
|
if min_id is None:
|
|
|
|
return
|
2014-03-01 17:20:04 +01:00
|
|
|
|
|
|
|
print "%s rows need updating" % (max_id - min_id,)
|
2014-02-26 21:50:36 +01:00
|
|
|
while min_id <= max_id:
|
|
|
|
lower = min_id
|
|
|
|
upper = min_id + batch_size
|
|
|
|
print '%s about to update range [%s,%s)' % (time.asctime(), lower, upper)
|
|
|
|
db.start_transaction()
|
2014-03-01 17:20:04 +01:00
|
|
|
params = list(vals) + [lower, upper]
|
|
|
|
db.execute(stmt, params=params)
|
2014-02-26 21:50:36 +01:00
|
|
|
db.commit_transaction()
|
|
|
|
min_id = upper
|
|
|
|
time.sleep(sleep)
|
|
|
|
|
2014-03-01 17:20:04 +01:00
|
|
|
def add_bool_columns(db, table, cols):
|
2014-02-26 21:50:36 +01:00
|
|
|
validate(table)
|
2014-03-01 17:20:04 +01:00
|
|
|
for col in cols:
|
|
|
|
validate(col)
|
2014-02-26 21:50:36 +01:00
|
|
|
coltype = 'boolean'
|
|
|
|
val = 'false'
|
|
|
|
|
2014-03-01 17:20:04 +01:00
|
|
|
stmt = ('ALTER TABLE %s ' % (table,)) \
|
|
|
|
+ ', '.join(['ADD %s %s' % (col, coltype) for col in cols])
|
2014-02-26 21:50:36 +01:00
|
|
|
timed_ddl(db, stmt)
|
|
|
|
|
2014-03-01 17:20:04 +01:00
|
|
|
stmt = ('ALTER TABLE %s ' % (table,)) \
|
|
|
|
+ ', '.join(['ALTER %s SET DEFAULT %s' % (col, val) for col in cols])
|
2014-02-26 21:50:36 +01:00
|
|
|
timed_ddl(db, stmt)
|
|
|
|
|
2014-03-01 17:20:04 +01:00
|
|
|
vals = [val] * len(cols)
|
|
|
|
do_batch_update(db, table, cols, vals)
|
2014-02-26 21:50:36 +01:00
|
|
|
|
|
|
|
stmt = 'ANALYZE %s' % (table,)
|
|
|
|
timed_ddl(db, stmt)
|
|
|
|
|
2014-03-01 17:20:04 +01:00
|
|
|
stmt = ('ALTER TABLE %s ' % (table,)) \
|
|
|
|
+ ', '.join(['ALTER %s SET NOT NULL' % (col,) for col in cols])
|
2014-02-26 21:50:36 +01:00
|
|
|
timed_ddl(db, stmt)
|