1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 """
18 ======================
19 MySQL adpater driver
20 ======================
21
22 MySQL adapter driver.
23
24 :Variables:
25 `adapter` : ``module``
26 The database adapter
27 """
28 __author__ = u"Andr\xe9 Malo"
29 __docformat__ = "restructuredtext en"
30
31 import MySQLdb as _mysql
32 from MySQLdb.constants import CLIENT as _mysql_flags
33
34 from wtf import util as _wtf_util
35 from wtf.ext.db import _exceptions
36
37 adapter = _mysql
38
39
41 """
42 Get this module
43
44 :Return: The module
45 :Rtype: ``module``
46 """
47 return _wtf_util.load_dotted(__name__)
48
49
51 """
52 Is a particular integrity error a unique violation?
53
54 :Parameters:
55 `e` : `Exception`
56 DB-API exception instance
57
58 :Return: Is it?
59 :Rtype: ``bool``
60 """
61 return isinstance(e, adapter.IntegrityError) and e.args[0] == 1062
62
63
65 """
66 Translate exception to wtf.ext DBAPI exception
67
68 The new exception is raised.
69 """
70 _exceptions.translate(adapter)
71
72
74 """
75 Set autocommit
76
77 :Parameters:
78 `value` : ``bool``
79 yes or no?
80 """
81 connection.autocommit(int(bool(value)))
82
83
85 """
86 Start transaction
87 """
88 cur = connection.cursor()
89 try:
90 cur.execute('START TRANSACTION')
91 finally:
92 cur.close()
93
94
100
101
107
108
110 """
111 Connect to database ``dbname``
112
113 The following config options are recognized:
114
115 ``host`` : ``str``
116 DB host
117 ``port`` : ``int``
118 DB port
119 ``user`` : ``str``
120 Username for login
121 ``passwd`` : ``str``
122 Password for login
123 ``db`` : ``str``
124 Database to connect to
125
126 The following keyword arguments are recognized:
127
128 ``use_unicode`` : ``bool``
129 Use unicode? Default: True.
130
131 :Parameters:
132 `conf` : ``dict``
133 Connection options
134
135 `kwargs` : ``dict``
136 Additional parameters for the connect
137
138 :Return: new connection
139 :Rtype: DB-API connection
140
141 :Exceptions:
142 - `DBConfigurationError` : Configuration error
143 """
144 args = dict((key, conf[key])
145 for key in ('host', 'port', 'user', 'passwd', 'db') if key in conf
146 )
147 args['client_flag'] = (
148 _mysql_flags.MULTI_STATEMENTS
149 | _mysql_flags.MULTI_RESULTS
150 | _mysql_flags.FOUND_ROWS
151 )
152 args['use_unicode'] = bool(kwargs.get('use_unicode', True))
153 args['charset'] = 'utf8'
154 if 'port' in args:
155 args['port'] = int(args['port'])
156 if args['host'] == 'localhost':
157 args['host'] = '127.0.0.1'
158 if 'passwd' in args and callable(args['passwd']):
159 args['passwd'] = args['passwd']()
160 try:
161 return _mysql.connect(**args)
162 finally:
163 args['passwd'] = 'XXXXX'
164