-
Notifications
You must be signed in to change notification settings - Fork 52
/
ushuffle_sad.py
149 lines (119 loc) · 4 KB
/
ushuffle_sad.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
#!/usr/bin/env python3
from distutils.log import warn as printf
from os.path import dirname
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT # Okay only in Python3 :(
from random import randrange as rand
from sqlalchemy import Column, Integer, String, create_engine, exc, orm
from sqlalchemy.ext.declarative import declarative_base
from password import PASSWORD
from ushuffle_dbU import DBNAME, NAMELEN, randName, FIELDS, tformat, cformat,\
RDBMSs, scanf
DSNs = {
'mysql': 'mysql://root@localhost/%s/%s' % (DBNAME, PASSWORD),
'sqlite': 'sqlite:///:memory:',
'postgresql': 'postgresql+psycopg2://binaryBoy:%s@localhost/%s' % (PASSWORD, DBNAME)
}
Base = declarative_base()
class Users(Base):
__tablename__ = 'users'
login = Column(String(NAMELEN))
userid = Column(Integer, primary_key=True)
projid = Column(Integer)
def __str__(self):
return ''.join(map(tformat, (self.login, self.userid, self.projid)))
class SQLAlchemyTest(object):
def __init__(self, dsn):
try:
eng = create_engine(dsn)
except ImportError:
raise RuntimeError()
try:
eng.connect()
except exc.OperationalError:
eng = create_engine(dirname(dsn))
conn = eng.connect()
try:
conn.connection.connection.set_isolation_level(0)
conn.execute('CREATE DATABASE %s' % DBNAME).close()
conn.connection.connection.set_isolation_level(1)
except exc.OperationalError:
raise RuntimeError()
eng = create_engine(dsn)
Session = orm.sessionmaker(bind=eng)
self.ses = Session()
self.users = Users.__table__
self.eng = self.users.metadata.bind = eng
def insert(self):
self.ses.add_all(Users(login=who, userid=userid, projid=rand(1, 5)) \
for who, userid in randName()
)
def update(self):
fr = rand(1, 5)
to = rand(1, 5)
i = self.ses.query(
Users
).filter_by(projid=fr).update({'projid':to})
self.ses.commit()
return fr, to, i
def delete(self):
rm = rand(1, 5)
i = self.ses.query(
Users
).filter_by(projid=rm).delete()
self.ses.commit()
return rm, i
def dbDump(self, newest5=False):
printf("\n%s" % ''.join(map(cformat, FIELDS)))
if not newest5:
users = self.ses.query(Users).all()
else:
users = self.ses.query(Users).order_by(Users.userid.desc())[:5] # I don't see any need of offset here.
for user in users:
printf(user)
self.ses.commit()
def __getattr__(self, attr):
return getattr(self.users, attr)
def finish(self):
self.ses.connection().close()
def setup():
return RDBMSs[scanf(
'''
Choose a database system:
(M)ySQL
(G)adfly
(S)QLite
(P)ostgreSQL
Enter choice: ''').strip().lower()[0]]
def main():
printf("*** Connect to %r database" % DBNAME)
db = setup()
if db not in DSNs:
printf("\nERROR: %r not supported, exit" % db)
return
try:
orm = SQLAlchemyTest(DSNs[db])
except RuntimeError:
printf("\nERROR: %r not supported, exit" % db)
return
printf("\n*** Create users table (drop old one if appl.)")
orm.drop(checkfirst=True)
orm.create()
printf("\n*** Insert names into table")
orm.insert()
orm.dbDump()
print("\n*** Top 5 newest employees")
orm.dbDump(newest5=True)
printf("\n*** Move users to a random group")
fr, to, num = orm.update()
printf("\t(%d users moved) from (%d) to (%d)" % (num, fr, to))
orm.dbDump()
printf("\n*** Randomly delete group")
rm, num = orm.delete()
printf("\t(group #%d; %d users removed)" % (rm, num))
orm.dbDump()
printf("\n Drop users table")
orm.drop()
printf("\n*** Close cxns")
orm.finish()
if __name__ == "__main__":
main()