34. La notación polaca de Odoo
Odoo trabaja con notación polaca prefija por ejemplo
["|", ("active", "=", False), ("active", "=", True)]
Pero tanto en Python com en SQL se utiliza la notación infija
if (a>3 or b<=4)
where (age>30 and isAvalible=True)
Vamos a realizar una opción para convertir la notación infija a prefija
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 | import copy import numbers # ------Imprescindible para poder importar de otras carpetas (de basicutils) import sys from pathlib import Path for i in range(2):sys.path.append(str(Path(__file__).parents[i])) try: # if in the same folder then needs a try and import directly from basicutils import xmutils except Exception as error: import xmutils # ------Fin imprescindible spaces=' ' def toPolish(cond:str, pos=0, indent=0): #print (indent* spaces+ 'call toPolish('+cond+', pos='+str(pos),'strNet='+cond[pos:]+')') myDict={"var1":'', "var2":'', "oper":''} word='' afterSpace=False i=pos while i<len(cond): if (len(word)==0 or afterSpace) and cond[i].lower() in ['a','o','n']: i, anOper=getOperator(cond,i, indent+1) if len(anOper)>0: if len(word)>0: if len(myDict['var1'])==0:myDict['var1']=word elif len(myDict['var2'])==0:myDict['var2']=word if len(myDict['oper'])==0:myDict['oper']=anOper elif anOper in ['and','or']: myDict1=copy.deepcopy(myDict) myDict['var1']=myDict1 myDict['var2']='' myDict['oper']=anOper elif anOper in ['not']: #print(indent*spaces+'toPolish in not word:'+word) if len(myDict['var2'])==0: myDict1={"oper":anOper} i,myDict1["var1"]=getExpressionAfterNot(cond,i, indent+1) if len(myDict['var1'])==0:myDict['var1']=myDict1 elif len(myDict['var2'])==0:myDict['var2']=myDict1 else: raise Exception("Error en toPolish: ya hay dos operandos aqui") word='' if i<len(cond): if (cond[i].lower()>='a' and cond[i].lower()<='z') or \ '0'<=cond[i]<='9' or \ cond[i] in ["_","-","=","!",">","<"]: word+=cond[i] afterSpace=False i+=1 elif cond[i]=="'": i,word=getWordInQuotes(cond,i+1, word, indent+1) afterSpace=False elif cond[i]==' ': afterSpace=True word=word+cond[i] while i<len(cond) and cond[i]==' ': i+=1 #if cond[i] in[' ',"-","=",">","<","'"]: # continue #else : word+=cond[i-1] #if cond[i] in[' ']: continue #elif cond[i] in["-","=",">","<","'"]: # word+=cond[i-1] elif cond[i]=='(': if len(word.strip())>0: #print(indent*spaces+' toPolish word0:'+word) if len(myDict['var1'])==0:myDict['var1']=word elif len(myDict['var2'])==0:myDict['var2']=word else: raise Exception("Error en toPolish: ya hay dos operandos") word='' i,word=getParentesis(cond,i,indent+1) #print(indent*spaces+' toPolish wordA:'+str(word)) if isinstance(word, str) and len(word)>0: afterSpace=True elif isinstance(word, dict): if len(str(myDict['var1']).strip())==0:myDict['var1']=word elif len(str(myDict['var2']).strip())==0:myDict['var2']=word else: raise Exception("Error en toPolish: ya hay dos operandos") word='' else: i+=1 if len(word.strip())>0: #print(indent*spaces+' toPolish:word1:'+str(word)) if len(str(myDict['var1']).strip())==0:myDict['var1']=word elif len(str(myDict['var2']).strip())==0:myDict['var2']=word else: raise Exception("Error en toPolish: ya hay dos operandos") if len(myDict['oper'])==0: #print (indent*spaces+'toPolish: return var1:'+str(myDict['var1'])) return myDict['var1'] else: #print (indent*spaces+'toPolish: return dict:'+str(myDict)) return myDict def getOperator(cond,i, indent): #print(indent*' '+'getOperator('+cond+','+str(i)+',strNet='+cond[i:]+')') j=i;oper='' if cond[i:i+4].lower() in ['and ','and(']: j=i+3;oper='and' elif cond[i:i+3].lower() in ['or ','or(']: j= i+2;oper='or' elif cond[i:i+4].lower() in ['not ','not(']: j=i+3;oper='not' else: j=i;oper='' #print (indent*spaces+'getOperator return j:'+str(j)+',oper:'+str(oper)+',strNet='+cond[i:]+')') return j,oper def getWordInQuotes(cond: str, i:int,word, indent): #print(indent*spaces+'getWordInQuotes(cond:'+cond+',i:'+str(i)+',word:'+str(word)+')') j=cond.find("'",i)+1 word+="'"+cond[i:j+1] #print(indent*spaces+'getWordInQuotes return j:'+str(j)+',word:'+str(word)+',strNet='+cond[i:]+')') return j,word def getParentesis(cond:str,pos:int, indent): #print(indent*spaces+'getParentesis( cond:'+cond+',pos:'+str(pos)+',strNet='+cond[pos:]+')') i=pos+1 nParentesis=1 while nParentesis>0 and i<len(cond): i+=1 if cond[i]=='(': nParentesis+=1 elif cond[i]==')': nParentesis-=1 myVar= toPolish(cond[pos+1:i],indent=indent+1) #print(indent*spaces+'getParentesis return i:'+str(i+1)+',myVar:'+str(myVar)+',strNet='+cond[i+1:]+')') return i+1, myVar def getExpressionAfterNot(cond:str, pos:int, indent): #print(indent*spaces+'getExpressionAfterNot(cond:'+cond+', pos:'+str(pos)+'strNet:'+cond[pos:]+')') i=pos word='' while i<len(cond): if cond[i]==' ': i+=1 continue elif cond[i]=='(': #edu1 #j,word=getParentesis(cond,i) #return i,word return getParentesis(cond,i, indent+1) elif cond[i].lower() in ['a','o','n']: j, anOper=getOperator(cond,i,indent+1) if len(anOper)>0: return i, word else: word+=cond[i] i+=1 else: word+=cond[i] i+=1 #print(indent*spaces+'getExpressionAfterNot return i:'+str(i)+',word:'+str(word)) return i, word def evalExpressionDict(myDict:object, dList:list=[], indent:int=0, conditionAsTuple:bool=True): if isinstance(myDict,dict): oper=myDict.get('oper') var1=myDict.get('var1') var2=myDict.get('var2') if oper is not None and len(oper)>0: dList.append(oper.replace('and','&').replace('or','|').replace('not','!')) if var1 is not None and len(var1)>0: dList=evalExpression(var1,dList, indent+1,conditionAsTuple) if var2 is not None and len(var2)>0: dList=evalExpression(var2,dList, indent+1,conditionAsTuple) else: dList.append(evalStringExpression(myDict, indent+1,conditionAsTuple)) #print(indent*spaces+'evalExpressionDict return dList:'+str(dList)) return dList def evalExpression(expr:object, dList:list, indent:int=0,conditionAsTuple=True): if isinstance(expr,dict): dList=evalExpressionDict(expr,dList, indent+1,conditionAsTuple) else: dList.append(evalStringExpression(expr, indent+1,conditionAsTuple)) #print(indent*spaces+'evalExpression return dList:'+str(dList)) return dList def evalStringExpression(expr:str, indent:int=0, conditionAsTuple=True): i=0 word='' var1='' var2='' oper='' afterSpace=False #if expr=='cc>0': # print ('voila') while i<len(expr): if expr[i] in ['!','=','>','<',' ']: afterSpace=True if expr[i]==' ': i+=1 continue if (len(word)==0 or afterSpace) and expr[i].lower() in ['!','=','>','<','l','i','not','c']: i, aTermOper=getTermOperator(expr,i, indent+1) if len(aTermOper)>0: oper=aTermOper if len(word)>0: if len(var1)==0:var1=word #else: raise Exception("Error en evalStringExpression: ya se ha dado valor a var1 previamente") word='' if len(var2)==0: var2=expr[i:].strip() #remove single quotes if var2[0]=="'": var2=var2[1:-1] else: if var2=='True':var2=True elif var2=='False':var2=False else: #aNumber=xmutils.isNumber(var2) aNumber=None if var2.replace('.','',1).isdigit(): aNumber=float(var2) if '.' in var2 else int(var2) if aNumber is not None: var2=aNumber if isinstance(var2,str) and var2[-1]=="'":var2=var2[:-1] i=len(expr) if len(var1)==0: word+=expr[i] i+=1 #print ('i='+str(i)) #print ('word='+str(word)) #print ('expr='+str(expr)) if conditionAsTuple: aTuple=(var1, oper, var2) else: aTuple=[var1,oper,var2] #print(indent*spaces+'evalStringExpression return aTuple:'+str(aTuple)) return aTuple def getTermOperator(cond:str ,pos:int, indent:int=0): #print(indent*' '+'getTermOperator('+cond+','+str(pos)+',strNet='+cond[pos:]+')') j=pos;oper='';ok=False myDict={ 1:['>','<','='], 2:['or','is','!=','<=','>=','=?','in'], 3:['not','and'], 4:['like'], 5:['ilike','=like'], 6:['is not','=ilike','not in'], 7:['----NO NE HI HA CAP----'], 8:['not like','child of'], 9:['not ilike'] } i=9 while i>0 and not ok: if cond[pos:pos+i].lower() in myDict[i]:ok=True else: i-=1 if ok: j=pos+i; oper=cond[pos:pos+i].lower() #print (indent*spaces+'getTermOperator return j:'+str(j)+',oper:'+str(oper)+',strNet='+cond[i:]+')') return j,oper def getDomainExpression(cond:str, conditionAsTuple:bool=True): myDict=toPolish(cond) print('') print(myDict) print('') aList=evalExpressionDict(myDict, dList=[], indent=0, conditionAsTuple=conditionAsTuple) return aList if __name__ == "__main__": mlist=[ "id = 7259 and (active = True or active = False)", "a ilike '%pepe%'", "not javi>3", "(a>'julio')", "a>'pepe' and not b<'Marta'", "(a>'pepe' and not b<'Marta')", "aa>0 AND (pepe<'edu')", "aa>0 AND (pepe<'edu' or maria>'juan') And (jaime<5 or not(javi>=12))", "aa>'123' and bb<'ddd' and cc>0 or (ee=23 and ff=100)", "aa>'123' and not(b<'Marta' or c>12)", "(pepe<'edu' or maria>'juan') And (jaime<5 or not(javi>=12))", "aa>0 AND (pepe<'edu' or maria>'juan') And (jaime<5 or not(javi>=12))", "not(aa>0 AND (pepe<'edu' or maria>'juan') And (jaime<5 or not(javi>=12)))" ] for st in mlist: print (st) print (getDomainExpression(st, conditionAsTuple=False)) print("--------------------------------------") #print(st) #myDict=toPolish(st) #print (myDict) #print ('---Domain---') #print (evalExpressionDict(myDict)) #print('----') #print('') |
Al final en el "__main__" se muestran ejemplos para ver copmo convierte de notación infija a prefija.
Comentarios
Publicar un comentario