This is my "serials" table and mapper:

table.serials = Table("serials", instance.metadata.default,
    Column("prefix", String(32), primary_key=True),
    Column("month", String(32), nullable=False),
    Column("count", Integer, nullable=False),
)

class Serial(object):
    pass

mapperSerial = mapper(Serial, table.serials)

I need a getSerial(prefix) to get a unique serial number depend on current
month, here's my code using orm:

def getSerial(prefix):
    from datetime import datetime
    today = datetime.today()
    month = "%s%02d" % (str(today.year)[2:], today.month)
    count = None

    query = instance.session.default.query(Serial)
    serial = query.get(prefix)
    if serial is None:
        serial = Serial()
        serial.prefix = prefix
        serial.month = month
        serial.count = 1
        instance.session.default.save(serial)
    if serial.month != month:
        serial.month = month
        serial.count = 1
    count = serial.count
    serial.count += 1
    instance.session.default.flush()
    instance.session.default.expunge(serial)
    return "%s-%s%04d" % (prefix, month, count)

But if there're two or more clients run getSerial() at the same time,
they'll get same result and will cause some problem. So I write codes use
"LOCK TABLES" in my first post in this thread. Can the orm do the same thing
beautifully? For "group version" of my program, it use MySQL; and "single
machine version", it use SQLite.


2007/6/22, Michael Bayer <[EMAIL PROTECTED]>:
>
>
> conn = engine.connect()
> trans = conn.begin()
> ...etc
> trans.commit()
>
> table locking is usually either implicit to SQL operations performed
> within the transaction or using a construct like SELECT..FOR UPDATE,
> but you can still issue your straight text if you like (but LOCK
> TABLES isnt portable).
>
>
> On Jun 21, 5:41 pm, "Can Xue" <[EMAIL PROTECTED]> wrote:
> > I'm using MySQL and when I need to lock a table, I do:
> >
> >     conn = engine.connect()
> >     conn._autocommit = dummyFunc
> >     conn.execute("LOCK TABLES tablename WRITE")
> >     try:
> >         ...
> >         conn.execute("COMMIT")
> >     except:
> >         conn.execute("ROLLBACK")
> >         ...
> >     finally:
> >         conn.execute("UNLOCK TABLES")
> >         conn.close()
> >
> > Are there any more pythonic ways to do such tasks?
> >
> > --
> >
> > XUE Can
>
>
> >
>

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

Reply via email to