1#! /usr/bin/env python 2 3""" 4usage: %(progname)s [args] 5""" 6 7 8# import startscript; startscript.init(__name__) 9import os, sys, string, time, getopt 10from log import * 11 12import odb 13import MySQLdb 14 15class Database(odb.Database): 16 def __init__(self,db, debug=0): 17 odb.Database.__init__(self, db, debug=debug) 18 self.SQLError = MySQLdb.Error 19 20 def escape(self,str): 21 if str is None: return None 22 return MySQLdb.escape_string(str) 23 24 def listTables(self, cursor=None): 25 if cursor is None: cursor = self.defaultCursor() 26 cursor.execute("show tables") 27 rows = cursor.fetchall() 28 tables = [] 29 for row in rows: 30 tables.append(row[0]) 31 return tables 32 33 def listIndices(self, cursor=None): 34 return [] 35 36 def listFieldsDict(self, table_name, cursor=None): 37 if cursor is None: cursor = self.defaultCursor() 38 sql = "show columns from %s" % table_name 39 cursor.execute(sql) 40 rows = cursor.fetchall() 41 42 columns = {} 43 for row in rows: 44 colname = row[0] 45 columns[colname] = row 46 47 return columns 48 49 def alterTableToMatch(self): 50 invalidAppCols, invalidDBCols = self.checkTable() 51 if not invalidAppCols: return 52 53 defs = [] 54 for colname in invalidAppCols.keys(): 55 col = self.getColumnDef(colname) 56 colname = col[0] 57 coltype = col[1] 58 options = col[2] 59 defs.append(self.colTypeToSQLType(colname, coltype, options)) 60 61 defs = string.join(defs, ", ") 62 63 sql = "alter table %s add column " % self.getTableName() 64 sql = sql + "(" + defs + ")" 65 66 print sql 67 68 cur = self.db.defaultCursor() 69 cur.execute(sql) 70 71 72 73