My first attempt to restore the mssql database ended up in (Restoring…) status for hours without no result. So I did some research and came down to the procedure here that I need to execute from python.
First checking the RESTORE FILELISTONLY gives me something like this
(‘Mydatabase’, ‘C:Mydatabase.ndf’, …
(‘Mydatabase_log’, ‘F:Mydatabase_log.ldf, … (that’s right, it’s F:..)
So I wrote the following procedure (queries.sql):
RESTORE DATABASE [Mydatabase] FROM DISK = N'C:Mydatabase_Latest.bak' WITH REPLACE, NORECOVERY, STATS = 5,
MOVE 'Mydatabase' TO 'C:DatabasestmpMydatabase.ndf',
MOVE 'Mydatabase_log' TO 'C:DatabasestmpMydatabase_log.ldf';
RESTORE LOG [Mydatabase] FROM DISK = 'C:DatabasestmpMydatabase_log.ldf' WITH REPLACE, NORECOVERY;
RESTORE DATABASE [Mydatabase] WITH RECOVERY;
I run this from:
#!/usr/bin/env python3
import pyodbc
import sys
print("RUNNING QUERY:")
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=.\SQL2019;"
"Trusted_Connection=yes;", autocommit=True)
print("DATABASE CONNECTED.")
cursor = cnxn.cursor()
print("CURSOR READY.")
print(f"INFO: Opening {sys.argv[1]}")
with open(sys.argv[1]) as sqlcmd: #this received "queries.sql"
sqldata = sqlcmd.read().split(";")
for i in sqldata:
print(f"RUNNING: {i}")
r=cursor.execute(i)
try:
for row in r:
#for i, col in enumerate(columns):
print(row)
except pyodbc.ProgrammingError as e:
print(f"WARN: {e}")
print(f"DONE")
The problem is that this script ends with:
pyodbc.ProgrammingError: (‘42000’, “[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open backup device ‘C:DatabasestmpMydatabase_log.ldf’. Operating system error 32(The process cannot access the file because it is being used by another process.). (3201) (SQLExecDirectW); [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]RESTORE LOG is terminating abnormally. (3013)”)
Tried to restart machine and nothings works. I can’t do this through the SSMS interface. This is an automated process.