question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to disconnect from db and drop all tables?

See original GitHub issue

Hi, currently I am covering flask app with unit tests and I need to initialize database before each test starts and drop database after test is finished. But seems like there is no “easy” way to do it with PonyORM.

What I want is something like how it works with sqlalchemy http://pythonhosted.org/Flask-Testing/:

from flask.ext.testing import TestCase

from myapp import create_app, db

class MyTest(TestCase):

    SQLALCHEMY_DATABASE_URI = "sqlite://"
    TESTING = True

    def create_app(self):

        # pass in test configuration
        return create_app(self)

    def setUp(self):

        db.create_all()

    def tearDown(self):

        db.session.remove()
        db.drop_all()

Please advice: how can I disconnect from db and delete it? Is it possible?

Issue Analytics

  • State:closed
  • Created 10 years ago
  • Comments:13 (7 by maintainers)

github_iconTop GitHub Comments

2reactions
kozlovskycommented, Oct 24, 2013

I just added some methods which you can find useful:

  • db.drop_all_tables(with_all_data=True) - allows to delete all Pony-related tables from the database;
  • db.create_tables() - creation of missing tables, indexes and foreign keys;
  • db.drop_table('name'), MyEntity.drop_table(), MyEntity.my_collection.drop_table() - drop a specific table;
  • db.disconnect() - close the database connection for the current thread if it is opened

Also, you can now generate mapping without generating the tables:

  • db.generate_mapping(create_tables=True) - usual way, create tables if missed;
  • db.generate_mapping() - assuming tables are already created, check if existing tables look good;
  • db.generate_mapping(check_tables=False) - neither create nor check tables, useful if you plan to call db.create_tables() later.

Now I want to show how tests can be written using this functionality. In this example I write two test functions (“create order” and “delete order”) for pony.orm.examples.estore example:

from datetime import datetime
import unittest

from pony.orm import db_session, sql_debug, count

# This file contains entities that we want to test
from pony.orm.examples import estore
sql_debug(False)  # disable debug output so SQL queries don't spam our console

class TestExample(unittest.TestCase):

    def setUp(self):
        estore.db.drop_all_tables(with_all_data=True)
        estore.db.create_tables()
        estore.populate_database()

    def tearDown(self):
        pass

    @db_session
    def test_1_create_order(self):
        customer = estore.Customer[1]
        self.assertEquals(customer.name, 'John Smith')

        product = estore.Product[1]
        self.assertEquals(product.name, 'Kindle Fire HD')

        self.assertEquals(count(o for o in estore.Order), 5)

        order = estore.Order(
            customer=customer, total_price=product.price,
            state=estore.CREATED, date_created=datetime.now())

        item = estore.OrderItem(order=order, product=product,
                                price=product.price, quantity=1)

        estore.db.commit()
        self.assertEquals(count(o for o in estore.Order), 6)

    @db_session
    def test_2_delete_order(self):
        self.assertEquals(count(o for o in estore.Order), 5)
        self.assertTrue(estore.Order.exists(id=1))

        order = estore.Order[1]
        order.delete()

        estore.db.commit()
        self.assertEquals(count(o for o in estore.Order), 4)

if __name__ == '__main__':
    unittest.main()

In this example I don’t use the new db.disconnect() function, because it is easier for me to just drop tables in the already existed database. But you also can call db.disconnect(), remove SQLite database file and then call the db.create_tables() command.

Feel free to ask any additional questions or tell me if I’m missing something.

0reactions
sloriacommented, Dec 2, 2013

Thank you for your reponse. You were correct about the cause of the problem. It was fixed by explicitly setting the table names via the _table_ class attribute.

I would expect create_tables and drop_tables to act on the same tables, i.e. if db.create_tables()``createsperson, thendb.drop_all_tables()deletesperson`.

That said, I agree that drop_all_tables should not silently drop tables that have letter cases. I think the error message you suggested is fine.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to drop all tables from a database with one SQL query?
Use the INFORMATION_SCHEMA.TABLES view to get the list of tables. Generate Drop scripts in the select statement and drop it using Dynamic ...
Read more >
MySQL Drop All Tables: How-To With Examples - Database Star
Step 1: Generate a List of Drop Table Statements For All Tables · Step 2: Copy and Paste The Results Into a New...
Read more >
How to drop all tables in MySQL? - TablePlus
First, disable foreign key check: echo "SET FOREIGN_KEY_CHECKS = 0;" > ./temp.sql. Then dump the db with no data and drop all tables:....
Read more >
How to drop all tables in a MySQL database without dropping ...
If you have filesystem access, then just rm -rf databasename/* :). The Drop database statement ...
Read more >
Drop all tables from database command apart from named few
Using such a CURSOR, you can print or execute all the DROP statements: DECLARE cur_del CURSOR FOR SELECT QUOTENAME(SCHEMA_NAME(schema_id))+' ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found