I am using SQLalchemy with flask to interact with sql server. I have enabled system versioning for the tables. On executing first query to insert or update the table after the app runs , sysstarttime gets updated, but in next subsequent insert or update operation the sysstarttime doesn't update .. it is still showing the older transaction time meanwhile if some other running flask app tries to update the rows it throws an error "data modification failed for the system versioned table"
query that i have used for creating tables:
CREATE TABLE dbo.table(
ScanSubscriptionID NOT NULL PRIMARY KEY,
UserName varchar(20) NOT NULL,
SysStartTime DATETIME2 GENERATED ALWAYS AS ROW START NOT NULL,
SysEndTime DATETIME2 GENERATED ALWAYS AS ROW END NOT NULL,
PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.table));
Here's the code of my app:
import urllib
from flask import Flask
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
connection_string =\
urllib.parse.quote_plus('Driver={ODBC Driver 17 for SQL Server};Server=localhost\MSSQLSERVER01;Database=db_Data;Trusted_Connection=yes;')
connection_string = "mssql+pyodbc:///?odbc_connect=%s" % connection_string
app.config['SQLALCHEMY_DATABASE_URI'] = connection_string
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
session_option = {
'autocommit': True
}
db = SQLAlchemy(app, session_options=session_option)
db.init_app(app)
session1 = db.session
@app.route('/')
def testdb():
try:
session1.begin()
session1.execute("update [table] set UserName = 'Ksing' where ScanSubscriptionID = 1600336614")
session1.commit()
return '<h1>It works.</h1>'
except Exception as e:
raise e
finally:
print(f'Time is :{datetime.utcnow()}')
#session1.close()
if __name__ == '__main__':
app.run(debug=True)