23 from __future__
import with_statement
24 from contextlib
import closing
35 def __init__(self, host, database, user, port=3306, password=None):
41 if self.
host is not None and self.
port is not None and \
42 DbAuth.available(self.
host, str(self.
port)):
44 password = DbAuth.password(self.
host, str(self.
port))
45 elif not os.path.exists(os.path.join(os.environ[
'HOME'],
".my.cnf")):
46 password = getpass.getpass(
"%s's MySQL password: " % user)
55 if password
is not None:
58 def createDb(self, database, options=['-vvv']):
59 if not isinstance(database, basestring):
60 raise TypeError(
'database name is not a string')
63 cmd += [
'-e',
'CREATE DATABASE %s;' % database]
64 subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
68 def execStmt(self, stmt, stdout=sys.stdout, options=['-vvv']):
69 if not isinstance(stmt, basestring):
70 raise TypeError(
'SQL statement is not a string')
76 subprocess.check_call(cmd, stdout=stdout, stderr=sys.stderr)
81 if not isinstance(script, basestring):
82 raise TypeError(
'Script file name is not a string')
83 if not os.path.isfile(script):
85 'Script %s does not exist or is not a file' % script)
86 with open(script,
'rb')
as f:
91 subprocess.check_call(cmd, stdin=f,
92 stdout=sys.stdout, stderr=sys.stderr)
97 if not isinstance(query, basestring):
98 raise TypeError(
'Query is not a string')
99 with closing(self.
getConn())
as conn:
100 with closing(conn.cursor())
as cursor:
103 cursor.execute(query)
104 return cursor.fetchall()
107 with closing(self.
getConn())
as conn:
108 with closing(conn.cursor())
as cursor:
109 cursor.execute(
'SELECT COUNT(*) FROM information_schema.tables '
110 'WHERE table_schema=%s AND table_name=%s AND '
111 'table_type=\'VIEW\'', (self.
database, table))
112 return cursor.fetchone()[0] == 1
115 with closing(self.
getConn())
as conn:
116 with closing(conn.cursor())
as cursor:
117 cursor.execute(
'SELECT COUNT(*) FROM information_schema.tables '
118 'WHERE table_schema=%s AND table_name=%s',
120 return cursor.fetchone()[0] == 1
124 if self.
host is not None:
125 kw[
'host'] = self.
host
126 if self.
port is not None:
127 kw[
'port'] = self.
port
128 if self.
user is not None:
129 kw[
'user'] = self.
user
134 return sql.connect(**kw)
138 if not isinstance(parser, argparse.ArgumentParser):
139 raise TypeError(
'Expecting an argparse.ArgumentParser')
140 defUser = (os.environ.has_key(
'USER')
and os.environ[
'USER'])
or None
142 "--user", default=defUser, dest=
"user",
143 help=
"MySQL database user name (%(default)s).")
145 "--host", default=
"lsst10.ncsa.uiuc.edu", dest=
"host",
146 help=
"MySQL database server hostname (%(default)s).")
148 "--port", default=3306, type=int, dest=
"port",
149 help=
"MySQL database server port (%(default)d).")