Check for database existence, to allow delayed creation

This commit is contained in:
Itai Shirav 2018-08-19 18:02:37 +03:00
parent 32c77ab190
commit acf2f7a189
4 changed files with 19 additions and 4 deletions

View File

@ -4,6 +4,7 @@ Change Log
Unreleased
----------
- Include alias and materialized fields in queryset results
- Check for database existence, to allow delayed creation
v1.0.1
------

View File

@ -90,12 +90,14 @@ class Database(object):
self.username = username
self.password = password
self.readonly = False
self.db_exists = True
self.db_exists = False
self.db_exists = self._is_existing_database()
if readonly:
if not self.db_exists:
raise DatabaseException('Database does not exist, and cannot be created under readonly connection')
self.connection_readonly = self._is_connection_readonly()
self.readonly = True
elif autocreate:
self.db_exists = False
elif autocreate and not self.db_exists:
self.create_database()
self.server_version = self._get_server_version()
# Versions 1.1.53981 and below don't have timezone function
@ -339,6 +341,10 @@ class Database(object):
ver = '1.1.0'
return tuple(int(n) for n in ver.split('.')) if as_tuple else ver
def _is_existing_database(self):
r = self._send("SELECT count() FROM system.databases WHERE name = '%s'" % self.db_name)
return r.text.strip() == '1'
def _is_connection_readonly(self):
r = self._send("SELECT value FROM system.settings WHERE name = 'readonly'")
return r.text.strip() != '0'

View File

@ -148,10 +148,13 @@ class DatabaseTestCase(TestCaseWithData):
db = Database('db_not_here', autocreate=False)
with self.assertRaises(ServerError) as cm:
db.create_table(Person)
exc = cm.exception
self.assertEqual(exc.code, 81)
self.assertEqual(exc.message, "Database db_not_here doesn't exist")
# Now create the database - should succeed
db.create_database()
db.create_table(Person)
db.drop_database()
def test_preexisting_db(self):
db = Database(self.database.db_name, autocreate=False)

View File

@ -58,6 +58,11 @@ class ReadonlyTestCase(TestCaseWithData):
def test_drop_readonly_table(self):
self.database.drop_table(ReadOnlyModel)
def test_nonexisting_readonly_database(self):
with self.assertRaises(DatabaseException) as cm:
db = Database('dummy', readonly=True)
self.assertEqual(cm.exception.message, 'Database does not exist, and cannot be created under readonly connection')
class ReadOnlyModel(Model):
_readonly = True