Skip to content

Instantly share code, notes, and snippets.

@wangchen
Last active August 5, 2016 05:16
Show Gist options
  • Save wangchen/2dd3dd28c9c30edd07132fe26155ae9f to your computer and use it in GitHub Desktop.
Save wangchen/2dd3dd28c9c30edd07132fe26155ae9f to your computer and use it in GitHub Desktop.
Safe in/decreasing value without select-for-update
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