I would like to do a conditional insert of a a single row. This is often useful in a CRUD app for checking permissions and inserting in a single database call:
INSERT INTO project (name, user_id)
SELECT :name, :user_id
WHERE EXISTS (
SELECT 1
FROM users
WHERE id = :user_id
and role = :admin_role
)
In SQLAlchemy I use the following which isn't the most beautiful:
ins = insert(Project).from_select(
['name', 'user_id'],
select(
bindparam('name', project_name),
bindparam('user_id', user_id),
).where(
exists(
select(1).select_from(
User
).where(
User.c.id == 1,
User.c.role == "ADMIN",
)
)
)
)
I find my use of `bindparam` in the select statement to be rather noisy.
Does anyone know of a way to make it a bit more easier on the eyes?
Would you be open to making a SQLAlchemy conditional insert API?
Project.insert(name=project_name, user_id=user_id).where(
exists(
# ...
)
)
In other words, create a method "where" on Insert that will not use VALUES and instead use a SELECT.
Thanks and best regards,
Matthew