File: odb_mysql.py

package info (click to toggle)
clearsilver 0.10.5-7
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 3,304 kB
  • sloc: ansic: 24,586; python: 4,233; sh: 2,502; cs: 1,429; ruby: 819; java: 735; makefile: 589; perl: 120; lisp: 34; sql: 21
file content (72 lines) | stat: -rwxr-xr-x 1,614 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#! /usr/bin/env python

"""
usage: %(progname)s [args]
"""


# import startscript; startscript.init(__name__)
import os, sys, string, time, getopt
from log import *

import odb
import MySQLdb

class Database(odb.Database):
  def __init__(self,db, debug=0):
    odb.Database.__init__(self, db, debug=debug)
    self.SQLError = MySQLdb.Error
    
  def escape(self,str):
    if str is None: return None
    return MySQLdb.escape_string(str)

  def listTables(self, cursor=None):
    if cursor is None: cursor = self.defaultCursor()
    cursor.execute("show tables")
    rows = cursor.fetchall()
    tables = []
    for row in rows:
      tables.append(row[0])
    return tables

  def listIndices(self, cursor=None):
    return []

  def listFieldsDict(self, table_name, cursor=None):
    if cursor is None: cursor = self.defaultCursor()
    sql = "show columns from %s" % table_name
    cursor.execute(sql)
    rows = cursor.fetchall()

    columns = {}
    for row in rows:
      colname = row[0]
      columns[colname] = row

    return columns

  def alterTableToMatch(self):
    invalidAppCols, invalidDBCols = self.checkTable()
    if not invalidAppCols: return

    defs = []
    for colname in invalidAppCols.keys():
      col = self.getColumnDef(colname)
      colname = col[0]
      coltype = col[1]
      options = col[2]
      defs.append(self.colTypeToSQLType(colname, coltype, options))

    defs = string.join(defs, ", ")

    sql = "alter table %s add column " % self.getTableName()
    sql = sql + "(" + defs + ")"

    print sql

    cur = self.db.defaultCursor()
    cur.execute(sql)