try:
cursor = connection.cursor()
cursor.execute('update m_password set password = :new_password , updater_id = :updater_id_dic , update_date = :update_date_dic where user_cd = :user_cd_dic and del_flg = :del_flag_dic', queryDictionary)
# Commit
connection.commit()
# Close the cursor
cursor.close()
# Close the database connection
connection.close()
return {
'status': "success",
'errorCode': 0,
'errorMessage': json.dumps("")
}
except: cx_Oracle.IntegrityError as e:
errorObj, = e.args
return {
'status': "error",
'errorCode': errorObj.code,
'errorMessage': json.dumps(errorObj.message)
I am trying to update the value of oracle database . Database connection is alright . I can get the value from database . But update the value is not working . It shows success but value is not actually updated . Also there is no error .
also lambda log showing successfully executed . Please check this image
[1]: https://i.stack.imgur.com/PtLdy.png
I am stuck here .It will be really helpful if i get some help .
Thank you.
It's likely that you're getting an error other than an IntegrityError and don't have an explicit error handler for it. This would cause you to continue towards your this is fine return method.
In fact, updating a password shouldn't throw an integrity error at all since you're not operating on something that effects your schema or is effected by a schema constraint. According to the docs:
This exception is raised when the relational integrity of the data is affected. For example, a duplicate key was inserted or a foreign key constraint would fail.
To troubleshoot, I'd start by accepting any error here. Once you've determined what error type you've caught, you can add per exception error handling as needed.
except Exception as e:
errorObj, = e.args
return {
...
Related
We use mongouse version 0.4.2 and have a piece of code that looks like this:
from mongoengine import Document
class Job(Document):
.....
def create_and_save_job(cls, my_data):
try:
j = cls(**my_data)
j.save()
except Exception as e:
if "duplicate unique keys" in e.message:
return
else:
raise
logger.info({"id": j.id, "status": "success"})
We use sentry to capture any exception raised in our code.
We later found out that we logged a lot of id that don't actually exist in the Job collection, and sentry doesn't have any exception related to this.
(something like)
log: {"id": 1234, "status": "success"}
>> db.job.findOne({_id: ObjectId(1234)})
null
What could be causing this? Should we place the save with insert_one and reload after save?
Thanks,
I have the following code to update a url in a table
from mysql.connector import Error
import mysql.connector
def update_url(self, data):
target_url = data['target_url']
try:
cnx = mysql.connector.connect(
host=os.getenv('mysql_host'),
port=os.getenv('mysql_port'),
user=os.getenv('mysql_user'),
password=os.getenv('mysql_password'),
database=os.getenv('mysql_database')
)
# Create Cursor
cur = cnx.cursor(dictionary=True)
# update target_url
cur.execute('''UPDATE client_url_info
SET target_url=%s
WHERE id=%s''', (data['client_id'], target_url))
cnx.commit()
change_url = {
'status': True,
'msg': 'Target URL has been successfully updated'
}
return change_url
except mysql.connector.Error as err:
change_error_url = {
'status': 'MYSQL_ERROR',
'msg': "Failed in MySQL: {}".format(err)
}
return change_error_url
finally:
if (cnx.is_connected()):
cnx.close()
for some reason I can add data and delete data, but when I try to use update it does not work.
based on other questions, the issue could be cause by the missing of commit() which in my case is included in the code.
I don´t know if I´m not looking right, the code seems to be fine and actually returns the successful msg after execution.
Table info:
Is there any other configuration I´m missing?
thanks in advance
One of my view in Django executes save operations on 6-7 tables. I want these transactions to be atomic I,e if the 5th or 6th transaction fail I want to rollback all the previous saves.
The view contains a try-except block to handle the exceptions raised.
It looks something like this:
#transaction.atomic
def my_view(request):
sid = transaction.savepoint()
try:
Table1.save()
Table2.save()
Table3.save()
Table4.save()
Table5.save()
Table6.save()
Table7.save() # This might fail. In case of failure I want to rollback saves from Table1 to Table6
transaction.savepoint_commit(sid)
except Exception as e:
print(str(e))
transaction.savepoint_rollback(sid)
return JsonResponse({"Status": 0, "Data": str(e)})
I've tried the above and Table7.save() has failed and Table1 to Table6 rollback has not happened.
I want to return the JSON response as {"Status": 0, Data: "Error That occurred"} in all the cases.
I don't want to re-raise the exception in except block as done in This link
What should I do to return a proper JSONResponse and rollback everything in case of failure?
As suggested in the link:
transaction.atomic will execute a transaction on the database if your
view produces a response without errors. Because you're catching the
exception yourself, it appears to Django that your view executed just
fine. If you catch the exception, you need to handle it yourself
An alternative approach is to use transaction.atomic inside with (as context manager), which will ensure a commit or rollback (again suggested on the same link and also explained here)
def my_view(request):
try:
with transaction.atomic():
Table1.save()
Table2.save()
Table3.save()
Table4.save()
Table5.save()
Table6.save()
Table7.save() # This might fail. In case of failure I want to rollback saves from Table1 to Table6
except Exception as e:
print(str(e))
return JsonResponse({"Status": 0, "Data": str(e)})
I'm trying to run over a for loop that validates objects and saves them, and I want to fail it all if at least one have failed, but only after going over all the objects. I've tried different approaches, but on all of them - even if there was an exception, at least one object was saved to DB. In the latest version, see below, I'm trying to set
transaction.set_rollback(True)
if at least on exception was raised.
try:
is_failed = False
with transaction.atomic():
for identifier, spec in spec_dict.items():
try:
spec_data = {'title':my_title,
'identifier': identifier,
'updated_by': user_id,
'created_by': user_id
}
serializer = SpecSerializer(data=spec_data)
serializer.is_valid(raise_exception=True)
serializer.save()
except DataError as DE:
print("** in DataError")
is_failed = True
pass
except ValidationError as VE:
print("** in ValidationError")
print(str(VE))
is_failed = True
pass
except Exception as Exc:
print("** inside Exception: " + str(Exc))
is_failed = True
pass
if is_failed:
transaction.set_rollback(True)
except IntegrityError:
print("** inside integrity error")
pass
Seems like the 'set_rollback' doesn't affect the transaction. Worth to mention that all our http requests are wrapped in transaction.
EDIT:
Should transaction.atomic() work for non view functions? Couldn't find answer for that
So, apparently -
transaction.atomic():
is managing the transaction for the 'default' DB by default, unless other DB is mentioned:
transaction.atomic(using='otherDB'):
Since we use more than one DB and the one that I worked on was not set as the default, I was missing the 'using'.
I have a function the a Celery task calls in my Django app that processes each row in a CSV file and tries to insert information from each row into the PostgreSQL database using a model, like so:
reader = csv.DictReader(csvfile, dialect=csv.get_dialect('excel'))
for row_number, row in enumerate(reader):
try:
...
customer, created = Customer.objects.get_or_create(
first_name = row['First Name'],
last_name = row['Last Name'],
email = row['Email'],
account_owner = account_owner
)
...
except Exception, e:
message = "%s: %s\n" % (type(e).__name__, e)
sys.stderr.write("%s\n" % message)
I'm getting the following error at Customer.objects.get_or_create on the first iteration of the loop:
DatabaseError: no such savepoint
And then I'm getting DatabaseError: current transaction is aborted, commands ignored until end of transaction block for each iteration thereafter.
I have successfully inserted (manually with SQL) a record into this table with the same information the script would provide. I have also tried working with savepoints, with no luck:
sid = transaction.savepoint()
customer, created = Customer.objects.get_or_create(
first_name = row['First Name'],
last_name = row['Last Name'],
email = row['Email'],
account_owner = account_owner
)
transaction.savepoint_commit(sid)
This is happening on my dev machine with PostgreSQL 9.1 installed from Homebrew. Obviously the main goal is to fix this issue, but any helpful pointers for debugging the Celery task or locating my Postgres log files would be helpful also.
After doing some more research, it looks like the underlying cause of this is in an IntegrityError which tries to force a savepoint rollback, which doesn't exist anymore. I fix the IntegrityError and I assume the no savepoint issue is fixed. Still would be great to see the IntegrityError immediately as I'm debugging...
Enabled logging using these instructions and I'm seeing that the insert statement generated by the get_or_create violates a foreign key contraint.