Skip to content

Commit

Permalink
dbconfig: support the case where the db is not initialized
Browse files Browse the repository at this point in the history
Instead of just crashing, return the default value or KeyError

buildbot db init code will explain how to create the tables
  • Loading branch information
Pierre Tardy committed Feb 19, 2015
1 parent 4f7cef3 commit 0c1a59d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
24 changes: 19 additions & 5 deletions master/buildbot/db/dbconfig.py
Expand Up @@ -16,6 +16,7 @@
from buildbot.db import enginestrategy
from buildbot.db import model
from buildbot.db import state
from sqlalchemy.exc import OperationalError


class FakeDBConnector(object):
Expand Down Expand Up @@ -58,16 +59,29 @@ def getDb(self):
db.master.caches = FakeCacheManager()
db.model = model.Model(db)
db.state = state.StateConnectorComponent(db)
self.objectid = db.state.thdGetObjectId(db_engine, self.name, "DbConfig")['id']
try:
self.objectid = db.state.thdGetObjectId(db_engine, self.name, "DbConfig")['id']
except OperationalError as e:
if "no such table" in str(e):
db.pool.engine.close()
return None
else:
raise
return db

def get(self, name, default=state.StateConnectorComponent.Thunk):
db = self.getDb()
ret = db.state.thdGetState(db.pool.engine, self.objectid, name, default=default)
db.pool.engine.close()
if db is not None:
ret = db.state.thdGetState(db.pool.engine, self.objectid, name, default=default)
db.pool.engine.close()
else:
if default is not state.StateConnectorComponent.Thunk:
return default
raise KeyError("Db not yet initialized")
return ret

def set(self, name, value):
db = self.getDb()
db.state.thdSetState(db.pool.engine, self.objectid, name, value)
db.pool.engine.close()
if db is not None:
db.state.thdSetState(db.pool.engine, self.objectid, name, value)
db.pool.engine.close()
25 changes: 25 additions & 0 deletions master/buildbot/test/unit/test_db_dbconfig.py
Expand Up @@ -68,3 +68,28 @@ def test_init2(self):
def test_init3(self):
obj = dbconfig.DbConfig({}, self.basedir)
self.assertEqual(obj.db_url, "sqlite:///state.sqlite")


class TestDbConfigNotInitialized(db.RealDatabaseMixin, unittest.TestCase):

@defer.inlineCallbacks
def setUp(self):
# as we will open the db twice, we can't use in memory sqlite
yield self.setUpRealDatabase(table_names=[], sqlite_memory=False)

def createDbConfig(self):
return dbconfig.DbConfig({"db_url": self.db_url}, self.basedir)

def test_default(self):
def thd():
db = self.createDbConfig()
self.assertEqual("foo", db.get(u"slaves", "foo"))

return threads.deferToThread(thd)

def test_error(self):
def thd():
db = self.createDbConfig()
self.assertRaises(KeyError, db.get, u"slaves")

return threads.deferToThread(thd)

0 comments on commit 0c1a59d

Please sign in to comment.