Here's what I do.

First, I get the sequence f rom the table's columns

seq = table.c.id.default
# or if you have a mapper-class
# seq = MyClass.id_property.property.columns[0].default

Then, I execute that sequence to advance the sequence until it's the
value needed.

engine.execute(seq)

The reason I only execute the sequence once is because in my use case,
I know I've just inserted one record manually, so I only want to
advance the sequence once.

I think in your case, after getting the sequence, I would do something
like the following:

column = table.c.id
# or if you have a mapper
# column = MyClass.id_property.property.columns[0]
seq = column.sequence
# get the max ID
maxid = session.query(func.max(column)).one()[0]
# repeatedly advance the sequence until it's greater or equal than the
maxid
while seq.execute() < maxid: pass


I don't think this is the best solution, but it's the best thing I've
come up with so far with my limited knowledge.

Good luck.

On Nov 16, 12:56 pm, Jaume Sabater <jsaba...@gmail.com> wrote:
> Hello everyone!
>
> I've been searching information regarding this topic but without help
> so far. I have a dbloader.py script that takes information from a
> number of CSV files and dumps it into the database. After that we
> execute a number of tests to check all services are working fine
> (returning the right information and calculated data such as
> availability and so on).
>
> In these CSV files I have manually set up the id fields of every
> table, but when I add the rows to the database, I am passing the id
> value as part of the dictionary, therefore the sequence of the primary
> key is not updated. So, after all data has been loaded, I'd like to
> update the start value of the sequence.
>
> It's PostgreSQL, therefore I could do something like:
>
> maxid = engine.execute('select max(id) from <table>').fetchone()[0]
> engine.execute("select setval('<table>_id_seq', %s)" % (maxid + 1))
>
> But I'd like to do this properly, at SA level. Just in case database
> changes in the future or just to satisfy myself. But I have not been
> able to find the way to modify the attributes of the sequence of each
> table I find in the metadata. I have found ways of retrieving the
> nextid in the documentation, but not modifying it.
>
> Is there a way to grab a sequence and set it's next value using the
> abstractions SA facilitates?
>
> Thanks in advance.

--

You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.


Reply via email to