From 44d3dcee34af1917f39785f3b9eb997ffcd4d49a Mon Sep 17 00:00:00 2001 From: Itai Shirav Date: Sun, 19 Aug 2018 18:20:17 +0300 Subject: [PATCH] Added `Database.does_table_exist` method --- CHANGELOG.md | 1 + src/infi/clickhouse_orm/database.py | 9 +++++++++ tests/test_database.py | 5 +++++ 3 files changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad7f613..e3e68f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ------ diff --git a/src/infi/clickhouse_orm/database.py b/src/infi/clickhouse_orm/database.py index 9c47ef5..b6018a9 100644 --- a/src/infi/clickhouse_orm/database.py +++ b/src/infi/clickhouse_orm/database.py @@ -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. diff --git a/tests/test_database.py b/tests/test_database.py index 00dcc93..4028247 100644 --- a/tests/test_database.py +++ b/tests/test_database.py @@ -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))