Hello community,
Recently a DBA asked me about a “live” connection to a database, and this was a connection I had set up on one of our gateways for testing purposes. Since I was not going to use it, I decided to disable it, which gave me an idea: I could enable the connection when needed, and disable it when I’m done; that way I don’t keep the connection alive for more than needed.
So I came up with the following code:
class Connection(object):
def __init__(self, db):
self.db = db
self.enabled = False
def __enter__(self):
import time
self.enabled = True
system.db.setDatasourceEnabled(self.db, self.enabled)
# Wait for the connection to be Valid.
while self.status != "Valid":
time.sleep(1)
def __exit__(self, type, value, traceback):
self.enabled = False
system.db.setDatasourceEnabled(self.db, self.enabled)
@property
def status(self):
ci = system.db.getConnectionInfo(self.db)
return ci.getValueAt(0, "Status")
db = "test"
conn = Connection(db)
with conn:
data = system.db.runQuery(query="SELECT 1", database=db)
print data.getValueAt(0, 0)
Using the with
statement I don’t have to worry about enabling and disabling the connection every time I run a query against that connection.
It is a very rough approach, as I am sure there is room for improvement, but I wanted to share and ask if someone else has done something similar.