forked from simon-weber/Instant-SQLite-Audit-Trail
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaudit.py
executable file
·167 lines (117 loc) · 4.48 KB
/
audit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#!/usr/bin/env python3
import os
import sys
import sqlite3
#all _conn_ references are an sqlite3.Connection
def attach_log(conn,
audit_table='_audit',
ops=('INSERT', 'UPDATE', 'DELETE')):
"""Create a log on this connection. If a log already exists, it is
cleared."""
detach_log(conn)
conn.executescript(
"CREATE TABLE {audit_table}"
" (time TEXT, tbl TEXT, op TEXT, old TEXT, new TEXT);".format(
audit_table=audit_table)
)
for table in get_nonaudit_tables(conn, audit_table):
col_names = get_columns(conn, table)
for op in ops:
conn.execute(trigger_text(table, op, col_names))
def detach_log(conn,
audit_table='_audit',
ops=('INSERT', 'UPDATE', 'DELETE')):
"""Remove and stop logging."""
conn.executescript("DROP TABLE IF EXISTS %s" % audit_table)
for table in get_nonaudit_tables(conn, audit_table):
for op in ops:
conn.execute("DROP TRIGGER IF EXISTS %s" % trigger_name(table, op))
def get_nonaudit_tables(conn, audit_table='_audit'):
tables = [info[1] for info in
conn.execute("SELECT * FROM sqlite_master WHERE type='table' AND NOT (rootpage IS NULL OR rootpage == 0)")]
return [t for t in tables
if t != audit_table and not t.startswith('sqlite_')]
def get_columns(conn, table):
return [info[1] for info in
conn.execute("PRAGMA table_info(%s)" % table)]
def trigger_name(table, op):
return "%s_%s" % (table, op.lower())
def sqlite_list_text(elements):
"""Return text to create a repr of a python list."""
return "'[' || %s || ']'" % "|| ', ' ||".join(elements)
def to_python(repr_str):
"""Execute a python statement and return its result."""
ns = {}
exec("val = (%s)" % repr_str, ns)
return ns['val']
def sqlite_str(var):
"""Return text to convert an sqlite variable into a Python repr."""
return "(CASE WHEN quote({0})='NULL' then 'None' ELSE quote({0}) END)".format(var)
def sqlite_quote(val):
"""Return text to quote some sqlite value."""
return "'%s'" % val
def col_pair_text(col, version):
"""Return text to create a repr of a python list [colname, colval]."""
slt = sqlite_list_text
s = sqlite_str
return slt(["'''%s'''" % col,
s("%s.%s" % (version, col))])
def select_text(table, col_names, version):
"""Generate a select statement for new or old values of this table."""
slt = "SELECT {tuple_str} FROM {table} WHERE rowid={version}.rowid".format(
tuple_str=sqlite_list_text([col_pair_text(c, version)
for c in col_names]),
table=table,
version=version,
)
return "(%s)" % slt
def audit_up_text(table, op, col_names, audit_table):
old_vals, new_vals = 'NULL', 'NULL'
if op in ('UPDATE', 'DELETE'):
old_vals = select_text(table, col_names, 'OLD')
if op in ('INSERT', 'UPDATE'):
new_vals = select_text(table, col_names, 'NEW')
q = sqlite_quote
audit_info = ["DATETIME('now')",
q(table),
q(op),
old_vals,
new_vals,
]
audit_info = ','.join(audit_info)
return "INSERT INTO {audit_table} VALUES({audit_info});".format(
audit_table=audit_table,
audit_info=audit_info
)
def trigger_text(table, op, col_names, audit_table='_audit', name=None):
if name is None:
name = trigger_name(table, op)
when = 'BEFORE' if op == 'DELETE' else 'AFTER'
return "CREATE TRIGGER {name} {when} {op} ON {table} " \
"BEGIN {audit_update} END;".format(
name=name,
when=when,
op=op,
table=table,
audit_update=audit_up_text(table, op, col_names, audit_table)
)
def usage(script_name):
return "usage: %s attach|detach DBFILE" % script_name
if __name__ == '__main__':
script_name = sys.argv[0]
if len(sys.argv) != 3:
print(usage(script_name))
exit(1)
command, db = sys.argv[1:]
if not os.path.isfile(db):
#race condition ignored
print("warning: creating %s" % db)
with sqlite3.connect(db) as conn:
if command == 'attach':
attach_log(conn)
elif command == 'detach':
detach_log(conn)
else:
print('invalid command; use attach or detach')
print()
print(usage(script_name))