Could not change transaction status (0) (SQLSetConnectAttr) - sql-server

We have a Django app connected to a remote SQL-server database.
I get an error when i try to do an update request on a database table :
[HY000] [FreeTDS][SQL Server]Could not change transaction status (0) (SQLSetConnectAttr).
I conclude that a similar request is still in progress and it blocks all my requests.
1/ The "autocommit" parameter is True.
2/ I tested :
connection.rollback()
This did not resolve the problem.
3/ I tried to do a live SQL query on the database.
My query returns no error.
It's a problem with Django or the libraries used.
Traceback :
/venv/src/django-pyodbc-azure/sql_server/pyodbc/base.pyc in
_set_autocommit(self, autocommit)
361 else:
362 self.connection.rollback()
--> 363 self.connection.autocommit = autocommit
364
365 def check_constraints(self, table_names=None):
Error: ('HY000', '[HY000] [FreeTDS][SQL Server]Could not change transaction status (0) (SQLSetConnectAttr)')
Does someone have an idea ?

The problem is fixed.
I remove the following line:
if not ModelName.objects.filter(pk=instance.pk)
My code :
#receiver(pre_save, sender=ModelName)
def model_name_pre_save(sender, instance, **kwargs):
if not ModelName.objects.filter(pk=instance.pk):
instance.field_name = value

Related

pyodbc+mssql connection possible but query fails

The following code is running into a Docker container. I have a connection specified as follow which is working as I could make a simple query based on it.
from sqlalchemy import create_engine
engine = create_engine("mssql+pyodbc://username:pw#hostname?driver_name")
con_xpf = engine.connect()
con_xpf.execute("use db_name;")
After that I create a sqlite3 DB and connect to it:
DBNAME = "data/NEWDB.db"
con = sqlite3.connect(DBNAME)
tbllist = ["AAAAA","BBBBBBBB","CCCCCCCCC","DDDDDDDDD","EEEEEEEEE"
"FFFFFFFFF","GGGGGGGGG","HHHHHH","IIIIIIIII"]
chunksizes = [500000,800000,500000,1000000,500000,500000,500000,900000,500000]
The problem start from here when I try to run the following code to query from the first DB to write into the sqlite DB:
def loads_data_from_xpf(tbllist,chunksizes) :
for tbl,chunksize in zip(tbllist,chunksizes) :
cnt = 0
maxcnt = math.ceil(pd.read_sql("SELECT COUNT(*) CNT FROM x.{}".format(tbl),con_xpf).CNT[0]/chunksize)
with tqdm(range(maxcnt)) as pbar:
for chunk in pd.read_sql("SELECT * FROM x.{} A".format(tbl),con_xpf,chunksize=chunksize) :
chunk.to_sql(tbl,con,if_exists="append")
pbar.update()
loads_data_from_xpf(tbllist,chunksizes)
I got the following error:
OperationalError: (pyodbc.OperationalError) ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x71 (113) (SQLGetData)')
(Background on this error at: http://sqlalche.me/e/13/e3q8)
Could the problem be because of the size of the query? Do you see any error somewhere? I am stuck for a while. Any help would be appreciated.
EDIT
I am now able to see the sqlite DB file updating meaning data are pushed into it. But I have the following error which is because of the Jupyter Kernel. Help please
Traceback (most recent call last):
File "/home/airflow/.local/lib/python3.6/site-packages/nbclient/client.py", line 841, in async_execute_cell
exec_reply = await self.task_poll_for_reply
concurrent.futures._base.CancelledError
During handling of the above exception, another exception occurred:
nbclient.exceptions.DeadKernelError: Kernel died

Teradata Database TeraJDBC 16.20.00.04 Error 3610 SQLState HY000 Internal error: Please do not resubmit the last request

Im requesting a report in the form of excel in my application. The application generates a report by running several(31) sql tasks, everytime i submit a request. But for a particular request the execution of 28th task doesnt complete and throws the below error.
[Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request. SubCode, CrashCode: 0, 2693
01/28/2020 10:35:28,586 ERROR com.xxxx.yyyy.zz.Runner:generateBasicReport:174 - java.sql.SQLException: [Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request. SubCode, CrashCode: 0, 2693
com.xxxx.yyyy.zz.exception.ReportGenerationException: java.sql.SQLException: [Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request. SubCode, CrashCode: 0, 2693
at com.xxxx.yyyy.zz.generator.task.CancellableSqlTask.execute(CancellableSqlTask.java:79)
at com.xxxx.yyyy.zz.generator.task.TaskExecutor.executeNext(TaskExecutor.java:56)
at com.xxxx.yyyy.zz.generator.ReportGenerator.executeTasks(ReportGenerator.java:119)
at com.xxxx.yyyy.zz.generator.ReportGenerator.execute(ReportGenerator.java:83)
at com.xxxx.yyyy.zz.generator.task.CompositeCancellableTask.execute(CompositeCancellableTask.java:32)
at com.xxxx.yyyy.zz.Runner.executeGeneration(Runner.java:209)
at com.xxxx.yyyy.zz.Runner.generateBasicReport(Runner.java:171)
at com.xxxx.yyyy.zz.Runner.generateReports(Runner.java:137)
at com.xxxx.yyyy.zz.Runner.startReportGenerator(Runner.java:92)
at com.xxxx.yyyy.zz.Runner.main(Runner.java:69)
Caused by: java.sql.SQLException: [Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request. SubCode, CrashCode: 0, 2693
at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDatabaseSQLException(ErrorFactory.java:309)
at com.teradata.jdbc.jdbc_4.statemachine.ReceiveInitSubState.action(ReceiveInitSubState.java:103)
at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.subStateMachine(StatementReceiveState.java:311)
at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.action(StatementReceiveState.java:200)
at com.teradata.jdbc.jdbc_4.statemachine.StatementController.runBody(StatementController.java:137)
at com.teradata.jdbc.jdbc_4.statemachine.PreparedStatementController.run(PreparedStatementController.java:46)
at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:389)
at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:331)
at com.teradata.jdbc.jdbc_4.TDPreparedStatement.doPrepExecuteUpdate(TDPreparedStatement.java:225)
at com.teradata.jdbc.jdbc_4.TDPreparedStatement.executeUpdate(TDPreparedStatement.java:2769)
at com.xxxx.yyyy.zz.generator.task.CancellableUpdate.perform(CancellableUpdate.java:36)
at com.xxxx.yyyy.zz.generator.task.CancellableSqlTask.execute(CancellableSqlTask.java:74)
... 9 more
That means that the request caused some exception that Teradata couldn't handle, and like the message says, "don't re-submit". You could try digging into the logs, but I don't know how fruitful that will be. I think they are somewhere in /var/opt/teradata/. Otherwise, you'd have to check with customer support to debug.
From the documentation:
2693 The fieldids in field 5 are not contiguous.
Explanation: The field descriptors in field 5 should be contiguous, they are not.
Generated By: FldLocat.
For Whom: Site support representative.
Notes: This is caused by an incorrect field 5 header.
Remedy: Contact your Support Representative.

Error running transactions on HANA database

I am running bulk transactions on HANA database and getting following error:
2018-01-15 10:23:33,865 ERROR c.c.t.Payment [tpcc-thread-5] UPDATE district SET d_ytd = d_ytd + 1601.0 WHERE d_w_id = 1 AND d_id = 1
com.sap.db.jdbc.exceptions.JDBCDriverException: SAP DBTech JDBC: [138]: transaction serialization failure: TrexUpdate failed on table 'SYSTEM:DISTRICT' with error: transaction order error, rc=4614
at com.sap.db.jdbc.exceptions.SQLExceptionSapDB._newInstance(SQLExceptionSapDB.java:193)
.......
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
2018-01-15 10:23:34,139 ERROR c.c.t.Payment [tpcc-thread-5] Payment error
java.lang.Exception: Payment update transaction error
Anybody has any idea what could be wrong?
I found out that this was a valid error. For transaction type REPEATABLE_READ or SERIALIZABLE this problem can occur when before end of one transaction, another transaction modifies the same data which transaction one was working on.
To get rid of this error, we can use transaction type READ_COMMITTED, which takes a snapshot of the data at the beginning and uses the same data throughout the transaction. It will also lock the rows its working on so that other transactions cannot modify it.

sqlalchemy: '<' not supported between instances of 'str' and 'int' for table schema attribute (pyodbc)

I am trying to retrieve a table from an MSSQL server (using a DSN)
I have this code:
engine=sqlalchemy.create_engine('mssql+pyodbc://MATRIX')
md=sqlalchemy.MetaData()
tsk = sqlalchemy.Table('MATRIX_SMSIMA', md, autoload=True, autoload_with=engine, schema='USER')
Initially, I tried it without the schema attribute and got an error message that pyodbc doesn't support a default schema.
When adding the schema attribute I get an error message that seems to stem from the guts of the Table function:
in _compile(element, compiler, **kw)
39 def _compile(element, compiler, **kw):
40 from . import base
---> 41 if compiler.dialect.server_version_info < base.MS_2005_VERSION:
42 return compiler.process(element.bindvalue, **kw)
43 else:
TypeError: '<' not supported between instances of 'str' and 'int'
Is there a way around this?
OK, I have just found that the application I'm connecting to is working with InterSystems Cache SQL and not with MS SQL, so this is a false alarm

django-pyodbc and pervasive database

Hi There is a way to use django-pyodbc with pervasive database ? I try different settings but when I try to inspectdb to create a model from the database it shows me this error but I can create querys in pervasive with python pyodbc.
`('42000', '[42000] [Pervasive][ODBC Client Interface][LNA][Pervasive][ODBC
Engine Interface]Invalid SET statement. (0) (SQLExecDirectW)')
Request Method: GET
Request URL:
Django Version: 1.6.6
Exception Type: ProgrammingError
Exception Value:
('42000', '[42000] [Pervasive][ODBC Client Interface][LNA][Pervasive][ODBC Engine Interface]Invalid SET statement.
(0) (SQLExecDirectW)')
Exception Location: C:\Python27\lib\site-packages\django_pyodbc\base.py in _cursor, line 296
Python Executable: C:\Python27\python.exe
Python Version: 2.7.8
cursor.execute("SET DATEFORMAT Ymd; SET DATEFIRST %s" % self.datefirst)
pyodbc.ProgrammingError: ('42000', '[42000] [Pervasive][ODBC Client Interface][LNA][Pervasive] [ODBC Engine Interface]Invalid SET statement. (0) (SQLExecDirectW)')`
and this is the piece of the error when I try to run inspectdb on the database.
According to the main problem is in this file base.py line 296 is some problem with a set statement on the odbc driver this is piece of the code on base.py I try to comment but after another thing shows up.
`cursor.execute("SET DATEFORMAT Ymd; SET DATEFIRST %s" % self.datefirst)
if self.ops.sql_server_ver < 2005:
self.creation.data_types['TextField'] = 'ntext'
self.features.can_return_id_from_insert = False
ms_sqlncli = re.compile('^((LIB)?SQLN?CLI|LIBMSODBCSQL)')
self.drv_name = self.connection.getinfo(Database.SQL_DRIVER_NAME).upper()
# http://msdn.microsoft.com/en-us/library/ms131686.aspx
if self.ops.sql_server_ver >= 2005 and ms_sqlncli.match(self.drv_name) and self.MARS_Connection:
# How to to activate it: Add 'MARS_Connection': True
# to the DATABASE_OPTIONS dictionary setting
self.features.can_use_chunked_reads = True`
Try put single quote around %s:
cursor.execute("SET DATEFORMAT Ymd; SET DATEFIRST '%s'" % self.datefirst)
Check your access rights. The error message indicates a syntax error but according to mssql support site, error code 42000 is either "Syntax error or access violation".

Resources