-
Notifications
You must be signed in to change notification settings - Fork 0
/
JQL.py
424 lines (327 loc) · 13 KB
/
JQL.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
import operator
import json
from collections import Iterable
from EngineRoom import AST, ParseText,breakDownStringToTokens
#from EngineRoom import createnode
jsonstring = '{"tim":{"nazivtima":"BobRock" , "igraci" : [{"id" : "prvi" , "ime" : "Sale"},{"id":"drugi","ime" : "Dzoni"}]}}'
json_loaded = json.loads(jsonstring)
class Node(object):
"""docstring for Node"""
def __init__(self):
self.childrens = []
def add(self, child):
self.childrens.append(child)
def dooperation(self):
"""do operation on childrens, eval"""
pass
def __str__(self):
print "<" + self.__class__.__name__ + ">"
if len(self.childrens) == 0:
return "Nema vise dece ova grana"
for child in self.childrens:
print child.__str__()
return "to"
class LeafNode(Node):
def __init__(self, token):
super(LeafNode, self).__init__()
self.token = token
def dooperation(self):
return self.token.value
class BaseExprNode(Node):
def dooperation(self):
#print "BaseExpr"
return self.childrens[0].dooperation()
class AndMathOpNode(Node):
def dooperation(self):
return self.childrens[0].dooperation()
class StrongExprNode(Node):
def dooperation(self):
#print "StrongExpr"
return self.childrens[0].dooperation()
class ExprNode(Node):
def dooperation(self):
return self.childrens[0].dooperation()
class QueryNode(Node):
def dooperation(self):
return self.childrens[0].dooperation()
class RemoveExprNode(Node):
#TODO at end of dooperation replace original json file with one from removeexpr
#TODO figure out what should you return at and of it, cuz' node above requires something
def dooperation(self, jsonstring=json_loaded):
path_to_object = self.childrens[0].dooperation()
what_to_delete = self.childrens[1].dooperation()
return delete_from_json(path_to_object, jsonstring, what_to_delete[0], what_to_delete[1])
class AddExprNode(Node):
#TODO at end of dooperation replace original json file with one from removeexpr
def dooperation(self, jsonstring=json_loaded):
#get object or objects to which you have to add new json object
path_to_objects = self.childrens[0].dooperation()[0]
conditions = self.childrens[0].dooperation()[1]
objects = getjsonobject(path_to_objects, jsonstring, conditions)
to_add = self.childrens[1].dooperation()
#transform to_add from string to json
#check for json input validity
#input can be new dict , adding to list {"key":"value}
#or it can be simple addition to existing dict as "key":"value"
try:
to_add_json = json.loads(to_add)
except ValueError:
raise ValueError('Couldn\'t transform input string into json')
if type(objects) is list and conditions is None:
objects.append(to_add_json)
else:
for obj in objects:
for key in to_add_json.keys():
obj[key] = to_add_json[key]
return jsonstring
class UpdateExprNode(Node):
def dooperation(self, jsonstring=json_loaded):
#TODO see if it's ok to transforem getjsonobject to generator
#print "updateexpr"
path_to_objects = self.childrens[0].dooperation()[0]
conditions = self.childrens[0].dooperation()[1]
objects = getjsonobject(path_to_objects, jsonstring,
conditions) #this ain't gonna work cuz json is not gonna change, due to immutability of strings
#objects = jsonstring["sale"]["items"]
to_update_with = self.childrens[1].dooperation()
for obj in objects:
#objects[index] = to_update_with
obj.clear()
obj.update(json.loads(to_update_with))
#print jsonstring
return jsonstring
class GetExprNode(Node):
def dooperation(self, jsonstring=json_loaded):
#print "getexpr"
path_to_object = self.childrens[0].dooperation()
from_object = getjsonobject(path_to_object, jsonstring)
#tuple , object we are looking for and conditions if there are any
what_to_return = self.childrens[1].dooperation()
return getjsonobject(what_to_return[0], from_object, what_to_return[1])
class WutNode(Node):
def dooperation(self):
"""Should return path to the request object and
optional list of conditions"""
#print "wut node do"
path_to_object = self.childrens[0].dooperation()
try:
conditions = flattenlistoftuples(self.childrens[1].dooperation())
except IndexError:
conditions = None
return (path_to_object, conditions)
class ObjectNode(Node):
def dooperation(self):
"""Returns 'path' to the object as a list of keys"""
lista = []
for child in self.childrens:
lista.append(child.dooperation())
return list(flatten(lista))
class ConditionNode(Node):
def dooperation(self):
listl = []
for child in self.childrens:
listl.append(child.dooperation())
return listl
class BasicConditionNode(Node):
def dooperation(self):
"""Returns tuple with key to objects child, comparison operator,
and value to witch it will be later compared to """
key = self.childrens[0].dooperation()
value = self.childrens[2].dooperation()
comparisonop = self.childrens[1].dooperation()
return (key, comparisonop, value)
class VariableNode(Node):
def dooperation(self):
return self.childrens[0].dooperation()
class ValueNode(Node):
def dooperation(self):
return self.childrens[0].dooperation()
class JsonStringNode(LeafNode):
pass
class MathExprNode(Node):
pass
class StringExprNode(Node):
pass
class ComparisonOpNode(Node):
def dooperation(self):
return self.childrens[0].dooperation()
class EqualNode(LeafNode):
def dooperation(self):
#find way to have assignment function
#or maybe i don't even need it
return "gonna be"
class LessNode(LeafNode):
def dooperation(self):
return operator.lt
class GreaterNode(LeafNode):
def dooperation(self):
return operator.gt
class TwoEqualNode(LeafNode):
def dooperation(self):
return operator.eq
class LessOrEqualNode(LeafNode):
def dooperation(self):
return operator.le
class EqualOrGreaterNode(LeafNode):
def dooperation(self):
return operator.ge
class WordNode(LeafNode):
def dooperation(self):
return self.token.value
class OperatorNode(Node):
def dooperation(self):
return self.childrens[0].dooperation()
class NumberNode(LeafNode):
def dooperation(self):
return self.token.value
class PlusNode(LeafNode):
def dooperation(self):
return operator.add
class MinusNode(LeafNode):
def dooperation(self):
return operator.sub
class TimesNode(LeafNode):
def dooperation(self):
return operator.mul
class DivideNode(LeafNode):
def dooperation(self):
return operator.div
class MathOpNode(Node):
def dooperation(self):
if len(self.childrens) == 3:
op_func = self.childrens[1].dooperation()
arg_1 = self.childrens[0].dooperation()
arg_2 = self.childrens[2].dooperation()
return op_func(arg_1,arg_2)
else:
return self.childrens[0].dooperation()
def flatten(listl):
for element in listl:
if isinstance(element, Iterable) and not isinstance(element, basestring):
for sub in flatten(element):
yield sub
else:
yield element
def flattenlistoftuples(listoftuples):
for element in listoftuples:
if isinstance(element, Iterable) and not isinstance(element, basestring) \
and not isinstance(element, tuple):
for sub in flatten(element):
yield sub
else:
yield element
def getjsonobject(paramlist, loaded_json_string, conditions=None, func=None):
"""Returns json object, where paramlist is 'path' to it.
If path to it is not valid a.k.a object doesn't exists
it will return None"""
#TODO refactor this method , so it will use func(which can be append or del) instead append
#TODO refactor it so it will become generator and thus make result redundant
jsonobject = reduce(dict.get, paramlist, loaded_json_string)
if conditions is not None:
result = []
for jo in jsonobject:
evaluated_conditions = [condition[1](getjsonobject(condition[0], jo), condition[2]) \
for condition in conditions]
if all(evaluated_conditions) and evaluated_conditions:
#print jo, "ovde se desava neka magija"
result.append(jo)
return result
else:
return jsonobject
def delete_from_json(path_to_object, json_object, what_to_delete, conditions=None):
"""
:rtype : dict
"""
jsonobject = reduce(dict.get, path_to_object + what_to_delete, json_object)
if conditions is not None:
to_delete = []
for index, jo in enumerate(jsonobject):
evaluated_conditions = [condition[1](getjsonobject(condition[0], jo), condition[2])
for condition in conditions]
if all(evaluated_conditions) and evaluated_conditions:
#print jo, "ovo se brise"
#del jo #throws RuntimeError: dictionary changed size during iteration
to_delete.append(index)
for todel in to_delete:
del jsonobject[todel]
return json_object
else:
del jsonobject
return json_object
nodes = {"baseexpr": BaseExprNode,
"strongexpr": StrongExprNode,
"expr": ExprNode,
"queryexpr": QueryNode,
"removeexpr": RemoveExprNode,
"addexpr": AddExprNode,
"updateexpr": UpdateExprNode,
"getexpr": GetExprNode,
"wut": WutNode,
"object": ObjectNode,
"condition": ConditionNode,
"basiccondition": BasicConditionNode,
"value": ValueNode,
"jsonstring": JsonStringNode,
"mathexpr": MathExprNode,
"stringexpr": StringExprNode,
"variable": VariableNode,
"comparisonop": ComparisonOpNode,
"less": LessNode,
"greater": GreaterNode,
"lessorequal": LessOrEqualNode,
"equalorgreater": EqualOrGreaterNode,
"twoequal": TwoEqualNode,
"equal": EqualNode,
"word": WordNode,
"number": NumberNode,
"operator": OperatorNode,
"plus": PlusNode,
"minus": MinusNode,
"times": TimesNode,
"divide": DivideNode
}
#there is a need for "cushion" node
grammar = {"baseexpr": [["strongexpr"]],
"strongexpr": [["variable", "equal", "lcurlyb", "expr", "rcurlyb"], ["expr"]], #fix this shit
"expr": [["queryexpr"], ["mathexpr"], ["stringexpr"]],
"variable": [["var", "word"]],
"queryexpr": [["removeexpr"], ["addexpr"], ["updateexpr"], ["getexpr"]],
"removeexpr": [["from", "object", "remove", "wut"]],
"getexpr": [["from", "object", "get", "wut"]],
"addexpr": [["to", "wut", "add", "jsonstring_start", "jsonstring", "jsonstring_end"]],
"updateexpr": [["update", "wut", "to", "jsonstring_start", "jsonstring", "jsonstring_end"]],
"object": [["word", "arrow", "object"], ["word"]],
"condition": [["basiccondition", "and", "condition"], ["basiccondition"]],
"basiccondition": [["object", "comparisonop", "value"]],
"value": [["word"], ["number"]],
"wut": [["object", "where", "condition"], ["object"]],
"comparisonop": [["less"], ["greater"], ["twoequal"], ["lessorequal"], ["greaterorequal"]],
"mathexpr": [["number", "operator", "mathexpr"], ["number"]],
"operator": [["plus"], ["minus"], ["times"], ["divide"]],
"stringexpr": [[]],
}
def do_it(query):
token_list = breakDownStringToTokens(query)
parser = ParseText(grammar,"baseexpr")
print token_list
if parser.parse(token_list):
#parser.parse(["number", "minus", "number", "and","number","plus","number"]):
b = BaseExprNode()
#p = createnode(nodes["baseexpr"])
# print p, "ovo"
ast = AST(token_list,b,grammar,nodes)
ast.createtree("baseexpr", parser.where_was_i)
# print ast.stack2
#print json.dumps(ast.stack2[0].dooperation(), indent=4, sort_keys=True)
print ast.stack2[0].dooperation()
print ast.stack2
else:
print "nope doin"
do_it("to tim->igraci where id == prvi add '{\"Novi atribut\" : \"I njegov kljuc\"}'")
#do_it("update tim->igraci where id == prvi to '{\"hej ovo je\":\"nesto novo\"}'")
#do_it("from tim get igraci where id == prvi")
if __name__ == '__main__':
#print globals()[nodes["baseexpr"]]
#print getattr("BaseExprNode")
#do_it("5 + 5")
pass