[sqlalchemy] AuditLog my first attempt

2 views
Skip to first unread message

Marco De Felice

unread,
Mar 4, 2008, 5:34:11 AM3/4/08
to sqlal...@googlegroups.com
So after some coding and thanks to sdobrev previous reply I came up with
the following mapperextension that allows for a client side update log
to a different table (logtable name = table_prefix + original table
name) with a logoperation field added.

Any comment is welcome as I don't really know SA internals, it seems to
work against a simple mapped table.

#------------------------------------------------------------------

import sqlalchemy as sqa
import sqlalchemy.orm as sqorm
from sqlalchemy.sql import text as sqaText

class AuditLog(sqorm.MapperExtension):

def __init__(self, table_prefix):
self.table_prefix = table_prefix

def after_update(self, mapper, connection, instance):

#what to do with a multitable mapper ?
assert len(mapper.tables) == 1

statement = "INSERT INTO %s%s" %(self.table_prefix,
mapper.tables[0].name)

fnames = ["logoperation"]
parms = [":logoperation"]
vals = {"logoperation" : "U"} #the log operation is U = Update

for c in mapper.columns:
attrName = c.name

fnames.append(attrName)

parm = ":%s" % attrName
parms.append(parm)

(added, unchanged, deleted) = sqorm.attributes.get_history(
instance._state,
attrName)

#when it fails?
assert len(unchanged) < 2

if added :
vals[attrName] = added[0]
elif unchanged:
vals[attrName] = unchanged[0]

fnamesStr = ", ".join(fnames)
valuesStr = ", ".join(parms)
statement += " (%s) VALUES (%s)" % (fnamesStr, valuesStr)

s=sqaText(statement)
connection.execute(s, vals)

return sqorm.EXT_CONTINUE

svilen

unread,
Mar 4, 2008, 6:03:07 AM3/4/08
to sqlal...@googlegroups.com
On Tuesday 04 March 2008 12:34:11 Marco De Felice wrote:
> So after some coding and thanks to sdobrev previous reply I came up
> with the following mapperextension that allows for a client side
> update log to a different table (logtable name = table_prefix +
> original table name) with a logoperation field added.
>
> Any comment is welcome as I don't really know SA internals, it
> seems to work against a simple mapped table.
for multitable mappers...
a) log as mapper-access and not table-access
b) or, while walking mapper.columns, each column knows which table it
comes from, so for those changed u can log them separately
Reply all
Reply to author
Forward
0 new messages