Added Database.does_table_exist method

This commit is contained in:
Itai Shirav 2018-08-19 18:20:17 +03:00
parent 378cae88bc
commit 44d3dcee34
3 changed files with 15 additions and 0 deletions

View File

@ -5,6 +5,7 @@ Unreleased
----------
- Include alias and materialized fields in queryset results
- Check for database existence, to allow delayed creation
- Added `Database.does_table_exist` method
v1.0.1
------

View File

@ -134,6 +134,15 @@ class Database(object):
raise DatabaseException("You can't drop system table")
self._send(model_class.drop_table_sql(self))
def does_table_exist(self, model_class):
'''
Checks whether a table for the given model class already exists.
Note that this only checks for existence of a table with the expected name.
'''
sql = "SELECT count() FROM system.tables WHERE database = '%s' AND name = '%s'"
r = self._send(sql % (self.db_name, model_class.table_name()))
return r.text.strip() == '1'
def insert(self, model_instances, batch_size=1000):
'''
Insert records into the database.

View File

@ -179,3 +179,8 @@ class DatabaseTestCase(TestCaseWithData):
instance = Model1.objects_in(self.database)[0]
self.assertEquals(instance.to_dict(), dict(system='s', readonly='r'))
def test_does_table_exist(self):
class Person2(Person):
pass
self.assertTrue(self.database.does_table_exist(Person))
self.assertFalse(self.database.does_table_exist(Person2))