-
-
Save wangchen/2dd3dd28c9c30edd07132fe26155ae9f to your computer and use it in GitHub Desktop.
Safe in/decreasing value without select-for-update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import Column, Integer, String | |
from sqlalchemy import create_engine | |
from sqlalchemy.orm import sessionmaker | |
from sqlalchemy.ext.declarative import declarative_base | |
import logging | |
logging.basicConfig() | |
Base = declarative_base() | |
# Define a unsigned type for avoiding negative value | |
# drop domain if exists uint4; | |
# create domain uint4 as integer check(value > 0); | |
# sql for creating demo table | |
# drop table if exists t; | |
# create table t(id integer primary key, name text, counter uint4); | |
class T(Base): | |
__tablename__ = 't' | |
id = Column(Integer, primary_key=True) | |
name = Column(String(20)) | |
counter = Column(Integer) | |
db_url = 'postgresql+psycopg2://localhost/zzb_shard_1' | |
engine = create_engine(db_url, echo=True) | |
Session = sessionmaker(bind=engine) | |
session = Session() | |
# create a obj if it does not exist | |
data = { 'id': 1, 'name': 'dawn', 'counter': 1} | |
t = session.query(T).get(data['id']) | |
if not t: | |
t = T(**data) | |
session.add(t) | |
session.commit() | |
# increase numberic column | |
t.counter = T.counter + 1 | |
print("*NOTE*:\n - type: %s\n - value: %s" % (type(t.counter), t.counter)) | |
session.commit() | |
session.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment