File: pymssql.py

package info (click to toggle)
pymssql 0.8.0%2Bdfsg-2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 160 kB
  • ctags: 196
  • sloc: ansic: 877; python: 409; makefile: 5
file content (331 lines) | stat: -rw-r--r-- 8,870 bytes parent folder | download
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""DB-SIG compliant module for communicating with MS SQL servers"""
#***************************************************************************
#                          pymssql.py  -  description
#
#    begin                : 2003-03-03
#    copyright            : (C) 2003-03-03 by Joon-cheol Park
#    email                : jooncheol@gmail.com
#    current developer    : Andrzej Kukula <akukula@gmail.com>
#    homepage             : http://pymssql.sourceforge.net
#
#***************************************************************************
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA  02110-1301  USA
#***************************************************************************

__author__ = "Joon-cheol Park <jooncheol@gmail.com>, Andrzej Kukula <akukula@gmail.com>"
__version__ = '0.8.0'
import _mssql
import types
import string
import time
import datetime

### module constants

# compliant with DB SIG 2.0
apilevel = '2.0'

# module may be shared, but not connections
threadsafety = 1

# this module use extended python format codes
paramstyle = 'pyformat'

#export column type names from _mssql
class DBAPITypeObject:
	def __init__(self,*values):
		self.values = values
	def __cmp__(self,other):
		if other in self.values:
			return 0
		if other < self.values:
			return 1
		else:
			return -1

STRING = DBAPITypeObject(_mssql.STRING)
BINARY = DBAPITypeObject(_mssql.BINARY)
NUMBER = DBAPITypeObject(_mssql.NUMBER)
DATETIME = DBAPITypeObject(_mssql.DATETIME)
DECIMAL = DBAPITypeObject(_mssql.DECIMAL)

### exception hierarchy

class Warning(StandardError):
	pass

class Error(StandardError):
	pass

class InterfaceError(Error):
	pass

class DatabaseError(Error):
	pass

class DataError(DatabaseError):
	pass

class OperationalError(DatabaseError):
	pass

class IntegrityError(DatabaseError):
	pass

class InternalError(DatabaseError):
	pass

class ProgrammingError(DatabaseError):
	pass

class NotSupportedError(DatabaseError):
	pass


### cursor object

class pymssqlCursor:

	def __init__(self, src):
		self.__source = src
		self.description = None
		self.rowcount = -1
		self.arraysize = 1
		self._result = []
		self.__fetchpos = 0
		self.__resultpos = 0

	def close(self):
		self.__source = None
		self.description = None
		self.result = []
		self.rowcount = -1

	def execute(self, operation, params = None):
		# "The parameters may also be specified as list of
		# tuples to e.g. insert multiple rows in a single
		# operation, but this kind of usage is depreciated:
		if params and type(params) == types.ListType and \
					type(params[0]) == types.TupleType:
			self.executemany(operation, params)
		else:
			# not a list of tuples
			self.executemany(operation, (params,))

	def executemany(self, operation, param_seq):
		self.description = None
		self.rowcount = -1
		self.__fetchpos = 0
		self.__resultpos = 0

		# first try to execute all queries
		totrows = 0
		sql = ""
		try:
			for params in param_seq:
				if params != None:
					sql = _quoteparams(operation, params)
				else:
					sql = operation
				#print sql
				ret = self.__source.query(sql)
				if ret == 1:
					self._result = self.__source.fetch_array()
					totrows = totrows + self._result[self.__resultpos][1]
				else:
				    self._result = None
				    raise DatabaseError, "error: %s" % self.__source.errmsg()
		except:
			raise DatabaseError, "internal error: %s" % self.__source.errmsg()

		# then initialize result raw count and description
		if len(self._result[self.__resultpos][0]) > 0:
			self.description = map(lambda (colname,coltype): (colname, coltype, None, None, None, None, None),self._result[self.__resultpos][0])
			self.rowcount = totrows
		else:
			self.description = None
			self.rowcount = self._result[self.__resultpos][1]

	def nextset(self):
		if self._result ==None:
			return 0

		resultlen =len(self._result)
		if resultlen>1 and self.__resultpos+1<resultlen:
			self.__resultpos = self.__resultpos + 1
			return 1
		else:
			return 0

	def fetchone(self):
		ret = self.fetchmany(1)
		if ret: return ret[0]
		else: return None

	def fetchall(self):
		return self._result[self.__resultpos][2][self.__fetchpos:]

	def fetchmany(self, size = None, keep = 1):
		if size == None:
			size = self.arraysize
		if keep == 1:
			self.arraysize = size
		res = self._result
		if res[self.__resultpos][1]==self.__fetchpos:
		    return []
		reslen = len(res[self.__resultpos][2][self.__fetchpos:])
		if reslen < size:
		    size = res[self.__resultpos][1]
		ret = res[self.__resultpos][2][self.__fetchpos:self.__fetchpos+size]
		self.__fetchpos = self.__fetchpos + size
		return ret

	def setinputsizes(self, sizes):
		pass

	def setoutputsize(self, size, col = 0):
		pass

def _quote(x):
	if type(x) == types.StringType:
		x = "'" + string.replace(str(x), "'", "''") + "'"
	elif type(x) in (types.IntType, types.LongType, types.FloatType):
		pass
	elif x is None:
		x = 'NULL'
	# datetime quoting (thanks Jan Finell <jfinell@regionline.fi>)
	# described under "Writing International Transact-SQL Statements" in BOL
	# beware the order: isinstance(x,datetime.date)=True if x is
	# datetime.datetime ! Also round x.microsecond to milliseconds,
	# otherwise we get Msg 241, Level 16, State 1: Syntax error
	elif isinstance(x, datetime.datetime):
		x = "{ts '%04d-%02d-%02d %02d:%02d:%02d.%s'}" % \
			(x.year,x.month, x.day,
			x.hour, x.minute, x.second, x.microsecond / 1000)
	elif isinstance(x, datetime.date):
		x = "{d '%04d-%02d-%02d'}" % (x.year, x.month, x.day)
	# alternative quoting by Luciano Pacheco <lucmult@gmail.com>
	#elif hasattr(x, 'timetuple'):
	#	x = time.strftime('\'%Y%m%d %H:%M:%S\'', x.timetuple())
	else:
		#print "didn't like " + x + " " + str(type(x))
		raise InterfaceError, 'do not know how to handle type %s' % type(x)

	return x

def _quoteparams(s, params):
	if hasattr(params, 'has_key'):
		x = {}
		for k, v in params.items():
			x[k] = _quote(v)
		params = x
	else:
		params = tuple(map(_quote, params))
	return s % params



### connection object

class pymssqlCnx:

	def __init__(self, cnx):
		self.__cnx = cnx
		try:
			self.__cnx.query("begin tran")
			self.__cnx.fetch_array()
		except:
			raise OperationalError, "invalid connection."

	def close(self):
		if self.__cnx == None:
			raise OperationalError, "invalid connection."
		self.__cnx.close()
		self.__cnx = None

	def commit(self):
		if self.__cnx == None:
			raise OperationalError, "invalid connection."
		try:
			self.__cnx.query("commit tran")
			self.__cnx.fetch_array()
			self.__cnx.query("begin tran")
			self.__cnx.fetch_array()
		except:
			raise OperationalError, "can't commit."

	def rollback(self):
		if self.__cnx == None:
			raise OperationalError, "invalid connection."
		try:
			self.__cnx.query("rollback tran")
			self.__cnx.fetch_array()
			self.__cnx.query("begin tran")
			self.__cnx.fetch_array()
		except:
			raise OperationalError, "can't rollback."

	def cursor(self):
		if self.__cnx == None:
			raise OperationalError, "invalid connection."
		try:
			return pymssqlCursor(self.__cnx)
		except:
			raise OperationalError, "invalid connection."



# connects to a database
def connect(dsn = None, user = "sa", password = "", host = ".", database = "master"):
	# first get params from DSN
	dbhost = ""
	dbbase = ""
	dbuser = ""
	dbpasswd = ""
	dbopt = ""
	dbtty = ""
	try:
		params = string.split(dsn, ":")
		dbhost = params[0]
		dbbase = params[1]
		dbuser = params[2]
		dbpasswd = params[3]
		dbopt = params[4]
		dbtty = params[5]
	except:
		pass

	# override if necessary
	if user != "":
		dbuser = user
	if password != "":
		dbpasswd = password
	if database != "":
		dbbase = database
	if host != "":
		dbhost = host

	# empty host is localhost
	if dbhost == "":
		dbhost = "."
	if dbuser == "":
		dbuser = "sa"

	# open the connection
	con = _mssql.connect(dbhost, dbuser, dbpasswd)
	con.select_db(dbbase)
	return pymssqlCnx(con)