SqlAlchemy query gives outdated data [duplicate] - sqlalchemy

I have a table (MySQL) with a row in it.
I can read it fine with:
self._session.query(Automatic).\
filter(Automatic.do_when <= time()).\
limit(limit).\
all()
However, if I then delete the row from table (with the mysql client or phpMyAdmin), the row is still returned by the code above. I don't know if this is related to the question "How to disable SQLAlchemy caching?".
Edit:
Adding a
self._session.commit()
after makes no difference.

Edit: Adding commit() before reading did the trick, as per eggyal's explanation.
self._session.commit()
self._session.query(Automatic).\
filter(Automatic.do_when <= time()).\
limit(limit).\
all()

Related

SQL query that is bugged in a way I don't understand

I know the title is weird, but I am on that same bug for HOURS.
I have this query
UPDATE tournaments SET password_req_count = password_req_count + 1 WHERE id = 20;
(You can replace 20 by anything, it really does not matter)
This query modifies a timestamp field called start_timestamp by ALWAYS setting it the computers current hour.
And this query is perfectly fine, there's no bug with this :
UPDATE tournaments SET password_req_count = 0 WHERE id = 20;
This was happening in the PHP code until I removed that one query, then it stopped. Then I decided to try it by directly executing the query myself, without PHP, and the bug is still here.
password_req_count is an int (I mean, I checked it, the problem isn't here)
This query does not appear in the query history of MySQL (the one you can get by pressing the "UP" key to remake a query quickly...), and this bug doesn't appear locally (it only appears on my server). Note that I exported my local database to the server's one, so everything is exactly the same there and here.
The MySQL server version was 5.5 on my server and 5.7 at home, I thought this was the problem so I updated it, but absolutely nothing changed. I also googled a lot about this, but I found no topic talking about this subject.
I do have query logs, so I am SURE that there is NOTHING that edits the start_timestamp (except this weird bug obviously). It is not supposed to be edited anyway.
Edit : I just edited the field name to password_request_count because password_req_count already exists in another table. But the bug is still here.
RECAP HERE
Edit 2 : Here is a video because apparently the post is not clear enough. Notice that I can't do the UPDATE query again by pressing the "up" touch, and please also notice that start_timestamp gets edited if I increment password_req_count.
http://www.nx-lab.com/bug.mp4
Edit 3 : Apparently this also happens if I edit other fields (such as top_prize)
There could be a couple of things doing this, one is a trigger on the table. This code will show you if there are any...
SHOW TRIGGERS FROM tournaments;
The other thing, which is the correct answer in this case, is an auto update on the datetime column. This causes the date and time in the column to be updated automatically when there is an update to the table.
You can read more about it here:
https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
If you want to remove to auto update then an ALTER table is required to remove it from the column, from Timestamp without change on update...
ALTER TABLE leads MODIFY added_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Check if rows exist in table

Consider this code. This code inserts the row to the database if it is not found, then only updates it if the row is found. The updateNode() method gives the entity some values based on the user input, so I called it in both cases.
session.beginTransaction();
node = (Node)session.createQuery("from Node").uniqueResult();
if (node == null) {
node = new Node();
updateNode();
session.save(node);
} else {
updateNode();
}
session.getTransaction.commit();
Is there a better way of checking if rows exist in the table aside from using queries?
Is the cat alive or dead? You don't know without checking it, so you'll have to execute the query in the database.
I assume your question is about to avoid writing such a query manually, but rather letting Hibernate do it itself. Then you may want to look at querying by example/prototype.
Regardless of the approach taken, keep concurrency issues in mind though; you may want to apply some unique constraints and/or optimistic/pessimistic locks.
The only way to find out if something already exists in the database is to query it. However you do not need a separate query. You need only one query and not two thanks to mysql's INSERT... ON DUPLICATE KEY UPDATE feature. And it doesn't need any additional java coding either.
If you want to do this with hibernate it will have to be a custom query and you will need to return the inserted row id with LAST_INSERT_ID in your query.

How to use MySQL's REPLACE Syntax in Rails

Can I use REPLACE without patching ActiveRecord or executing raw SQL in Rails 4?
I just want to save a record only if there is no corresponding data in its table.
I know find_or_create_by method but I guess this generates twofold queries, SELECT and INSERT.
If there is another INSERT query between the two, it will fail, right?
Or am I worrying too much? (The system I'm working on is not a mission critical one.)
REPLACE is a MySQL extension to the SQL standard.
As ActiveRecord tries to be database agnostic as much as possible, I don't think adding behaviour of a specific database is a priority... last mention I found of people asking for it was on 2009 Forums.
Anyway, I'm not sure if using REPLACE would be the same as using find_or_create_by.
From MySQL Reference:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
find_or_create_by behaves differently, since it will leave the record as it is, if it already exists:
# File 'activerecord/lib/active_record/relation.rb', line 200
def find_or_create_by(attributes, &block)
find_by(attributes) || create(attributes, &block)
end
Also, as you mentioned, find_or_create_by can have a race condition if you don't use it properly. You should use it like this (from ActiveRecord Documentation):
begin
CreditAccount.find_or_create_by(user_id: user.id)
rescue ActiveRecord::RecordNotUnique
retry
end

Debbuging SQL query

I have a problem debugging some problem.
I started thread in wordpress.stackexchange.com thinking that I get more wordpress related debugging suggestions but went with totally different way.
You can see topic here: https://wordpress.stackexchange.com/questions/123394/some-ways-to-debug-code
with update: DELETE FROM wp_bp_activity WHERE item_id = 0
My Question is SQL related: Can DELETE statement be triggered from something then DELETE query? for example I rememeber having a bad query which was deleting everything. (but that was everything and not an if statment)
So to extend this question: If I search every query with DELETE FROM will I find it for sure? Can this be written differently? Because for now, I can't find it.
TRUNCATE is also used to DELETE all the records from a table.
You can also have some kind of foreign key cascading, that is triggering the delete in that table. More here.
Addicionally, make sure to search on the database also, on triggers and on stored procedures
One other option is that they were updated to a different value than the one you are looking for.

Perl - DBI - MySQL - Easy way to get row id after update?

Is there an easy way to get the id of the row that was affected by an update statement from DBI? In this particular case, it will always be either 0 or 1 row. I didn't want the expense of having to redo the selection part of the query again to get the data, as it is kind of costly.
I am have to do the update first, because otherwise I introduce the possibility of a race-time condition between the select and the update.
You might want to read this related SO topic (I've linked to the answer by #Erwin Brandstetter) -- this is the way I've always handled it.
Depending on your database engine, you are likely to have a SELECT ... FOR UPDATE facility. You should use this to
SELECT ... FOR UPDATE the record you want to update
Save the ID from the record, and do the UPDATE using the ID instead of the original criteria
The MySQL documentation about SELECT ... FOR UPDATE may helps you, working with transactions.