Giter Club home page Giter Club logo

pytds's Introduction

pytds

https://secure.travis-ci.org/denisenkom/pytds.png?branch=master https://ci.appveyor.com/api/projects/status/a5h4y29063crqtet?svg=true

Python DBAPI driver for MSSQL using pure Python TDS (Tabular Data Stream) protocol implementation. Doesn't depend on ADO or FreeTDS. Can be used on any platform, including Linux, MacOS, Windows.

It can be used with https://pypi.python.org/pypi/django-sqlserver as a Django database backend.

Features

  • Fully supports new MSSQL 2008 date types: datetime2, date, time, datetimeoffset
  • MARS
  • Bulk insert
  • Table-valued parameters
  • TLS connection encryption
  • Kerberos support on non-Windows platforms (requires kerberos package)

Installation

To install run this command:

$ pip install python-tds

If you want to use TLS you should also install pyOpenSSL package:

$ pip install pyOpenSSL

For a better performance install bitarray package too:

$ pip install bitarray

To use Kerberos on non-Windows platforms (experimental) install kerberos package:

$ pip install kerberos

Documentation

Documentation is available at https://python-tds.readthedocs.io/en/latest/.

Example

To connect to database do

import pytds
with pytds.connect('server', 'database', 'user', 'password') as conn:
    with conn.cursor() as cur:
        cur.execute("select 1")
        cur.fetchall()

To enable TLS you should also provide cafile parameter which should be a file name containing trusted CAs in PEM format.

For detailed documentation of connection parameters see: pytds.connect

pytds's People

Contributors

aersam avatar allaboutmikey avatar chadcatlett avatar denisenkom avatar deronnax avatar diegueus9 avatar jackwotherspoon avatar lhcgreg avatar m32 avatar mariusdkm avatar niconil avatar niphlod avatar quinox avatar radyz avatar sandrotosi avatar shubha-rajan avatar takoau avatar tarper24 avatar terratrue-daniel avatar tpow avatar vflashm avatar zdxerr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytds's Issues

Bulk insert - copy_to

I can't seem to make this to work, looking at the code there are two issues.

1- The table name is formatted between "[ ]" which means you can only send dbo tables and not able to specify any schema

2- For some reason all the column types inserted are nvarchar(4000), and this is probably the reason I'm failing at inserting some int and date columns, I keep getting: OperationalError: Invalid column type from bcp client for colid 1.

Are there any undocumented limitations I am missing?

Support table-value parameters?

Is there any plan to support table-valued parameters?
Currently, I have an process that reads and builds a dataset and then serializes it and stores one row of data at a time in a loop. This was fine when the amount of data was small, but now that I have moved to production I process about 10,000 records the chattiness and the performance of the execution is becoming too slow for a good real time feedback.

pytds fails on string decode (wrong server encoding detection?)

While the MS SQL Server DB's collation is Latin1_General_BIN pytds is trying to use cp1252 collation for decoding which doesn't seem right to me.

Other possible cause is so-known Double Mis-Encoding, which, I guess would be nice to handle to by using either ignore or replace error schema for decoding.

Traceback (most recent call last):
  ...
  File "/usr/lib/python3.4/site-packages/pytds/__init__.py", line 761, in __next__
    row = self.fetchone()
  File "/usr/lib/python3.4/site-packages/pytds/__init__.py", line 734, in fetchone
    row = self._session.fetchone()
  File "/usr/lib/python3.4/site-packages/pytds/tds.py", line 3428, in fetchone
    if not self.next_row():
  File "/usr/lib/python3.4/site-packages/pytds/tds.py", line 3439, in next_row
    self.process_token(marker)
  File "/usr/lib/python3.4/site-packages/pytds/tds.py", line 3390, in process_token
    return handler(self)
  File "/usr/lib/python3.4/site-packages/pytds/tds.py", line 3500, in <lambda>
    TDS_ROW_TOKEN: lambda self: self.process_row(),
  File "/usr/lib/python3.4/site-packages/pytds/tds.py", line 2595, in process_row
    curcol.value = self.row[i] = curcol.type.read(r)
  File "/usr/lib/python3.4/site-packages/pytds/tds.py", line 1143, in read
    return r.read_str(size, self._codec)
  File "/usr/lib/python3.4/site-packages/pytds/tds.py", line 642, in read_str
    return codec.decode(readall(self, size))[0]
  File "/usr/lib/python3.4/encodings/cp1252.py", line 15, in decode
    return codecs.charmap_decode(input,errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 5: character maps to <undefined>

AttributeError: type object 'Float' has no attribute 'from_stream'

I installed django-sqlserver and pytds to work with a database in SQL Server 2005. When I ran the command inspectdb I got this:

  File "/home/diegueus9/dev/whatsup/local/lib/python2.7/site-packages/pytds/tds.py", line 3411, in find_result_or_done
    self.process_token(marker)
  File "/home/diegueus9/dev/whatsup/local/lib/python2.7/site-packages/pytds/tds.py", line 3345, in process_token
    return handler(self)
  File "/home/diegueus9/dev/whatsup/local/lib/python2.7/site-packages/pytds/tds.py", line 3458, in <lambda>
    TDS7_RESULT_TOKEN: lambda self: self.tds7_process_result(),
  File "/home/diegueus9/dev/whatsup/local/lib/python2.7/site-packages/pytds/tds.py", line 2440, in tds7_process_result
    self.get_type_info(curcol)
  File "/home/diegueus9/dev/whatsup/local/lib/python2.7/site-packages/pytds/tds.py", line 2407, in get_type_info
    curcol.type = self.get_type_factory(type_id).from_stream(r)
AttributeError: type object 'Float' has no attribute 'from_stream'

Login error in v1.6.0

connect to sql server 2008 fails. the same code works in v1.5.4

below is code in "test.py"

import argparse

import pytds

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='test connection')
    parser.add_argument('--host', help='db host')
    parser.add_argument('--db', help='db name')
    parser.add_argument('--user', help='db user')
    parser.add_argument('--passwd', help='db password')
    parser.add_argument('--port', type=int, default=1433, help='db port')
    args = parser.parse_args()
    con = pytds.connect(args.host, args.db, args.user, args.passwd, port=args.port)

run it with

python test.py --host host --db dbname --user user --passwd pass

get these error :

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    con = pytds.connect(args.host, args.db, args.user, args.passwd, port=args.port)
  File "/Users/DMT/lib/python2.7/site-packages/pytds/dbapi.py", line 254, in __init__
    self._open()
  File "/Users/DMT/lib/python2.7/site-packages/pytds/dbapi.py", line 166, in _open
    raise err
pytds.tds.LoginError: Invalid instance name

version 1.6.12 error no attribute 'total_seconds' on py2.6

In attempting to use pytds 1.6.12 on Python 2.6 (centos, red hat), we encountered the following error when attempting to establish a connection:

>>> import pytds
>>> print pytds.__version__
1.6.12
>>> conn = pytds.connect('10.1.1.10', 'master', 'sa', 'password')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vagrant/lib/pytds/dbapi.py", line 257, in __init__
    self._open()
  File "/home/vagrant/lib/pytds/dbapi.py", line 169, in _open
    raise err
AttributeError: 'datetime.timedelta' object has no attribute 'total_seconds'

The offending code is actually in tds.py. datetime.timedelta.total_seconds was introduced in Py2.7.

In the current master branch, there is a workaround in tds.py, a total_seconds function that is called that calculates the delta in seconds. Please apply this to the 1.6 release branch and create a new release so that pypi has a working download.

Thanks

DB-API 2.0 places restrictions on types in cursor.description

I learned while comparing the results of a query with the results from pymssql that the cursor.description data structure is required to have objects in the second (type_code) position in each column tuple that compare equal to certain type objects: https://www.python.org/dev/peps/pep-0249/#type-objects-and-constructors.

For my example query, I zip()ed the description attributes of a pymssql cursor (first element) and a pytds cursor (second element) for comparison.

[(('planeID', 3, None, None, None, None, None),
  ('planeID', 127, None, None, None, None, 0)),
 (('obsID', 3, None, None, None, None, None),
  ('obsID', 127, None, None, None, None, 0)),
 (('productID', 1, None, None, None, None, None),
  ('productID', 167, None, 256, None, None, 0)),
 (('metaDataRights', 1, None, None, None, None, None),
  ('metaDataRights', 167, None, 32, None, None, 1)),
 (('metaRelease', 4, None, None, None, None, None),
  ('metaRelease', 61, None, 8, None, None, 1)),
 (('dataRights', 1, None, None, None, None, None),
  ('dataRights', 167, None, 32, None, None, 1)),
 (('dataRelease', 4, None, None, None, None, None),
  ('dataRelease', 61, None, 8, None, None, 1)),
 (('dataProductType', 1, None, None, None, None, None),
  ('dataProductType', 167, None, 32, None, None, 1)),
 (('calibrationLevel', 3, None, None, None, None, None),
  ('calibrationLevel', 56, None, 4, None, None, 1)),
 (('previewURI', 1, None, None, None, None, None),
  ('previewURI', 167, None, 0, None, None, 1)),
 (('productURI', 1, None, None, None, None, None),
  ('productURI', 167, None, 0, None, None, 1)),
 (('prvName', 1, None, None, None, None, None),
  ('prvName', 167, None, 256, None, None, 1)),
 (('prvReference', 1, None, None, None, None, None),
  ('prvReference', 167, None, 0, None, None, 1)),
 (('prvVersion', 1, None, None, None, None, None),
  ('prvVersion', 167, None, 256, None, None, 1)),
 (('prvProject', 1, None, None, None, None, None),
  ('prvProject', 167, None, 256, None, None, 1)),
 (('prvProducer', 1, None, None, None, None, None),
  ('prvProducer', 167, None, 256, None, None, 1)),
 (('prvRunID', 1, None, None, None, None, None),
  ('prvRunID', 167, None, 0, None, None, 1)),
 (('prvLastExecuted', 4, None, None, None, None, None),
  ('prvLastExecuted', 61, None, 8, None, None, 1)),
 (('prvKeywords', 1, None, None, None, None, None),
  ('prvKeywords', 167, None, 0, None, None, 1)),
 (('prvInputs', 1, None, None, None, None, None),
  ('prvInputs', 167, None, 0, None, None, 1)),
 (('posLocationRA', 3, None, None, None, None, None),
  ('posLocationRA', 62, None, 8, None, None, 1)),
 (('posLocationDec', 3, None, None, None, None, None),
  ('posLocationDec', 62, None, 8, None, None, 1)),
 (('posBounds', 2, None, None, None, None, None),
  ('posBounds', 0, None, None, None, None, 1)),
 (('posBoundsSTCS', 1, None, None, None, None, None),
  ('posBoundsSTCS', 167, None, 0, None, None, 1)),
 (('posDimension1', 3, None, None, None, None, None),
  ('posDimension1', 56, None, 4, None, None, 1)),
 (('posDimension2', 3, None, None, None, None, None),
  ('posDimension2', 56, None, 4, None, None, 1)),
 (('posResolution', 3, None, None, None, None, None),
  ('posResolution', 62, None, 8, None, None, 1)),
 (('posSampleSize', 3, None, None, None, None, None),
  ('posSampleSize', 62, None, 8, None, None, 1)),
 (('posTimeDependant', 3, None, None, None, None, None),
  ('posTimeDependant', 50, None, 1, None, None, 1)),
 (('enrValue', 3, None, None, None, None, None),
  ('enrValue', 62, None, 8, None, None, 1)),
 (('enrMin', 3, None, None, None, None, None),
  ('enrMin', 62, None, 8, None, None, 1)),
 (('enrMax', 3, None, None, None, None, None),
  ('enrMax', 62, None, 8, None, None, 1)),
 (('enrBounds', 2, None, None, None, None, None),
  ('enrBounds', 0, None, None, None, None, 1)),
 (('enrBoundsSTCS', 1, None, None, None, None, None),
  ('enrBoundsSTCS', 167, None, 0, None, None, 1)),
 (('enrDimension', 3, None, None, None, None, None),
  ('enrDimension', 56, None, 4, None, None, 1)),
 (('enrResolution', 3, None, None, None, None, None),
  ('enrResolution', 62, None, 8, None, None, 1)),
 (('enrSampleSize', 3, None, None, None, None, None),
  ('enrSampleSize', 62, None, 8, None, None, 1)),
 (('enrResolvingPower', 3, None, None, None, None, None),
  ('enrResolvingPower', 62, None, 8, None, None, 1)),
 (('enrBandpassName', 1, None, None, None, None, None),
  ('enrBandpassName', 167, None, 256, None, None, 1)),
 (('enrEMBand', 1, None, None, None, None, None),
  ('enrEMBand', 167, None, 32, None, None, 1)),
 (('enrTransition', 1, None, None, None, None, None),
  ('enrTransition', 167, None, 256, None, None, 1)),
 (('enrTransitionSpecies', 1, None, None, None, None, None),
  ('enrTransitionSpecies', 167, None, 256, None, None, 1)),
 (('enrRestWavelength', 3, None, None, None, None, None),
  ('enrRestWavelength', 62, None, 8, None, None, 1)),
 (('timValue', 3, None, None, None, None, None),
  ('timValue', 62, None, 8, None, None, 1)),
 (('timMin', 3, None, None, None, None, None),
  ('timMin', 62, None, 8, None, None, 1)),
 (('timMax', 3, None, None, None, None, None),
  ('timMax', 62, None, 8, None, None, 1)),
 (('timBounds', 2, None, None, None, None, None),
  ('timBounds', 0, None, None, None, None, 1)),
 (('timBoundsSTCS', 1, None, None, None, None, None),
  ('timBoundsSTCS', 167, None, 0, None, None, 1)),
 (('timDimension', 3, None, None, None, None, None),
  ('timDimension', 56, None, 4, None, None, 1)),
 (('timResolution', 3, None, None, None, None, None),
  ('timResolution', 62, None, 8, None, None, 1)),
 (('timSampleSize', 3, None, None, None, None, None),
  ('timSampleSize', 62, None, 8, None, None, 1)),
 (('timExposure', 3, None, None, None, None, None),
  ('timExposure', 62, None, 8, None, None, 1)),
 (('plrDimension', 3, None, None, None, None, None),
  ('plrDimension', 56, None, 4, None, None, 1)),
 (('plrState', 1, None, None, None, None, None),
  ('plrState', 167, None, 2, None, None, 1)),
 (('dqFlag', 1, None, None, None, None, None),
  ('dqFlag', 167, None, 32, None, None, 1)),
 (('mtrSourceNumberDensity', 3, None, None, None, None, None),
  ('mtrSourceNumberDensity', 62, None, 8, None, None, 1)),
 (('mtrBackground', 3, None, None, None, None, None),
  ('mtrBackground', 62, None, 8, None, None, 1)),
 (('mtrBackgroundStdDev', 3, None, None, None, None, None),
  ('mtrBackgroundStdDev', 62, None, 8, None, None, 1)),
 (('mtrFluxDensityLimit', 3, None, None, None, None, None),
  ('mtrFluxDensityLimit', 62, None, 8, None, None, 1)),
 (('mtrMagLimit', 3, None, None, None, None, None),
  ('mtrMagLimit', 62, None, 8, None, None, 1)),
 (('recordCreated', 4, None, None, None, None, None),
  ('recordCreated', 61, None, None, None, None, 0)),
 (('recordModified', 4, None, None, None, None, None),
  ('recordModified', 61, None, 8, None, None, 1)),
 (('statusCode', 3, None, None, None, None, None),
  ('statusCode', 56, None, None, None, None, 0))]

automatic rollback on sql2000?

I have some code which accesses a sql 2000 database.
Here's the basics.

cnxn = pytds.connect(server='myserver', database='customers', user='username', password='password', port=1433, tds_version=0x70000000,autocommit=False) #gets an error if i don't set the tds_version - should be automatic and can be fixed 7.1 also works...
cursor = cnxn.cursor()
sql = "UPDATE customer set lastname = @LastName where customerID = @customerID"
params = {'LastName':Wilson,'customerID':123456}
cursor.execute(sql, params)
cnxn.commit()

What happens is the data isn't updated. It's rolled back immediately after executing. After that, PYTDS starts a transaction and then immediately commits it, essentially doing nothing.

The only way to get PYTDS to actually commit is to turn on autocommit. However, I don't want to do that. I want to count the affected rows and then decide if I want to commit. For example in this case, I want to make sure that only one customer was updated. I get that with cursor.rowcount and if it's greater than 1, something went wrong and I need to rollback. What it should do is issue the commit when I say, if the connection is not in autocommit mode. It's instead automatically rolling back everything when it's not in autocommit mode.

Error "'_TdsSession' object has no attribute 'send_cancel'" during Django test database creation

I got this error when Django tries to recreate test database

$ python ./manage.py test -v3

Creating test database for alias 'mssql' ('database_name_test')...
Got an error creating the test database: '_TdsSession' object has no attribute 'send_cancel'
Type 'yes' if you would like to try deleting the test database 'database_name_test', or 'no' to cancel: yes
Destroying old test database 'default'...
Got an error recreating the test database: '_TdsSession' object has no attribute 'send_cancel'

pytds version 1.6.1

Error getting results from TSQL statement

query:

DECLARE @TOTAL_PLAN_CACHE BIGINT, @SINGLE_USE_PLAN_CACHE BIGINT;
SELECT @TOTAL_PLAN_CACHE = SUM(CAST(cp_tot.size_in_bytes AS BIGINT)) FROM sys.dm_exec_cached_plans AS cp_tot WHERE cp_tot.cacheobjtype = N'Compiled Plan';
SELECT @SINGLE_USE_PLAN_CACHE = SUM(CAST(cp_single.size_in_bytes AS BIGINT)) FROM sys.dm_exec_cached_plans AS cp_single
WHERE
    cp_single.cacheobjtype = N'Compiled Plan'
    AND cp_single.objtype IN (N'Adhoc', N'Prepared')
    AND cp_single.usecounts = 1;
SELECT @TOTAL_PLAN_CACHE AS total_plan_cache, @SINGLE_USE_PLAN_CACHE AS single_use_plan_cache, CAST(@SINGLE_USE_PLAN_CACHE AS float) / CAST(@TOTAL_PLAN_CACHE AS float) AS plan_bloat
import pytds
with pytds.connect('server', 'database', 'user', 'password') as conn:
    with conn.cursor() as cur:
        cur.execute(query)
        cur.fetchall()

Results in Previous statement didn't produce any results

However in SSMS (values are different because it's a different server) I get a result:
image

And with the following hack I can get the results I'm looking for:

try:
    tmp = cur.return_value
except Exception:
    pass
print(cur._session.row)

[u'system', 4987691008, 2605195264, 0.5223249114312416]

SQL Express default instance name.

The default instance name of SQL Server Express is 'SQLEXPRESS' rather than 'MSSQLServer'. So, connecting to 'Express' edition of SQL Server without instance name causes 'invalid instance name' error.
This may be a 'read me' issue.

use relative imports always

Hi, I'm trying this module and found out that there are a few places where relative imports are skipped are preventing a successfull connection, if the module is not installed with pip (hence, in sys.path)

e.g. in dbapi.py , there are a few

from pytds.tz import FixedOffsetTimezone

that could be replaced with

from .tz import FixedOffsetTimezone

This should "enable" working with pytds when used as a non-installed package...

reading cursor.return_value breaks fetches

User calls stored procedure with callproc.
Stored procedure returns resultset and return value.
If return value is read before resultset, resultsset is always empty.
It's not clear to me if it can be fixed easily. I suppose it should be at least asserted.

import sys
import pytds

assert len(sys.argv) == 5, 'Provide 4 db connection arguments'

with pytds.connect(*sys.argv[1:]) as connection:
    with connection.cursor() as cursor:
        cursor.execute("""
create proc TestProcedure
as
begin
    select 1 union select 2 union select 3
    select 'a' union select 'b' union select 'c'
    return 9
end
""")
        cursor.callproc('TestProcedure')

        # HERE:        
        # print cursor.return_value # if uncommented, breaks fetchall

        print cursor.fetchall()   # returns 1,2,3
        cursor.nextset()
        print cursor.fetchall()   # returns a,b,c
        print cursor.return_value # returns 9

    connection.rollback()

OUTPUT clause returns wrong result set

when running an execmany query that uses the OUTPUT clause, only one result is returned.
Example:

pytds.connect(**config)
connection.autocommit = True

# test table has only one field name varchar(20)
cursor = connection.cursor()
query = "INSERT INTO [test] (name) OUTPUT inserted.name values (%s)"
cursor.executemany(query, [("mike"), ("john"), ("robert")])

cursor.fetchall() # returns only one element, should return 3 of them

getaddrinfo port parameter type on sock open

Hi, I'm running Django 1.8.7 on Ubuntu, using the master branch of django-sqlserver to connect to a remote SQLServer via pytds.

I was using the released 1.8.2, and ran across an issue. I tried copying the master branch and using it directly and I get the same issue.

Cannot connect to server '<my-sql-server>: getaddrinfo() argument 2 must be integer or string", error('getaddrinfo() argument 2 must be integer or string',)

I put a print on (host, port) on line 282 and both the parameters were there. Guessing there was an issue with the port I put a cast to int in and lo and behold it works fine.

sock = socket.create_connection((host, int(port)), retry_time)

I'm not entirely clear in my mind why that's the case and no one else has run into it as far as I've seen. I'd be happy to make a pull request if you have an idea why this might bubble up now and if it'd be safe for all users of the package.

Thanks!

Passing raw bytes to sql server

Legacy part of my project pipes raw bytes into sql varchars.
My code is written in python2 and I need to ensure interoperability with that code.

pytds has bytes_to_unicode option, but setting it to false does not work as expected.

Example:

con = pytds.connect(<credentials here>, bytes_to_unicode=False)
c = con.cursor()
arg = 'weird chars \xee\xb4\xba'
c.execute('''
set nocount on
declare @a varchar(max) = %s
select @a
''', [arg])
row = c.fetchone()
print repr(arg)
print repr(row[0])

With bytes_to_unicode=True (default) I get following result:

'weird chars \xee\xb4\xba'
u'weird chars ?'

Setting bytes_to_unicode=False fails with exception:

Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    ''', [arg])
  File "pytds/__init__.py", line 634, in execute
    self._execute(operation, params)
  File "pytds/__init__.py", line 615, in _execute
    self._exec_with_retry(lambda: self._session.submit_rpc(
  File "pytds/__init__.py", line 563, in _exec_with_retry
    return fun()
  File "pytds/__init__.py", line 618, in <lambda>
    0))
  File "pytds/tds.py", line 3273, in submit_rpc
    param.type.write(w, param.value)
  File "pytds/tds.py", line 1434, in write
    val, _ = self._codec.encode(val)
  File "/opt/python-2.7env/lib/python2.7/encodings/cp1252.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_table)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xee in position 12: ordinal not in range(128)

Current implementation of bytes_to_unicode seems to be rather useless.
I'd say it should not try to encode input and should pass it as it is to the database.
I propose one simple change to achieve that:
In tds.py, in method VarCharMax.write

-            val = force_unicode(val)
-            val, _ = self._codec.encode(val)
+            if isinstance(val, unicode):
+                val, _ = self._codec.encode(val)

Result after the change:

'weird chars \xee\xb4\xba'
u'weird chars \xee\xb4\xba'

Still not perfect (I'd prefer it to return non-unicode string), but at least it works.

I'm not sure if this change affects anything else (I'm having troubles running test suite).
Please let me know what you think.

I'm having troubles running test suite, but still can make a pull request if necessary.

server login - make instance name check case insensitive

Instance names on MSSQL are typically in upper case. However they are case insensitive on Windows. With pytds the code that checks that the instance name is valid on the server performs the check case-sensitive.

dbapi.py, line 137:

instances = tds7_get_instances(login.server_name)
if login.instance_name not in instances:
    raise LoginError("Instance {0} not found on server {1}".format(login.instance_name, login.server_name))

maybe something along these lines:

if login.instance_name.upper() not in (i.upper() for i in instances):

AppEngine support

Great library.... would be even better to have this official support/work the Google AppEngine environment.

I have already made changes to get it going but not sure how to submit a pull request for you. Basically you need to modify the tds.py to

  1. USE_CORK = False (AppEngine doesn't support TCP_CORK)
  2. Convert bytearray to str for _sock.sendall in _write method (AppEngine doesn't support bytearray)

Version number inconsistent

Pip says I have 1.7.3.1 installed, but python import pytds; help(pytds) reports 1.7.0. I think this is due to the version in init.py. Perhaps it needs to pull something from version.py?

Calling a procedure that yields multiple result sets and has a transaction fails.

I'm trying to call a procedure that does some work and returns multiple result sets. But cursor.callproc fails with the following error message when you try to iterate the results.

OperationalError: Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0.

Here is an example stored procedure to try this with.

create procedure transaction_test_sp
as

begin tran
    if not exists (select 1 from sys.objects o where object_id = object_id('__t') and type='U')
        create table __t(
            a int
        )
    insert into __t 
    output inserted.*
    values (1)
    insert into __t
    output inserted.*
    values (2)
rollback tran

error: unpack_from requires a buffer of at least 8 bytes

This appears to be a duplicate of #37, but since that issue is closed and doesn't appear to be getting any attention, here I am. If someone reopens #37 and provides a real fix, please close this. ๐ŸŽ‰

Using a recent version of master from github source newer than the release in pypi is supposed to resolve this issue, but I intermittently get this error from pytds:

...
  File "create-budget.py", line 165, in execute
    return cur.fetchall()
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/__init__.py", line 790, in fetchall
    return list(row for row in self)
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/__init__.py", line 790, in <genexpr>
    return list(row for row in self)
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/__init__.py", line 793, in __next__
    row = self.fetchone()
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/__init__.py", line 766, in fetchone
    row = self._session.fetchone()
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/tds.py", line 1586, in fetchone
    if not self.next_row():
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/tds.py", line 1597, in next_row
    self.process_token(marker)
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/tds.py", line 1545, in process_token
    return handler(self)
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/tds.py", line 1664, in <lambda>
    tds_base.TDS_NBC_ROW_TOKEN: lambda self: self.process_nbcrow(),
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/tds.py", line 734, in process_nbcrow
    value = curcol.serializer.read(r)
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/tds_types.py", line 394, in read
    return self.subtypes[size].read(r)
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/tds_types.py", line 1255, in read
    days, t = r.unpack(self._struct)
  File "/Users/bsmith/.virtualenvs/sqlserver/lib/python3.6/site-packages/pytds/tds.py", line 167, in unpack
    return struc.unpack_from(buf, offset)
struct.error: unpack_from requires a buffer of at least 8 bytes

Usually the first few operations (selects, inserts, deletes) to the database succeed, but sometimes unpredictably a random subsequent operation will fail with that error.

I've tried setting an arbitrarily large login_timeout value (currently at 1200) on the connect call (as a possible fix suggested in #37), but that doesn't seem to make any difference.

Also, it shouldn't make any difference, but I'm establishing the connection and cursors as context managers like this:

with pytds.connect(**db_args) as conn:
    # magic happens here

error when trying to use in web2py

so I wanted to use pytds in web2py so that i can switch my web2py instance to pypy. So I changed the dal.py to connect using pytds (in the appropriate place)...

 def connector(cnxn=cnxn,driver_args=driver_args):
        return self.driver.connect(server=host,database=db,user=user,password=password,port=1433,     tds_version=0x70000000,autocommit=False)

that seems to be the right place to change it. I get a ticket (web2py's tracebacks) that says this:

Traceback (most recent call last):
File "C:\Temp\web2py_src\web2py\gluon\restricted.py", line 220, in restricted
exec ccode in environment
File "C:/Temp/web2py_src/web2py/applications/test/models/db.py", line 15, in
db = DAL('mssql://user:pass@server/tgtest',pool_size=1)
File "C:\Temp\web2py_src\web2py\gluon\dal.py", line 7868, in init
raise RuntimeError("Failure to connect, tried %d times:\n%s" % (attempts, tb))
RuntimeError: Failure to connect, tried 5 times:
Traceback (most recent call last):
File "C:\Temp\web2py_src\web2py\gluon\dal.py", line 7846, in init
self._adapter = ADAPTERSself._dbname
File "C:\Temp\web2py_src\web2py\gluon\dal.py", line 688, in call
obj = super(AdapterMeta, cls).call(_args, *_kwargs)
File "C:\Temp\web2py_src\web2py\gluon\dal.py", line 3455, in init
if do_connect: self.reconnect()
File "C:\Temp\web2py_src\web2py\gluon\dal.py", line 669, in reconnect
self.connection = f()
File "C:\Temp\web2py_src\web2py\gluon\dal.py", line 3452, in connector
return self.driver.connect(server=host,database=db,user=user,password=password,port=1433, tds_version=0x70000000,autocommit=False)
File "C:\Python27\lib\site-packages\pytds\dbapi.py", line 264, in init
self._open()
File "C:\Python27\lib\site-packages\pytds\dbapi.py", line 175, in _open
raise err
AttributeError: '_TdsSession' object has no attribute 'login'

I can't see anywhere that a _TdsSession object is being used, so i have no idea what to fix.

Support SSL

When I try to connect to Windows Azure SQL, it raises the following exception:

AttributeError: '_TdsSession' object has no attribute '_sock'

Changing line 3199 on file tds.py from:

self._sock = ssl.wrap_socket(self._sock, ssl_version=ssl.PROTOCOL_SSLv3)

to:

self._sock = ssl.wrap_socket(self._transport._sock, ssl_version=ssl.PROTOCOL_SSLv3)

Solves the issue. But then I get the following error:

ssl.SSLError: [Errno 8] _ssl.c:507: EOF occurred in violation of protocol

Has anyone had success when connecting to Azure using pytds?

fetchall() after UPDATE operation throws pytds.tds.Error

Hello,

When we call cursor.fetchall() after cursor.execute() an UPDATE operation, pytds throws an exception of type pytds.tds.Error.
Shouldn't it throw pytds.OperationalError? Because such cases fall under Operational Errors?

Thank you.

Doesn't support AlwaysOn

pytds does not support AlwaysOn for high availability ms sql servers.
It would be a great help if the same can be added.

Thank you.

python3 str error

Calling connect() without specifying 'port' causes an error in Python 3.

import pytds
conn = pytds.connect(server,db,user,password)
...
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pytds/tds.py", line 3681, in tds7_get_instances
s.sendto('\x03', (ip_addr, 1434))
TypeError: 'str' does not support the buffer interface

Version = 1.6.11

Cannot fetch results ("InterfaceError: Invalid type id 240")

I'm trying to use pytds with a Microsoft SQL Server 2012 database containing a table with a column of type geometry. Trying to fetch the results of a query including that column results in: InterfaceError: ('Invalid type id', 240). The ID 240 corresponds to the system_type_id for the geometry and geography types in sys.types, so I suspect the geometry column is the culprit.

(For what it's worth, pymssql seems to handle this query, though perhaps not in a very friendly way.)

With this code:

c.execute("SELECT TOP 1 * FROM CaomPlane;")
c.fetchall()
---------------------------------------------------------------------------
InterfaceError                            Traceback (most recent call last)
<ipython-input-81-6c71b5cabee4> in <module>()
----> 1 c.execute("SELECT TOP 1 * FROM CaomPlane;")
      2 c.fetchall()

/Users/jlong/lib/python3.6/site-packages/pytds/__init__.py in execute(self, operation, params)
    627         conn = self._assert_open()
    628         conn._try_activate_cursor(self)
--> 629         self._execute(operation, params)
    630 
    631     def _begin_tran(self, isolation_level):

/Users/jlong/lib/python3.6/site-packages/pytds/__init__.py in _execute(self, operation, params)
    616         else:
    617             self._exec_with_retry(lambda: self._session.submit_plain_query(operation))
--> 618         self._session.find_result_or_done()
    619         self._setup_row_factory()
    620 

/Users/jlong/lib/python3.6/site-packages/pytds/tds.py in find_result_or_done(self)
   3802             marker = self.get_token_id()
   3803             if marker == TDS7_RESULT_TOKEN:
-> 3804                 self.process_token(marker)
   3805                 return True
   3806             elif marker in (TDS_DONE_TOKEN, TDS_DONEPROC_TOKEN, TDS_DONEINPROC_TOKEN):

/Users/jlong/lib/python3.6/site-packages/pytds/tds.py in process_token(self, marker)
   3737         if not handler:
   3738             self.bad_stream('Invalid TDS marker: {0}({0:x})'.format(marker))
-> 3739         return handler(self)
   3740 
   3741     def get_token_id(self):

/Users/jlong/lib/python3.6/site-packages/pytds/tds.py in <lambda>(self)
   3854     TDS_CAPABILITY_TOKEN: lambda self: self.process_msg(TDS_CAPABILITY_TOKEN),
   3855     TDS_PARAM_TOKEN: lambda self: self.process_param(),
-> 3856     TDS7_RESULT_TOKEN: lambda self: self.tds7_process_result(),
   3857     TDS_ROW_TOKEN: lambda self: self.process_row(),
   3858     TDS_NBC_ROW_TOKEN: lambda self: self.process_nbcrow(),

/Users/jlong/lib/python3.6/site-packages/pytds/tds.py in tds7_process_result(self)
   2709             curcol = Column()
   2710             info.columns.append(curcol)
-> 2711             self.get_type_info(curcol)
   2712 
   2713             #

/Users/jlong/lib/python3.6/site-packages/pytds/tds.py in get_type_info(self, curcol)
   2669         type_class = self._tds._type_map.get(type_id)
   2670         if not type_class:
-> 2671             raise InterfaceError('Invalid type id', type_id)
   2672         curcol.type = type_class.from_stream(r)
   2673 

InterfaceError: ('Invalid type id', 240)

For comparison, I tried pymssql:

c.execute("SELECT TOP 1 * FROM CaomPlane;")
c.fetchall()
[(1000000000,
  1000000000,
  '2391589660720627712',
  'PUBLIC',
  datetime.datetime(2012, 2, 2, 22, 24, 14),
  'PUBLIC',
  datetime.datetime(2012, 2, 2, 22, 24, 14),
  'image',
  2,
  'http://galex.stsci.edu/data/GR7/pipe/01-vsn/02437-NGA_NGC5398_580_F5_19_158/d/01-main/0007-img/07-try/qa/NGA_NGC5398_580_F5_19_158-xd-int_2color.jpg',
  None,
  'NGS',
  None,
  None,
  'NGS',
  'CALTECH',
  None,
  None,
  None,
  None,
  210.542232477159,
  -32.6804067553693,
  b'A\x96\x01\x00\x01\x04&\x00\x00\x00\xb9\xc4O\xeb\xcfV@\xc0\xe1C\x89\x96\x1cij@\x9d\xa4T\x1dMI@\xc0A\xa1\x1a\x06\xbehj@\xa5k\xc3\xb41<@\xc0\xf4x\xce\xd4\xb3gj@A\x04$\xb3\xdd/@\xc0\xee\xb8<1\x06fj@\xb4\xf0\x8a\x1a\xab$@\xc0\xe9\x1a\x1c\xdb\xc1cj@\xd5#\rn\xeb\x1a@\xc0\x04\xa7\xa1\xba\xf7`j@1\xc5$u\xe5\x12@\xc0Q~Z^\xbc]j@X`]O\xd3\x0c@\xc0|\xb9\xecc\'Zj@K\x06\xdb\xe3\xe0\x08@\xc02\xe3\xd0\xcfRVj@ }\xb4\xb4*\x07@\xc0"\xf4\x1aXZRj@X\x87\xab\x1c\xbd\x07@\xc0\x8df\x9f\xa6ZNj@\x14\xa1\t\xfb\x93\n@\xc0\xa7\x020\x96pJj@F\xf8\x0f\xd0\x9a\x0f@\xc0\x11\xb5\xe1n\xb8Fj@\x18\xb4\x0cH\xad\x16@\xc0\xa3\xc0L%MCj@\x94\xf2\xbd3\x98\x1f@\xc0\x84\xb6b\xa0G@j@\xferw\xe7\x1a*@\xc0\xf1\x1bW\n\xbe=j@\xdc\xaf+\xfb\xe85@\xc0\x15\x87;0\xc3;j@fA0`\xacB@\xc0\xe7\xbb\xc6\xf4e:j@\xcc\x87\x14\xc1\x07P@\xc0\xfa\x86x\xda\xb09j@p\xe4G\x1d\x99]@\xc0q\x7f&\xa9\xa99j@\x1a\xb1G\x8f\xfcj@\xc0\x8b\x0f\x1e3Q:j@\xae\x11\xa0*\xcfw@\xc0A\xea\x1b=\xa3;j@\xabJ2\xdd\xb1\x83@\xc0\x08.\x03\x8c\x96=j@\xd3ZE=L\x8e@\xc03G\xc1\x19\x1d@j@\xe9b\x91.O\x97@\xc0\xa9y\x1ar$Cj@\xc9`\xdeFw\x9e@\xc0^\\\x915\x96Fj@o\xc1)\xde\x8e\xa3@\xc0\x10K\xda\xbfXJj@\xd33\x9c\xb6o\xa6@\xc0\xa7]\xa7\xecONj@u\x84_,\x04\xa7@\xc0\x8a\x98L\xf4]Rj@d\xad\xc2\xe2G\xa5@\xc05c\x8fXdVj@\xf9\xd74\xe7G\xa1@\xc0\xb2\x16<\xd8DZj@*\xd1iH"\x9b@\xc0L\xf0\x97`\xe2]j@\xda\xc0F\'\x05\x93@\xc0\xfbn\x04\xf3!aj@\x90\x80\xb8H-\x89@\xc0E\xe4\xcbv\xebcj@2\xfd\xb77\xe4}@\xc0\xb6\xe7do*fj@\x9c\x81\x99\x08~q@\xc0\x06V\xa3\x91\xcegj@\xdf\xa6\xdc\xd0Vd@\xc0\xc1\xb2\xca3\xcchj@\xb9\xc4O\xeb\xcfV@\xc0\xe1C\x89\x96\x1cij@\x01\x00\x00\x00\x02\x00\x00\x00\x00\x01\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00\x03',
  'CIRCLE ICRS 210.54223248 -32.68040676 0.625',
  3840,
  3840,
  None,
  1.5,
  None,
  235.0,
  169.3,
  300.7,
  b'\x00\x00\x00\x00\x01\x14\x9a\x99\x99\x99\x99)e@\x00\x00\x00\x00\x00\x00\x00\x0033333\xcbr@\x00\x00\x00\x00\x00\x00\x00\x00',
  'RANGE 169.3 300.7',
  None,
  None,
  None,
  None,
  'NUV',
  'UV',
  None,
  None,
  None,
  52797.213206,
  52797.21005787037,
  52797.21635416667,
  b'\x00\x00\x00\x00\x01\x14\x08\x8e\xcb\xb8\xa6\xc7\xe9@\x00\x00\x00\x00\x00\x00\x00\x00K9_\xec\xa6\xc7\xe9@\x00\x00\x00\x00\x00\x00\x00\x00',
  'RANGE 52797.210058 52797.216354',
  1,
  544.0,
  544.0,
  544.0,
  None,
  None,
  None,
  None,
  None,
  None,
  None,
  None,
  datetime.datetime(2015, 8, 9, 19, 20, 55, 507000),
  datetime.datetime(2016, 8, 25, 20, 7, 41, 833000),
  -1)]

Cannot build 1.8.0 with python-3.4 from pypi zip

Got following

$ python3.4 setup.py build
Traceback (most recent call last):
  File "setup.py", line 8, in <module>
    version=version.get_git_version(),
  File "/tmp/python-tds-1.8.0/version.py", line 90, in get_git_version
    raise ValueError("Cannot find the version number!")
ValueError: Cannot find the version number!

I think the problem is that there is no .git directory in pypi zip:

>>> from subprocess import Popen, PIPE
>>> p = Popen(['git', 'describe', '--abbrev=%d' % 4],stdout=PIPE, stderr=PIPE)
>>> p.stdout.readlines()
[]
>>> p.stderr.readlines()
[b'fatal: Not a git repository (or any of the parent directories): .git\n']

In read_release_version()

>>> f = open("RELEASE-VERSION", "r")
>>> version = f.readlines()[0]
>>> version
'1.8.0\n'
>>> version.strip().decode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'

exception thrown NULL value in parameter dictonary for INSERT

setting a named parameter to NULL results in exception:

ok, so this is working for me now by using %s in the query and a tuple for the parameter values

I'm still not understanding how it is supposed to work with using a dictionary for parameters

Please provide sample code of cursor.execute(sql, parameters) where parameters is a dictionary

readonly parameter of connect() doesn't seem to work correctly

I would expect this to set the applicationintent parameter in the connection string, but I'm not sure how to see the actual connection string and I get this error:

pytds.tds.OperationalError: The target database ('DATABASE') is in an availability group and is currently accessible for connections when the application intent is set to read only.

Is there something else that needs to be done?

cursor._session is None when iterating over cursor directly

When running something like:

with pytds.connect(as_dict=True, **settings.mssql) as conn:
    with conn.cursor() as cursor:
        cursor.callproc(self.SP_NAME)
        for row in cursor:
            print(row)

I'm getting a 'NoneType' object has no attribute 'fetchone' from the _session being None

> /usr/lib/python3.5/site-packages/pytds/__init__.py(744)fetchone()
-> row = self._session.fetchone()
(Pdb) self._session is None
True

For now, the workaround is to iterate over cursor.fetchall(), but I think iterating over the cursor directly should not raise that exception

Would really like a new release of pytds!

EDIT: It seems I was mistaken, and passing a NULL VARBINARY is supported in the current released version of pytds. It just isn't documented in that version. Even still, a new release of pytds would be appreciated!

The latest version of pytds on pypi is great, but doesn't support passing NULL for VARBINARY parameters. The new version seems to (see below). Would it be possible to get a release to pypi of the latest code?

# Must explicitly indicate the column is binary in order to pass NULL for VARBINARY
pytds.Column(type=pytds.VarBinaryMax())

Is there a better/cleaner way to achieve this?

Note that not passing something like this for a VARBINARY parameter will result in the following error:

pytds.tds.OperationalError: Implicit conversion from data type nvarchar to varbinary is not allowed. Use the CONVERT function to run this query.

Add support for sending parameters as varchar (either via switch or type based)

The make_param method never will make a parameters type varchar.
This is problematic as if you are using a query that seeks against an indexed varchar column, sql server will opt to convert the column to nvarchar rather than converting the parameter to varchar.
e.g.

select *
from my_table
where name = @name --name is a varchar(50)

Should use the index on name, but will not. I will have to explicitly convert the parameter to varchar.

I propose that if the type of the parameter sent in is str use varchar, varchar(max) or text. And if the type is unicode use nvarchar, nvarchar(max) or ntext

Finally, MS-SQL default type is int not nvarchar. If I pass None as a parameter it should be encoded as an int. This is minor point.
proof::

select null [a] into __t
select column_name,data_type from information_schema.columns where table_name='__t'

Missing values when retrieving row as dictionary

When using pytds to retrieve rows as dictionaries from a SQL Server 2008 R2 system, I ran into a problem where the values in the returned dictionary were all None.

The patch shown here seems to fix the bug:

seibert@8e6d857

However, I have no idea if this is an appropriate fix in general. I am happy to issue a pull request if this is the right approach.

as_dict flag on connection causes cursor fetch methods to have values that are none.

The processrow method never updates column.value as a result the dictionaries produced always have a value of None.
A potentional fix in tds.py line 2543::

    def process_row(self):
        r = self._reader
        info = self.res_info
        info.row_count += 1
        for i, curcol in enumerate(info.columns):
            curcol.value = self.row[i] = curcol.type.read(r)

That way curcol.value is populated, so that the dictionary has a usable result set.

gaierror(-2, 'Name or service not known') when try to connect to db

How I use pytds is like this:

import pytds as db_module

def tryConnect():

    db_conn = {
          'dsn': 'datahost\myplace',
          'database': 'dev',
          'user': 'dwapp',
          'password': '****'
     }

    db = db_module.connect(**db_conn)

And I'm getting:

Cannot connect to server 'datahost': [Errno -2] Name or service not known, gaierror(-2, 'Name or service not known')

The code snippet works locally because I have set datahost in my /etc/hosts, but when I running it on docker, even if I manually add the datahost to docker using docker run -i --add-host before running this test, I still got this error. I know this error is related to the environment, but is there anything else I left? @denisenkom any help?

does not support DSN

Needs to support DSN syntax. Otherwise it's not dbapi 2.0 compliant.

I would suggest you use dsnparse as that will make it easy.

Add support for TDS 5, Sybase, maybe

I am having a problem by trying to connect to a database url and port, maybe I'm making it wrong, I try the follow

with pytds.connect('132.248.205.170:4101', 'act_firma_tit', '#mypassword') as conn:

and I got this error

pytds.tds.LoginError: ("Cannot connect to server '132.248.205.170:4101': [Errno 11001] getaddrinfo failed", gaierror(11001, 'getaddrinfo failed'))

How can I connect correctly?

Error in v 1.7.3.1

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/home/pierovbg/workspace/crm-actors/actors/presentation/cli/management/commands/convert_profiles.py", line 18, in handle
    get_external_updates_processor().process_external_updates(converter)
  File "/home/pierovbg/workspace/crm-actors/actors/domain/external_updates/processor.py", line 29, in process_external_updates
    new_updates = self._repository.get_updates_after(last_processed)
  File "/home/pierovbg/workspace/crm-actors/actors/persistence/external_updates/update_repository.py", line 57, in get_updates_after
    return map(ExternalAccountUpdateDescription.fill_from_object, updates)
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/db/models/query.py", line 141, in __iter__
    self._fetch_all()
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/db/models/query.py", line 966, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/db/models/query.py", line 265, in iterator
    for row in compiler.results_iter():
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/db/models/sql/compiler.py", line 700, in results_iter
    for rows in self.execute_sql(MULTI):
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/db/models/sql/compiler.py", line 1156, in cursor_iter
    sentinel):
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/db/models/sql/compiler.py", line 1155, in <lambda>
    for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)),
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/django/db/utils.py", line 101, in inner
    return func(*args, **kwargs)
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/pytds/__init__.py", line 749, in fetchmany
    row = self.fetchone()
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/pytds/__init__.py", line 734, in fetchone
    row = self._session.fetchone()
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/pytds/tds.py", line 3428, in fetchone
    if not self.next_row():
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/pytds/tds.py", line 3439, in next_row
    self.process_token(marker)
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/pytds/tds.py", line 3390, in process_token
    return handler(self)
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/pytds/tds.py", line 3500, in <lambda>
    TDS_ROW_TOKEN: lambda self: self.process_row(),
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/pytds/tds.py", line 2595, in process_row
    curcol.value = self.row[i] = curcol.type.read(r)
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/pytds/tds.py", line 929, in read
    return r.get_int()
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/pytds/tds.py", line 623, in get_int
    return self.unpack(_int_le)[0]
  File "/home/pierovbg/.venvs/actors/lib/python3.3/site-packages/pytds/tds.py", line 611, in unpack
    return struct.unpack_from(buf, offset)
struct.error: unpack_from requires a buffer of at least 4 bytes

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.