denisenkom / pytds

Python DBAPI driver for MSSQL using pure Python TDS (Tabular Data Stream) protocol implementation
MIT License
192 stars 53 forks source link

Problem With Rowcount while trying to bulk insert #128

Open naresh561 opened 3 years ago

naresh561 commented 3 years ago

I have a sp

ALTER PROCEDURE [dbo].[sp_select_Test2] @Test [dbo].[TestTableType] READONLY 
AS
    BEGIN
        INSERT INTO dbo.test
        (
            Code,
            Text,
            Type
        ) 
        SELECT Name,
               Name,
               ID
        FROM   @Test        
    END;

I have this code

 def executeSP(self, SPName, params=[]):
        with pytds.connect(self.server, self.dbname, self.user, self.dbpwd) as connection:
            connection.autocommit = True
            # Check how to create Secure query
            with connection.cursor() as cursor:
                try:
                    cursor.callproc(SPName, params)
                    rows = None
                    if(cursor.rowcount < 0):
                        rows = cursor.fetchall()
                    cursor.close()
                    return rows

                except Exception as e:
                    if(self.logger):
                        self.logger.error(
                            "error executeQuery {0}, {1}".format(SPName, e))
                    else:
                        print(e)
dbObj = DBWrapper(DB_NAME, DB_PASSWORD, DB_USERNAME, DB_SERVER)
ipData = [ ["abc", 1],["def", 2],["ghi", 3]]

The Problem occurs when I am trying to call the SP with following code

ipTvp = dbObj.makeTVP('dbo.TestTableType', ipData)
data = dbObj.executeSP('dbo.sp_select_Test2', [ipTvp])

the RowCount is -1 while it should be non negative value. Please help Me, Thank you.

naresh561 commented 3 years ago

I found that in tds.py Line number 707

if done_count_valid:
            self.rows_affected = rows_affected
        else:
            self.rows_affected = -1

is causing the issue

takoau commented 2 years ago

@naresh561 For your reference: MS-TDS: DONEPROC

The DONE_COUNT flag in DONEPROC message is 0, simply states that bulk insert does not returns a row count, so it's natural to have -1 as return value. 0x10: DONE_COUNT. The DoneRowCount value is valid. This is used to distinguish between a valid value of 0 for DoneRowCount or just an initialized variable.