First of all, Gino seems awesome. Thanks for your hard work :)
I'm trying to understand how can I use things like on_conflict_do_nothing() (https://docs.sqlalchemy.org/en/13/dialects/postgresql.html#insert-on-conflict-upsert)
when using Gino ORM. Full example below, but basically this is what I'm trying to achieve:
await User.create(id='1', name='jack', fullname='Jack Jones') # succeeds
await User.create(id='1', name='jack', fullname='Jack Jones').on_conflict_do_nothing() # raises exception
How should things like these be approached when using Gino?
Thank you for your time!
from gino import Gino
db = Gino()
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
fullname = db.Column(db.String)
async def main():
async with db.with_bind('postgresql://localhost/gino'):
await db.gino.create_all()
await User.create(id='1', name='jack', fullname='Jack Jones')
# how to do something similar to this:
await User.create(id='1', name='jack', fullname='Jack Jones').on_conflict_do_nothing()
Thanks for the question! Please see example below:
from sqlalchemy.dialects.postgresql import insert
stmt = insert(User).values(id=1, name="jack", fullname="Jack Jones")
stmt = stmt.on_conflict_do_update(
index_elements=[User.id], set_=dict(id=stmt.excluded.id)
).returning(*User)
user = await stmt.gino.model(User).first()
# INSERT INTO users (id, name, fullname) VALUES ($1, $2, $3)
# ON CONFLICT (id) DO UPDATE SET id = excluded.id
# RETURNING users.id, users.name, users.fullname
Great, thanks!
Most helpful comment
Thanks for the question! Please see example below: