As pointed out here its possible to do the following with postgresql 9.1+
INSERT INTO example_table
(id, name)
SELECT 1, 'John'
WHERE
NOT EXISTS (
SELECT id FROM example_table WHERE id = 1
);
I've been having a play around with version 0.9 of sqlalchemy where they have introduced INSERT from SELECT method which should theoretically handle the above.
Is it possible and if so how? (as i want to take advantage of the result.inserted_primary_key that is not returned when using raw sql)
How can I use bindparams for the 'from_select' part as the only way I can seem to use it is when using table columns in the select.
e.g.
insrt = example_table.insert().
from_select(['id', 'name'],
example_table.select().
where(~exists(select([example_table.c.id],
example_table.c.id == 1))))
result = session.execute(insrt)
if result.is_insert:
print 'do something with result.inserted_primary_key'