def execute(self, environment): newEnv = Environment(environment, dbtemp) self.fromcl.execute(newEnv) if self.params: params = [] for p in self.params: if isinstance(p, expression.TableAll): result = p.execute(newEnv) for r in result: params.append(r) else: params.append(p) labels = [p.temp for p in params] value = [p.execute(newEnv).value for p in params] else: value = [newEnv.dataFrame[p] for p in newEnv.dataFrame] labels = [p for p in newEnv.dataFrame] for i in range(len(labels)): newEnv.dataFrame[labels[i]] = value[i] if self.wherecl == None: return newEnv.dataFrame.filter(labels) wh = self.wherecl.execute(newEnv) w2 = wh.filter(labels) # Si la clausula WHERE devuelve un dataframe vacio if w2.empty: return None return [w2, environment.types]
def execute(self, environment): # Verificamos que no pueden venir mas de 1 tabla en el clausula FROM if len(self.fromcl.tables) > 1: return "Error: syntax error at or near ','" newEnv = Environment(environment, dbtemp) self.fromcl.execute(newEnv) value = [newEnv.dataFrame[p] for p in newEnv.dataFrame] labels = [p for p in newEnv.dataFrame] for i in range(len(labels)): newEnv.dataFrame[labels[i]] = value[i] if self.wherecl == None: return newEnv.dataFrame.filter(labels) wh = self.wherecl.execute(newEnv) w2 = wh.filter(labels) # Si la clausula WHERE devuelve un dataframe vacio if w2.empty: return "Operacion DELETE completada" # Logica para eliminar table = self.fromcl.tables[0].name pk = Struct.extractPKIndexColumns(dbtemp, table) # Se obtienen las parametros de las llaves primarias para proceder a eliminar rows = [] if pk: for row in w2.values: rows.append([row[p] for p in pk]) else: rows.append([i for i in w2.index]) print(rows) # TODO: La funcion del STORAGE esta bugueada """ for row in rows: result = jsonMode.delete(dbtemp, table, row) print(result) """ return "Operacion DELETE completada"
def execute(self, environment): try: Struct.load() # Verificamos que no pueden venir mas de 1 tabla en el clausula FROM if len(self.fromcl.tables) > 1: instruction.semanticErrors.append( ["Error sintactico cerco e en ','", self.row]) instruction.syntaxPostgreSQL.append( "Error: 42601: Error sintactico cerca de , en la linea " + str(self.row)) return "Error: syntax error at or near ','" newEnv = Environment(environment, instruction.dbtemp) instruction.envVariables.append(newEnv) self.fromcl.execute(newEnv) value = [newEnv.dataFrame[p] for p in newEnv.dataFrame] labels = [p for p in newEnv.dataFrame] for i in range(len(labels)): newEnv.dataFrame[labels[i]] = value[i] if self.wherecl == None: w2 = newEnv.dataFrame.filter(labels) else: wh = self.wherecl.execute(newEnv) w2 = wh.filter(labels) # Si la clausula WHERE devuelve un dataframe vacio if w2.empty: return "Operacion UPDATE completada" # Logica para realizar el update table = self.fromcl.tables[0].name pk = Struct.extractPKIndexColumns(instruction.dbtemp, table) # Se obtienen las parametros de las llaves primarias para proceder a eliminar rows = [] if pk: for row in w2.values: rows.append([row[p] for p in pk]) else: rows.append([i for i in w2.index]) print(rows) # Obtenemos las variables a cambiar su valor ids = [p.id for p in self.values] values = [p.execute(newEnv).value for p in self.values] ids = Struct.getListIndex(instruction.dbtemp, table, ids) if len(ids) != len(values): return "Error: Columnas no encontradas" temp = {} for i in range(len(ids)): temp[ids[i]] = values[i] print(temp, rows) # TODO: La funcion del STORAGE esta bugueada bug = False for row in rows: result = jsonMode.update(instruction.dbtemp, table, temp, rows) if result != 0: bug = True break if bug: return ["Error: Funcion UPDATE del Storage", temp, rows] return "Operacion UPDATE completada" except: instruction.syntaxPostgreSQL.append( "Error: P0001: Error en la instruccion UPDATE")
def execute(self, environment): newEnv = Environment(environment, dbtemp) self.fromcl.execute(newEnv) value = [p.execute(newEnv).value for p in self.params] labels = [p.temp for p in self.params] for i in range(len(labels)): newEnv.dataFrame[labels[i]] = value[i] if self.wherecl == None: return newEnv.dataFrame.filter(labels) wh = self.wherecl.execute(newEnv) w2 = wh.filter(labels) return w2
def execute(self, environment): try: # Verificamos que no pueden venir mas de 1 tabla en el clausula FROM if len(self.fromcl.tables) > 1: syntaxErrors.append(["Error sintactico cerca de ,", self.row]) syntaxPostgreSQL.append( "Error: 42601: Error sintactico cerca de , en la linea " + str(self.row) ) return "Error: syntax error at or near ','" newEnv = Environment(environment, dbtemp) global envVariables envVariables.append(newEnv) self.fromcl.execute(newEnv) value = [newEnv.dataFrame[p] for p in newEnv.dataFrame] labels = [p for p in newEnv.dataFrame] for i in range(len(labels)): newEnv.dataFrame[labels[i]] = value[i] if self.wherecl == None: return newEnv.dataFrame.filter(labels) wh = self.wherecl.execute(newEnv) w2 = wh.filter(labels) # Si la clausula WHERE devuelve un dataframe vacio if w2.empty: return "Operacion DELETE completada" # Logica para eliminar table = self.fromcl.tables[0].name pk = Struct.extractPKIndexColumns(dbtemp, table) # Se obtienen las parametros de las llaves primarias para proceder a eliminar rows = [] if pk: for row in w2.values: rows.append([row[p] for p in pk]) else: rows.append([i for i in w2.index]) print(rows) # TODO: La funcion del STORAGE esta bugueada bug = False for row in rows: result = jsonMode.delete(dbtemp, table, row) if result != 0: bug = True break if bug: return ["Error: Funcion DELETE del Storage", rows] return "Operacion DELETE completada" except: syntaxPostgreSQL.append("Error: P0001: Error en la instruccion DELETE")
def execute(self, environment): try: newEnv = Environment(environment, instruction.dbtemp) instruction.envVariables.append(newEnv) labels = [] values = {} for i in range(len(self.params)): v = self.params[i].execute(newEnv) values[self.params[i].temp] = [v.value] labels.append(self.params[i].temp) newEnv.types[labels[i]] = v.type newEnv.dataFrame = pd.DataFrame(values) return [newEnv.dataFrame, newEnv.types] except: instruction.syntaxPostgreSQL.append( "Error: P0001: Error en la instruccion SELECT")
def execute(self, environment): newEnv = Environment(environment, instruction.dbtemp) instruction.envVariables.append(newEnv) s1 = self.s1.execute(newEnv) s2 = self.s2.execute(newEnv) df1 = s1[0] df2 = s2[0] types1 = list(s1[1].values()) types2 = list(s2[1].values()) if len(df1.columns) != len(df2.columns): instruction.syntaxPostgreSQL.append( "Error: 42611: INTERSEC definicion en numero de columnas invalida " ) return "Error: El numero de columnas no coinciden" for i in range(len(types1)): if types1[i] != types2[i]: instruction.semanticErrors.append( ["Error discrepancia de tipo de datos entre columnas", self.row] ) instruction.syntaxPostgreSQL.append( "Error: 42804: discrepancia de tipo de datos entre columnas " ) return "Error: Los tipos de columnas no coinciden" df = df1.merge(df2).drop_duplicates(ignore_index=True) return [df, types1]
def execute(self, environment): newEnv = Environment(environment, instruction.dbtemp) instruction.envVariables.append(newEnv) s1 = self.s1.execute(newEnv) s2 = self.s2.execute(newEnv) df1 = s1[0] df2 = s2[0] types1 = list(s1[1].values()) types2 = list(s2[1].values()) if len(df1.columns) != len(df2.columns): instruction.syntaxPostgreSQL.append( "Error: 42611: EXCEPT definicion en numero de columnas invalida " ) return "Error: El numero de columnas no coinciden" for i in range(len(types1)): if types1[i] != types2[i]: instruction.semanticErrors.append( ["Error discrepancia de tipo de datos entre columnas", self.row] ) instruction.syntaxPostgreSQL.append( "Error: 42804: discrepancia de tipo de datos entre columnas" ) return "Error: Los tipos de columnas no coinciden" df = df1.merge(df2, how="outer", indicator=True).loc[ lambda x: x["_merge"] == "left_only" ] del df["_merge"] return [df, types1]
def execute(self, environment): newEnv = Environment(environment, dbtemp) global envVariables envVariables.append(newEnv) s1 = self.s1.execute(newEnv) s2 = self.s2.execute(newEnv) df1 = s1[0] df2 = s2[0] types1 = list(s1[1].values()) types2 = list(s2[1].values()) if len(df1.columns) != len(df2.columns): syntaxPostgreSQL.append( "Error: 42611: UNION definicion en numero de columnas invalida " ) return "Error: El numero de columnas no coinciden" for i in range(len(types1)): if types1[i] != types2[i]: semanticErrors.append( ["Error discrepancia de tipo de datos entre columnas", self.row] ) syntaxPostgreSQL.append( "Error: 42804: discrepancia de tipo de datos entre columnas " ) return "Error: Los tipos de columnas no coinciden" df = pd.concat([df1, df2], ignore_index=True) return df
def generate3d(self, environment, instanciaAux): #Agregacion a la tabla for (nombre, tipo) in self.params: valores = defaultValues(tipo[0]) SymbolTable.add_symbol(nombre, valores[0], valores[1], 0, 0, None) header = f'\n@with_goto\ndef {self.name}(' # solo le quite la f :v for param in range(len(self.params)): header += self.params[param][0] if param != len(self.params) - 1: header += "," header += '):' eFinal = instanciaAux.getNewLabel() newEnv = Environment(environment) newEnv.addVar('eFinal', eFinal, 'Etiqueta', self.row, self.column) instanciaAux.addToCode(header) self.block.generate3d(newEnv, instanciaAux) SymbolTable.symbolTable.clear() instanciaAux.addToCode(f'\tlabel .{eFinal}')
def execute(self, environment): try: # Verificamos que no pueden venir mas de 1 tabla en el clausula FROM if len(self.fromcl.tables) > 1: return "Error: syntax error at or near ','" newEnv = Environment(environment, dbtemp) self.fromcl.execute(newEnv) value = [newEnv.dataFrame[p] for p in newEnv.dataFrame] labels = [p for p in newEnv.dataFrame] for i in range(len(labels)): newEnv.dataFrame[labels[i]] = value[i] if self.wherecl == None: w2 = newEnv.dataFrame.filter(labels) else: wh = self.wherecl.execute(newEnv) w2 = wh.filter(labels) # Si la clausula WHERE devuelve un dataframe vacio if w2.empty: return "Operacion UPDATE completada" # Logica para realizar el update table = self.fromcl.tables[0].name pk = Struct.extractPKIndexColumns(dbtemp, table) # Se obtienen las parametros de las llaves primarias para proceder a eliminar rows = [] if pk: for row in w2.values: rows.append([row[p] for p in pk]) else: rows.append([i for i in w2.index]) print(rows) # Obtenemos las variables a cambiar su valor ids = [p.id for p in self.values] values = [p.execute(newEnv).value for p in self.values] print(ids, values) # TODO: La funcion del STORAGE esta bugueada return "Operacion UPDATE completada" except: raise
def getc3d(input): """ docstring """ querys = [] messages = [] result = grammar.parse(input) lexerErrors = grammar.returnLexicalErrors() syntaxErrors = grammar.returnSyntacticErrors() tabla = Environment() if len(lexerErrors) + len(syntaxErrors) == 0 and result: for v in result: if isinstance(v, inst.Select) or isinstance( v, inst.SelectOnlyParams): r = v.c3d(tabla) if r: list_ = r[0].values.tolist() labels = r[0].columns.tolist() querys.append([labels, list_]) else: querys.append(None) else: r = v.c3d(tabla) messages.append(r) semanticErrors = grammar.returnSemanticErrors() PostgresErrors = grammar.returnPostgreSQLErrors() symbols = symbolReport() obj = { "messages": messages, "querys": querys, "lexical": lexerErrors, "syntax": syntaxErrors, "semantic": semanticErrors, "postgres": PostgresErrors, "symbols": symbols, "codigo": tabla.codigo, } astReport() BnfGrammar.grammarReport() return obj
import sys sys.path.append("../../..") from analizer.abstract import instruction from analizer.reports import Nodo from analizer.symbol.environment import Environment indexEnv = Environment(None, for3d=True) indicesReg = dict() class Index(instruction.Instruction): def __init__(self, indice, tabla, campos, tipo, row, column) -> None: self.index = indice self.table = tabla self.fields = campos self.type = tipo super().__init__(row, column) def execute(self, environment): campos = 'Campos: ' if isinstance(self.fields, list): for index in range(len(self.fields)): if index == len(self.fields) - 1: campos += self.fields[index] + ';' else: campos += self.fields[index] + ', ' else: campos += self.fields + ';' valor = 'Tabla: ' + self.table + '; ' + campos
def execute(self, environment): try: newEnv = Environment(environment, instruction.dbtemp) instruction.envVariables.append(newEnv) self.fromcl.execute(newEnv) if self.wherecl != None: self.wherecl.execute(newEnv) if self.groupbyCl != None: newEnv.groupCols = len(self.groupbyCl) groupDf = None groupEmpty = True if self.params: params = [] for p in self.params: if isinstance(p, TableAll): result = p.execute(newEnv) for r in result: params.append(r) else: params.append(p) labels = [p.temp for p in params] if self.groupbyCl != None: value = [] for i in range(len(params)): ex = params[i].execute(newEnv) val = ex.value newEnv.types[labels[i]] = ex.type # Si no es columna de agrupacion if i < len(self.groupbyCl): if not ( isinstance(val, pd.core.series.Series) or isinstance(val, pd.DataFrame) ): nval = { val: [ val for i in range(len(newEnv.dataFrame.index)) ] } nval = pd.DataFrame(nval) val = nval newEnv.dataFrame = pd.concat( [newEnv.dataFrame, val], axis=1 ) else: if groupEmpty: countGr = newEnv.groupCols # Obtiene las ultimas columnas metidas (Las del group by) df = newEnv.dataFrame.iloc[:, -countGr:] cols = list(df.columns) groupDf = df.groupby(cols).sum().reset_index() groupDf = pd.concat([groupDf, val], axis=1) groupEmpty = False else: groupDf = pd.concat([groupDf, val], axis=1) if groupEmpty: countGr = newEnv.groupCols # Obtiene las ultimas columnas metidas (Las del group by) df = newEnv.dataFrame.iloc[:, -countGr:] cols = list(df.columns) groupDf = df.groupby(cols).sum().reset_index() groupEmpty = False else: value = [p.execute(newEnv) for p in params] for j in range(len(labels)): newEnv.types[labels[j]] = value[j].type newEnv.dataFrame[labels[j]] = value[j].value else: value = [newEnv.dataFrame[p] for p in newEnv.dataFrame] labels = [p for p in newEnv.dataFrame] if value != []: if self.wherecl == None: df_ = newEnv.dataFrame if self.orderByCl: df_ = self.orderByCl.execute(df_, newEnv) df_ = df_.filter(labels) if self.limitCl: df_ = self.limitCl.execute(df_, newEnv) if self.distinct: return [df_.drop_duplicates(), newEnv.types] return [df_, newEnv.types] df_ = newEnv.dataFrame if self.orderByCl: df_ = self.orderByCl.execute(df_, newEnv) df_ = df_.filter(labels) if self.limitCl: df_ = self.limitCl.execute(df_, newEnv) if self.distinct: return [df_.drop_duplicates(), newEnv.types] return [df_, newEnv.types] else: newNames = {} i = 0 for (columnName, columnData) in groupDf.iteritems(): newNames[columnName] = labels[i] i += 1 groupDf.rename(columns=newNames, inplace=True) df_ = groupDf if self.limitCl: df_ = self.limitCl.execute(df_, newEnv) if self.orderByCl: df_ = self.orderByCl.execute(df_, newEnv) if self.distinct: return [df_.drop_duplicates(), newEnv.types] return [df_, newEnv.types] except: instruction.syntaxPostgreSQL.append( "Error: P0001: Error en la instruccion SELECT" )
from datetime import datetime import sys sys.path.append("../../..") from analizer.abstract import instruction from analizer.reports.Nodo import Nodo from analizer.symbol.environment import Environment import analizer.symbol.c3dSymbols as SymbolTable from analizer.abstract.expression import TYPE envProcedure = Environment(for3d=True) class Procedure(instruction.Instruction): def __init__(self, name, params, block, row, column) -> None: self.params = params self.block = block self.name = name super().__init__(row, column) def generate3d(self, environment, instanciaAux): for (nombre, tipo) in self.params: valores = defaultValues(tipo[0]) SymbolTable.add_symbol(nombre, valores[0], valores[1], 0, 0, None) header = f'\n@with_goto\ndef p{self.name}(' for param in range(len(self.params)): header += self.params[param][0] if param != len(self.params) - 1: header += "," header += '):'
import sys from datetime import datetime sys.path.append("../../..") from analizer.abstract import instruction from analizer.reports.AST import AST from analizer.symbol.environment import Environment import analizer.symbol.c3dSymbols as SymbolTable from analizer.abstract.expression import TYPE from analizer.reports.Nodo import Nodo envFunction = Environment(for3d=True) class Function(instruction.Instruction): def __init__(self, name, type_, params, block, row, column) -> None: self.params = params self.block = block self.name = name self.type = type_ super().__init__(row, column) def generate3d(self, environment, instanciaAux): #Agregacion a la tabla for (nombre, tipo) in self.params: valores = defaultValues(tipo[0]) SymbolTable.add_symbol(nombre, valores[0], valores[1], 0, 0, None) header = f'\n@with_goto\ndef {self.name}(' # solo le quite la f :v for param in range(len(self.params)): header += self.params[param][0]
import pickle from analizer.abstract import instruction as inst from analizer.symbol.environment import Environment from prettytable import PrettyTable with open("obj.pickle", "rb") as f: result = pickle.load(f) pila = 0 eje_if = "Verdadero" tabla = Environment() def ejecutar(): cont = pila if isinstance(result[cont], inst.Select) or isinstance(result[cont], inst.SelectOnlyParams): r = result[cont].execute(tabla) if r: list_ = r[0].values.tolist() labels = r[0].columns.tolist() salidaTabla = PrettyTable() encabezados = labels salidaTabla.field_names = encabezados cuerpo = list_ salidaTabla.add_rows(cuerpo) print(salidaTabla) print("\n") print("\n") else: print("")