-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpggenerator.py
191 lines (152 loc) · 6.36 KB
/
pggenerator.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import random as rand
import time
import datetime as dt
class Field(object):
def __init__(self, name, nullChance = 0, unique = False):
self.name = name
self.generated = []
self.nullChance = nullChance
self.relation = None
self.unique = unique
def fieldType(self):
raise "Not implemented"
def schema(self):
return "%s%s" % (self.fieldType(), (" UNIQUE" if self.unique else ""))
def generateNonNull(self):
raise "Not implemented"
def generate(self):
val = "NULL" if rand.random() < self.nullChance else self.generateNonNull()
self.generated.append(val)
return val
class IntField(Field):
def __init__(self, name, minVal = -2147483648, maxVal = 2147483647, nullChance = 0, unique = False):
super(IntField, self).__init__(name, nullChance, unique)
self.min = minVal
self.max = maxVal
def fieldType(self):
return "INTEGER"
def generateNonNull(self):
return rand.randint(self.min, self.max)
class RealField(Field):
def __init__(self, name, precision = 6, minVal = -2147483648.0, maxVal = 2147483647.0, nullChance = 0, unique = False):
super(RealField, self).__init__(name, nullChance, unique)
self.format = "{:.%sf}" % (precision,)
self.min = minVal
self.max = maxVal
def fieldType(self):
return "REAL"
def generateNonNull(self):
return self.format.format(rand.uniform(self.min, self.max))
class BooleanField(Field):
def __init__(self, name, chanceForTrue = 0.5, nullChance = 0, unique = False):
super(BooleanField, self).__init__(name, nullChance, unique)
self.chanceForTrue = chanceForTrue
def fieldType(self):
return "BOOLEAN"
def generateNonNull(self):
return rand.random() <= self.chanceForTrue
class TextField(Field):
def __init__(self, name, minLength = 0, maxLength = 255, letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", nullChance = 0, unique = False):
super(TextField, self).__init__(name, nullChance, unique)
self.minLength = minLength
self.maxLength = maxLength
self.letters = letters
def fieldType(self):
return "TEXT"
def generateNonNull(self):
return "'%s'" % (''.join([rand.choice(self.letters) for _ in range(rand.randint(self.minLength, self.maxLength))]),)
class DateField(Field):
def __init__(self, name, earliest, latest, nullChance = 0, unique = False):
'''
Both dates are expected to be a triple (year, month, day)
'''
super(DateField, self).__init__(name, nullChance, unique)
self.earliest = time.mktime(earliest + (0,0,0,0,0,0)) # append hour, minute, second, ...
self.latest = time.mktime(latest + (0,0,0,0,0,0))
def fieldType(self):
return "DATE"
def generateNonNull(self):
return "'%s'" % (dt.datetime.fromtimestamp(rand.randint(self.earliest, self.latest)).strftime('%Y-%m-%d'),)
class SerialField(Field):
def __init__(self, name, startValue = 1, nullChance = 0):
super(SerialField, self).__init__(name, nullChance, True)
self.current = startValue
def fieldType(self):
return "SERIAL"
def generateNonNull(self):
val = self.current
self.current += 1
return val
class ForeignKeyField(Field):
'''
keep in mind, when generating tuples for a relation with a ForeignKeyField,
at least some tuples for the referenced Field must be created already.
Naturally, the values for the ForeignKeyField will only be whatever has been
created up to that point in the referenced Field.
The type of the field will obviously be the same as the referenced field.
'''
def __init__(self, name, reference, nullChance = 0, unique = False):
super(ForeignKeyField, self).__init__(name, nullChance, unique)
if not reference.unique:
raise Exception("Can not reference non-UNIQUE field '%s'" % (str(reference.name,)))
self.reference = reference
def schema(self):
return "%s REFERENCES %s(%s)" % (self.reference.fieldType(), self.reference.relation.name, self.reference.name)
def generateNonNull(self):
assert len(self.reference.generated) > 0
return rand.choice(self.reference.generated)
class Relation(object):
def __init__(self, name, fields):
self.name = name
self.fields = fields
for f in fields:
f.relation = self
def field(self, fname):
for f in self.fields:
if f.name == fname:
return f
return None
def create(self):
return "CREATE TABLE %s(%s);" % (self.name, ', '.join(["%s %s" % (f.name,f.schema()) for f in self.fields]))
def drop(self, cascade = False):
return "DROP TABLE %s %s;" % (self.name, ("CASCADE" if cascade else ""))
def insert(self, n):
tuples = []
for i in range(n):
tuples.append(', '.join([str(v.generate()) for v in self.fields]))
return "INSERT INTO %s (VALUES \n %s\n);" % (self.name, ',\n '.join("(%s)" % (t,) for t in tuples))
def main():
# print(DateField("some_data", (1990,12,1), (2007,1,1)).generate())
# print(TextField("some_text", 20).generate())
# print(BooleanField("some_bool", 0.5).generate())
# print(IntField("some_int", 10,100).generate())
# print(RealField("some_real", 6,-10,10).generate())
r1 = Relation("persons", [
TextField("name", minLength = 5, maxLength = 10, unique = True),
IntField("income", 10000, 40000),
BooleanField("married", 0.3),
DateField("born", (1970,1,1),(2010,4,10)),
RealField("x", 6,-1,1),
TextField("mostlyNull", nullChance = 0.95),
SerialField("id")
])
r2 = Relation("orders", [
ForeignKeyField("pid", r1.field("id")),
IntField("quantity", 1,10),
TextField("article", maxLength = 20)
])
r3 = Relation("workers", [
ForeignKeyField("worker", r1.field("name")),
ForeignKeyField("boss", r1.field("name"))
])
print(r1.drop(True))
print(r1.create())
print(r1.insert(20))
print(r2.drop(True))
print(r2.create())
print(r2.insert(1000))
print(r3.drop(True))
print(r3.create())
print(r3.insert(50))
if __name__ == '__main__':
main()