Context - There is a folder with SQL Server Database backups; these backups are generated nightly and the .BAK file names will be different each time, as the timestamps are included in the filenames. There will be multiple .BAK for the same database in this folder.
We have single .sql file with commands to restore the latest backups like this:
exec RestoreDB 'Items', '\\BackupServer\BackupData\Cleaned\SQL03A.Items.2023-02-28.19-19-59.BAK'
The script below is what I attempted to generate the file RestoreDatabases.sql with the above exec
commands for all databases.
I want to include only the latest copy of the .BAK file. To do that, I added these two lines just to see the latest files:
latest_file = max(dbFiles, key=os.path.getmtime)
print(latest_file)
However, when I do this, the subsequent for loop doesn't execute at all.
My question is, why are these two lines changing the behavior of the subsequent for loop? Is there more elegant way to do this? Thank you.
Full Code
from difflib import restore
import os
import pathlib
from datetime import datetime
start_time = datetime.now()
databases = ["Application","Fraud","Orders","Returns","Location","Items", "UserProfile"]
excludeKeywords = ["Shrunk", "FullSized","ETV"]
backupDirectoryForAllDB = "\\\\172.24.114.178\\BackupData\\EcommCleaned"
backupDirectoryForUserProfile = "\\\\wawomsstg5efc.np.costco.com\\BackupData\\EcommCleaned"
restoreDBSQLFileFullPath = "C:\\Bins\\SQL\\RestoreDatabases.sql"
finalString = ""
for db in databases:
if db == "UserProfile":
dbFiles = pathlib.Path(backupDirectoryForUserProfile).rglob('*' + db +'*.BAK')
else:
dbFiles = pathlib.Path(backupDirectoryForAllDB).rglob('*' + db +'*.BAK')
latest_file = max(dbFiles, key=os.path.getmtime)
print(latest_file) #this works as expected
for filepath in dbFiles: #doesn't execute, with the above two lines why?
if not any(x in str(filepath) for x in excludeKeywords):
finalString += "exec RestoreDB '{dbName}', '{pathToBakFile}'".format(dbName=db, pathToBakFile=filepath.absolute()) + "\n"
# try:
# with open(restoreDBSQLFileFullPath, "w+") as f:
# f.write(finalString)
# print( restoreDBSQLFileFullPath + ' file updated with the most current .BAK file names.')
# except:
# print("Something went wrong when opening / writing " + restoreDBSQLFileFullPath)
# print()
print(finalString)
elapsed = (datetime.now() - start_time)
print(f"Took: {elapsed}" )