Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy truncate table with ORM

I have been using orm for my app, and try not to use sql to avoid sql syntax error when changing between different dbms.

At the moment I am testing with sqlite and mysql. I figured out to delete a table we can use:

db.session.query(models.MyTable).delete()

Unfortunately this method does not really "truncate" the table, because It does not reset the counting of autoincrement to 0.

Is there anyway to do the real truncate in SqlAlchemy orm ?

like image 791
w00d Avatar asked Nov 28 '12 15:11

w00d


People also ask

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.

How do I delete a table in flask SQLAlchemy?

Just call drop() against the table object.

How do you clear a table in sqlite?

sqlite> DELETE FROM table_name; Following is the basic syntax of DROP TABLE. sqlite> DROP TABLE table_name; If you are using DELETE TABLE command to delete all the records, it is recommended to use VACUUM command to clear unused space.

Why is SQLAlchemy slow?

At the ORM level, the speed issues are because creating objects in Python is slow, and the SQLAlchemy ORM applies a large amount of bookkeeping to these objects as it fetches them, which is necessary in order for it to fulfill its usage contract, including unit of work, identity map, eager loading, collections, etc.


1 Answers

SQLAlchemy delete(...) method is translated into SQL DELETE FROM query. This query does not resets any AUTO_INCREMENT counters. To reset a counter in MySQL you have to run a query like that:

ALTER TABLE tbl AUTO_INCREMENT = 100;

If I'm not mistaking, it has no analogue in SQLAlchemy.

like image 85
Maksym Polshcha Avatar answered Oct 12 '22 11:10

Maksym Polshcha