Great stuff, thanks!
I got my project working as I wanted it.
I added some error control.
def getDatabaseInfo():
# Define the query dictionary and excluded types
queryDict = {
'POSTGRES': 'SELECT current_database()',
'MSSQL': 'SELECT DB_NAME()',
}
excludedTypes = ['ORACLE']
# Get the database connections
dataIn = system.dataset.toPyDataSet(system.db.getConnections())
# Initialize lists for dataset
headers = ['ConnectionName', 'DatabaseName']
data = []
# Iterate through the connections
for row in dataIn:
if row['DBType'] in excludedTypes:
print row['Name'] + ' excluded.'
continue
try:
if row['Status'] == 'Valid':
dbConn = row['Name']
query = queryDict.get(row['DBType'])
if query:
db = system.db.runScalarQuery(query, dbConn)
print dbConn + ': ' + db
data.append([dbConn, db])
except:
print row['Name'] + ' exception.'
# Convert the data to a BasicDataset
dataset = system.dataset.toDataSet(headers, data)
return dataset
In case anyone's interested, I call this function through an expression: runScript('dbScripts.getDatabaseInfo')
then use the result to loop through the connections and get storage information from each db.
ds = system.dataset.toPyDataSet(value)
headers = ['ConnectionName', 'Database', 'file_id', 'LogicalName', 'PhysicalName', 'TotalSizeMB', 'AvailableSpaceMB']
data = []
query = '''
SELECT
file_id,
name AS LogicalName,
physical_name AS PhysicalName,
size * 8 / 1024 AS TotalSizeMB,
size * 8 / 1024 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS INT) * 8 / 1024 AS AvailableSpaceMB
FROM
sys.master_files
WHERE
database_id = DB_ID(N'{dbName}');
'''
resultData = []
for row in ds:
connectionName = row['ConnectionName']
databaseName = row['DatabaseName']
try:
# format the query with the database name
sql = query.format(dbName=databaseName)
# execute the formatted query
results = system.db.runPrepQuery(sql, [], connectionName)
# check if any results are returned.
if len(results) == 0:
# Add a blank row to data if there are no results
data.append([dbName, None, None, None, None, None])
# process the results
for resultRow in results:
data.append([
connectionName,
databaseName,
resultRow['file_id'],
resultRow['LogicalName'],
resultRow['PhysicalName'],
resultRow['TotalSizeMB'],
resultRow['AvailableSpaceMB']
])
except:
# Add a blank row to resultData if there's an exception
data.append([connectionName, databaseName, None, None, None, None, None])
dataset = system.dataset.toDataSet(headers, data)
return dataset
I'm sure there's a cleaner way to do it, but I'm not a coder.
Thanks again for the help!