[PYTHON] How to apply updlock, rowlock, etc. with a combination of SQLAlchemy and SQLServer

TL;DR

session.query(Table).with_hint(Table, "WITH (ROWLOCK)").filter(Table.count > 0)
# SELECT * FROM Table WITH (ROWLOCK) WHERE count > 0

Thing you want to do

In SQLAlchemy, the with_for_update method is normally used when locking, but as you can see in the example below, SQL Server does not have FOR UPDATE, so this description is ignored.

from sqlalchemy.sql import select, table, literal_column
from sqlalchemy.dialects import mssql

tbl = table("MyTable")
stmt = select([tbl]).where(literal_column("hoge") > 0).with_for_update()

print(stmt.compile(dialect=mssql.dialect()))
# SELECT
# FROM [MyTable]
# WHERE hoge > :hoge_1

solution

In SQL Server, locks are described as WITH (ROWLOCK, UDPLOCK) at the end of the FROM clause in the form of lock hints. In SQLAlchemy, you can embed a hint string as follows using a method called with_hint.

from sqlalchemy.sql import select, table, literal_column
from sqlalchemy.dialects import mssql

tbl = table("MyTable")
stmt = select([tbl]).with_hint(tbl, "WITH (ROWLOCK)").where(literal_column("count") > 0)

print(stmt.compile(dialect=mssql.dialect()))
# SELECT
# FROM [MyTable] WITH (ROWLOCK)
# WHERE count > :count_1

Congratulations

reference

https://docs.sqlalchemy.org/en/14/core/selectable.html#sqlalchemy.sql.expression.Select.with_hint

https://docs.sqlalchemy.org/en/14/core/selectable.html#sqlalchemy.sql.expression.Select.with_for_update

https://stackoverflow.com/questions/56030825/sqlalchemy-query-api-not-working-correctly-with-hints

https://www.m3tech.blog/entry/sqlalchemy-tutorial

Recommended Posts

How to apply updlock, rowlock, etc. with a combination of SQLAlchemy and SQLServer
How to convert a class object to a dictionary with SQLAlchemy
How to Alter with SQLAlchemy?
How to Delete with SQLAlchemy?
How to display a list of installable versions with pyenv
How to insert a specific process at the start and end of spider with scrapy
How to INNER JOIN with SQLAlchemy
How to set a shortcut to switch full-width and half-width with IBus
Overview of how to create a server socket and how to establish a client socket
How to make a surveillance camera (Security Camera) with Opencv and Python
Here's a brief summary of how to get started with Django
How to format a table using Pandas apply, pivot and swaplevel
Node.js: How to kill offspring of a process started with child_process.fork ()
How to display the CPU usage, pod name, and IP address of a pod created with Kubernetes
How to split and save a DataFrame
[EC2] How to take a screen capture of your smartphone with selenium
How to get parent id with sqlalchemy
How to add a package with PyCharm
[Introduction to Python] How to sort the contents of a list efficiently with list sort
Summary of how to build a LAMP + Wordpress environment with Sakura VPS
How to use SQLAlchemy / Connect with aiomysql
Find out how to divide a file with a certain number of lines evenly
How to count the number of elements in Django and output to a template
How to get a list of files in the same directory with python
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
[Introduction to Python] How to get the index of data with a for statement
A new form of app that works with GitHub: How to make GitHub Apps
How to read a CSV file with Python 2/3
A simple example of how to use ArgumentParser
How to send a message to LINE with curl
How to draw a 2-axis graph with pyplot
How to develop a cart app with Django
How to make a dictionary with a hierarchical structure.
Script to tweet with multiples of 3 and numbers with 3 !!
How to specify attributes with Mock of python
How to implement "named_scope" of RubyOnRails with Django
How to create a multi-platform app with kivy
A memo on how to overcome the difficult problem of capturing FX with AI
How to convert / restore a string with [] in python
A memo connected to HiveServer2 of EMR with python
A memo of how to use AIST supercomputer ABCI
[Python] How to draw a line graph with Matplotlib
How to get a logged-in user with Django's forms.py
How to make a shooting game with toio (Part 1)
How to get more than 1000 data with SQLAlchemy + MySQLdb
How to extract null values and non-null values with pandas
How to output CSV of multi-line header with pandas
Create a batch of images and inflate with ImageDataGenerator
How to loop and play gif video with openCV
How to infer MAP estimate of HMM with PyStruct
Basics of PyTorch (2) -How to make a neural network-
How to infer MAP estimate of HMM with OpenGM
[Python] How to create a 2D histogram with Matplotlib
How to learn structured SVM of ChainCRF with PyStruct
[How to!] Learn and play Super Mario with Tensorflow !!
[Python] How to draw a scatter plot with Matplotlib
Apply conda's env to a specific directory with pyenv-vertualenv
Summary of how to share state with multiple functions
[Linux] [C / C ++] How to get the return address value of a function and the function name of the caller
Unzip a lot of ZIP-compressed files with Linux commands to UTF8 and stick them together
How to interactively draw a machine learning pipeline with scikit-learn and save it in HTML