def ejecutar(self,ent:Entorno): tablas = [] result = [] self.encabezados = [] if self.nametable != None: tipo = self.nametable.tipo if tipo.tipo == 'identificador': nombre = self.nametable.getval(ent) self.ntabla = nombre tabla = ent.buscarSimbolo(nombre + "_" + ent.getDataBase()) if tabla != None: tablas.append(tabla) else: return "ERROR >> En la instrucción Delete, la tabla: "+self.ntabla+" NO EXISTE" if len(tablas) > 1: return "ERROR >> En la instrucción Delete, solo puede ingresar el nombre de una tabla" else: 'llenar resultado desde backend' real = tablas[0].nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) # filtros if self.exps != None: result = self.wheredelete(ent, tablas) else: return "ERROR >> En la instrucción Delete la expresión es incorrecta" return self.resultdelete(result,self.ntabla,ent.getDataBase())
def ejecutar(self, ent: Entorno): dbActual = ent.getDataBase() result = [] if dbActual != None: tabla: Simbolo = ent.buscarSimbolo(self.tabla + "_" + dbActual) if tabla != None: 'obtengo tabla' real = tabla.nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) columnas = tabla.valor 'lleno encabezado' for col in columnas: self.encabezado.append(col.nombre) for i in range(0, len(result)): resexp = self.resolver(self.where, ent, result, tabla, i) try: if resexp.valor: dic = {} 'busco la columna y le asigno el nuevo valor' for i in range(0, len(self.listaCampos)): nombrecol = self.listaCampos[i].columna expresion = self.listaCampos[i].exp contenido = expresion.getval(ent).valor for nocol in range(0, len(columnas)): if nombrecol == columnas[nocol].nombre: dic.update({nocol: contenido}) 'envio datos par update' llavePrim = [] for column in tabla.valor: prim: Simbolo = ent.buscarSimbolo( column.atributos.get('primary')) llavePrim = prim.valor break r = DBMS.update(dbActual, self.tabla, dic, llavePrim) if r == 0: variables.consola.insert( INSERT, 'Se ha actualizado un registro \n') except: reporteerrores.append( Lerrores( "Error Semantico", 'Error el resultado del where no es booleano', 0, 0)) variables.consola.insert( INSERT, 'Error el resultado del where no es booleano \n') else: variables.consola.insert( INSERT, "La tabla '" + self.tabla + "' que desea actualizar no existe\n") reporteerrores.append( Lerrores( "Error Semántico", "La tabla '" + self.tabla + "' que desea actualizar no existe", "", ""))
def ejecutar(self, ent: Entorno): completo = self.nombre + '_' + ent.getDataBase() tabla: Simbolo = ent.buscarSimbolo(completo) if tabla != None: columnas = tabla.valor if len(self.valores) == len(columnas): i = 0 correcto = True for columna in columnas: nombre = columna.nombre tipo = columna.tipo util = Tipo(None, None, -1, -1) if util.comparetipo(tipo, self.valores[i].tipo): 'todo correcto' else: correcto = False return 'Error los tipos de los valores no coinciden con la definicion de la tabla' i = i + 1 terminales = [] for val in self.valores: terminales.append(val.getval(ent)) print("T ", terminales) r = DBMS.insert(ent.getDataBase(), self.nombre, terminales) if (r == 4): return 'Error al Insertar Registro Violacion de Constraint Primary Key' return 'Registros insertados con exito'
def ejecutar(self, ent: Entorno): if (ent.getDataBase() == None): variables.consola.insert( INSERT, "ERROR >> En la instrucción Drop Table " + self.id + ", actualmente no hay ninguna base de datos en uso\n") reporteerrores.append( Lerrores( "Error Semántico", "En la instrucción Drop Table " + self.id + ", actualmente no hay ninguna base de datos en uso", "", "")) else: resultado = DBMS.dropTable(ent.getDataBase(), self.id) if (resultado == 0): ent.eliminarSimbolo(self.id + "_" + ent.getDataBase()) ent.eliminarSymTabla(self.id) variables.consola.insert( INSERT, "La tabla: (" + self.id + ") ha sido eliminada con exito\n") else: variables.consola.insert( INSERT, "ERROR >> En la instrucción Drop Table " + self.id + ", La tabla a eliminar NO EXISTE\n") reporteerrores.append( Lerrores( "Error Semántico", "En la instrucción Drop Table " + self.id + ", La tabla a eliminar NO EXISTE", "", ""))
def ejecutar(self, ent: Entorno): self.encabezado.clear() resultfiltro = [] resultfiltro.clear() llavesprim = [] llavesprim.clear() dbActual = ent.getDataBase() result = [] result.clear() if dbActual != None: tabla: Simbolo = ent.buscarSimbolo(self.tabla + "_" + dbActual) if tabla != None: 'obtengo tabla' real = tabla.nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) columnas = tabla.valor 'lleno encabezado' for col in columnas: self.encabezado.append(col.nombre) for i in range(0, len(result)): resexp = self.resolver(self.where, ent, result, tabla, i) try: if not resexp.valor: resultfiltro.append(result[i]) 'envio datos para delete' llavePrim = [] for column in tabla.valor: prim: Simbolo = ent.buscarSimbolo( column.atributos.get('primary')) if prim != None: llavePrim = prim.valor break except: reporteerrores.append( Lerrores( "Error Semantico", 'Error el resultado del where no es booleano', 0, 0)) variables.consola.insert( INSERT, 'Error el resultado del where no es booleano \n') llavesprim = llavePrim self.resultdelete(resultfiltro, self.tabla, ent.getDataBase(), llavesprim) else: variables.consola.insert( INSERT, "La tabla '" + self.tabla + "' que desea eliminar no existe\n") reporteerrores.append( Lerrores( "Error Semántico", "La tabla '" + self.tabla + "' que desea eliminar no existe", "", ""))
def ejecutar(self, ent:Entorno): if (ent.getDataBase()==None): return "ERROR >> En la instrucción Drop Table "+self.id+", actualmente no hay ninguna base de datos en uso" else: resultado = DBMS.dropTable(ent.getDataBase(),self.id) if (resultado==0): ent.eliminarSimbolo(self.id+"_"+ent.getDataBase()) return "La tabla: ("+self.id+") ha sido eliminada con exito" else: return "ERROR >> En la instrucción Drop Table "+self.id+", La tabla a eliminar NO EXISTE"
def ejecutar(self, ent: Entorno): #formato para el enum: ENUM_database_identificador nuevoType: Simbolo = Simbolo( TipoSimbolo.TYPE_ENUM, ("ENUM_" + ent.getDataBase() + "_" + self.id), self.contenido) nuevoType.baseDatos = ent.getDataBase() r = ent.nuevoSimbolo(nuevoType) if r == "ok": return "Nuevo tipo '" + self.id + "' creado" return "El tipo '" + self.id + "' ya existe declarado"
def ejecutar(self,ent:Entorno): #formato para el enum: ENUM_database_identificador nuevoType:Simbolo = Simbolo(TipoSimbolo.TYPE_ENUM,("ENUM_" + ent.getDataBase() + "_" + self.id),self.contenido) nuevoType.baseDatos = ent.getDataBase() r = ent.nuevoSimbolo(nuevoType) if r == "ok": variables.consola.insert(INSERT,"Nuevo tipo '" + self.id + "' creado\n") return variables.consola.insert(INSERT,"El tipo '" + self.id + "' ya existe declarado\n") reporteerrores.append(Lerrores("Error Semántico","El tipo '" + self.id + "' ya existe declarado","",""))
def ejecutar(self, ent: Entorno): dbActual = ent.getDataBase() result = [] if dbActual != None: tabla: Simbolo = ent.buscarSimbolo(self.tabla + "_" + dbActual) if tabla != None: 'obtengo tabla' real = tabla.nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) columnas = tabla.valor 'lleno encabezado' for col in columnas: self.encabezado.append(col.nombre) for i in range(0, len(result)): resexp = self.resolver(self.where, ent, result, tabla, i) try: if resexp.valor: 'envio datos par update' llavePrim = [] for column in tabla.valor: prim: Simbolo = ent.buscarSimbolo( column.atributos.get('primary')) llavePrim = prim.valor break #print("PK ----------",llavePrim) r = DBMS.delete(dbActual, self.tabla, llavePrim) #print("DELTEEEE ------------> ",r) if r == 0: variables.consola.insert( INSERT, 'Se ha eliminado un registro \n') except: reporteerrores.append( Lerrores( "Error Semantico", 'Error el resultado del where no es booleano', 0, 0)) variables.consola.insert( INSERT, 'Error el resultado del where no es booleano \n') else: variables.consola.insert( INSERT, "La tabla '" + self.tabla + "' que desea eliminar no existe\n") reporteerrores.append( Lerrores( "Error Semántico", "La tabla '" + self.tabla + "' que desea eliminar no existe", "", ""))
def ejecutar(self, ent: Entorno): 'Metodo Abstracto para ejecutar la instruccion' if self.distinct is None and self.froms is None and self.where is None and self.group is None and self.having is None and self.order is None and self.combinig is None: resultados = [] for exp in self.exps: if exp != None: resultados.append(exp.getval(ent)) return resultados elif self.froms != None and self.exps != None: tablas = [] for exp in self.froms: if exp != None: tipo = exp.tipo if tipo.tipo == 'identificador': nombre = exp.getval(ent) tabla = ent.buscarSimbolo(nombre) if tabla != None: tablas.append(tabla) #filtros #acceder a columnas if len(self.exps) == 1: if self.exps[0].getval(ent) == '*': result = [] for tabla in tablas: result.append( DBMS.extractTable(ent.getDataBase(), tabla.nombre)) return result
def ejecutar(self, ent: Entorno): dbActual = ent.getDataBase() if dbActual != None: tablaIndex: Simbolo = ent.buscarSimbolo(self.tabla + "_" + dbActual) if tablaIndex != None: for nombreCol in self.columnas: i = 0 fin = len(tablaIndex.valor) while i < fin: if nombreCol.valor == tablaIndex.valor[i].nombre: # IDX_database_tabla idIdex: str = "IDX_" + dbActual + "_" + self.tabla + "_" + self.iden + "_" + nombreCol.valor nuevoSym: Simbolo = Simbolo( TipoSimbolo.INDEX, idIdex, {}) nuevoSym.tabla = self.tabla nuevoSym.indexId = self.iden nuevoSym.baseDatos = dbActual nuevoSym.valor.update({ 'id': self.iden, 'columna': nombreCol.valor }) if self.unique: nuevoSym.valor.update({'unique': True}) if self.hash: nuevoSym.valor.update({'hash': True}) if self.orden != None: nuevoSym.valor.update({'orden': self.orden}) tablaIndex.valor[i].atributos.update( {'index': idIdex}) res = ent.nuevoSimbolo(nuevoSym) if res == "ok": variables.consola.insert( INSERT, "Se agregó nuevo index '" + self.iden + "' a la columna '" + nombreCol.valor + "'\n") else: variables.consola.insert( INSERT, "El nuevo index '" + self.iden + "' no se puede agregar porque ya existe.\n" ) reporteerrores.append( Lerrores( "Semántico", "El nuevo index '" + self.iden + "' no se puede agregar porque ya existe.\n", "", "")) break i = i + 1 else: variables.consola.insert( INSERT, "La tabla '" + self.tabla + "' a la que se le desea agregar el índice '" + self.iden + "' no existe.\n") reporteerrores.append( Lerrores( "Semántico", "La tabla '" + self.tabla + "' a la que se le desea agregar el índice '" + self.iden + "' no existe", "", ""))
def ejecutar(self, ent: Entorno): dbActual = ent.getDataBase() if dbActual != None: sym: Simbolo = ent.buscarIndex(self.iden) if sym != None: tabla: Simbolo = ent.buscarSimbolo(sym.tabla + "_" + dbActual) if tabla != None: columna = self.colIdx if isinstance(self.colIdx, int): if self.colIdx <= len(tabla.valor): columna = tabla.valor[self.colIdx - 1].nombre else: variables.consola.insert(INSERT, "El número '" + str( self.colIdx) + "' de columna en la tabla '" + sym.tabla + "' no existe.\n") reporteerrores.append(Lerrores("Semántico", "El número '" + str( self.colIdx) + "' de columna en la tabla '" + sym.tabla + "' no existe.", "", "")) return for col in tabla.valor: if col.nombre == columna: sym.valor.update({'columna': columna}) variables.consola.insert(INSERT, "El index '" + self.iden + "' ahora pertenece a la columna '" + columna + "'\n") return variables.consola.insert(INSERT, "La columna '" + columna + "' a la que desea cambiar el índice '" + self.iden + "' no existe.\n") reporteerrores.append(Lerrores("Semántico", "La columna '" + columna + "' a la que desea cambiar el índice '" + self.iden + "' no existe.", "", "")) else: variables.consola.insert(INSERT, "El index '" + self.iden + "' no existe \n") reporteerrores.append(Lerrores("Semántico", "El index '" + self.iden + "' no existe", "", ""))
def ejecutar(self, ent: Entorno): dbActual = ent.getDataBase() if dbActual != None: res = ent.eliminarIndex(self.iden) if res: variables.consola.insert(INSERT, "El índice '" + self.iden + "' se ha eliminado. \n") else: variables.consola.insert(INSERT, "El índice '" + self.iden + "' que desea eliminar no existe.\n") reporteerrores.append(Lerrores("Semántico","El índice '" + self.iden + "' que desea eliminar no existe.","",""))
def ejecutar(self, ent: Entorno): tablas = [] result = [] self.encabezado = [] 'Metodo Abstracto para ejecutar la instruccion' if self.distinct is None and self.froms is None and self.where is None and self.group is None and self.having is None and self.order is None and self.combinig is None: resultados = [] for exp in self.exps: if exp != None: resultados.append(exp.getval(ent)) return resultados elif self.froms != None and self.exps != None: for exp in self.froms: if exp != None: tipo = exp.tipo if tipo.tipo == 'identificador': nombre = exp.getval(ent) tabla = ent.buscarSimbolo(nombre + "_" + ent.getDataBase()) if tabla != None: tablas.append(tabla) if len(tablas) > 1: 'producto cartesiano' else: 'llenar resultado desde backend' real = tablas[0].nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) #filtros if self.where != None: result = self.execwhere(ent, tablas) #acceder a columnas if len(self.exps) == 1: if self.exps[0].getval(ent) == '*': self.mostarresult(result, 'prueba xd') elif self.exps[0].tipo.tipo == 'identificador': 'obtengo solo columnas pedidas' else: 'pendientes subconsultas y funciones'
def ejecutar(self, ent:Entorno): tam = len(self.listaDef) print (tam) nuevaTabla = Simbolo(TipoSimbolo.TABLA,self.id) listaColumnas = [] for x in range(0,tam,1): tt = self.listaDef[x] if tt.tipo == AtributosColumna.COLUMNA_SIMPLE: self.numColumnas += 1 nuevaColumna = Simbolo(tt.tipoDato,tt.identificador) listaColumnas.append(nuevaColumna) nuevaTabla.valor = listaColumnas dbActual = ent.getDataBase() if dbActual != None: estado = DBMS.createTable(dbActual,self.id, self.numColumnas) if estado == 0: nuevaTabla.baseDatos = dbActual ent.nuevoSimbolo(nuevaTabla) print("Tabla Creada") DBMS.showCollection()
def ejecutar(self, ent:Entorno): tabla:Simbolo = ent.buscarSimbolo(self.nombre) if tabla != None: columnas=tabla.valor if len(self.valores)== len(columnas): i=0 correcto=True for columna in columnas: nombre=columna.nombre tipo=columna.tipo util=Tipo(None,None,-1,-1) if util.comparetipo(tipo,self.valores[i].tipo): 'todo correcto' else: correcto=False return 'Error los tipos de los valores no coinciden con la definicion de la tabla' i=i+1 terminales = [] for val in self.valores: terminales.append(val.getval(ent)) DBMS.insert(ent.getDataBase(),tabla.nombre,terminales)
def ejecutar(self, ent:Entorno): completo=str(self.nombre+'_'+ ent.getDataBase()) tabla:Simbolo = ent.buscarSimbolo(completo) if tabla != None: columnas=tabla.valor i=0 contador=0 columnaunique=[] for columna in columnas: verificarnull=tabla.valor[i].atributos.get('not null') verificarprimary=tabla.valor[i].atributos.get('primary') verificarunique=tabla.valor[i].atributos.get('unique') verificarcheck=tabla.valor[i].atributos.get('check') condicion1:Expresion condicion2:Expresion if verificarunique!=None: columnaunique.append(columna.nombre) if(verificarcheck!=None): check=ent.buscarSimbolo(verificarcheck) #print("Condicion:",check.valor.exp1.getval(ent).valor,check.valor.simbolo,check.valor.exp2.getval(ent).valor) if isinstance(check.valor.exp1,Identificador): condicion1=check.valor.exp1.getval(ent) if condicion1==None: condicion1=Terminal(columna.tipo, check.valor.exp1.nombre) else: condicion1 = Terminal(columna.tipo, check.valor.exp1.getval(ent).valor) if isinstance(check.valor.exp2, Identificador): condicion2 = check.valor.exp2.getval(ent) if condicion2 == None: condicion2 = Terminal(columna.tipo, check.valor.exp2.nombre) else: condicion2 = Terminal(columna.tipo, check.valor.exp2.getval(ent).valor) operador=check.valor.simbolo l=0 for columna in columnas: #tipo=columna.tipo if(check.valor.exp1.getval(ent)==columna.nombre): k=0 for actual in self.namecolums: if(check.valor.exp1.getval(ent)==actual.getval(ent).valor): condicion1=Terminal(columna.tipo,self.valores[k].getval(ent).valor) k=k+1 l=l+1 n=0 for columna in columnas: if(check.valor.exp2.getval(ent)==columna.nombre): k=0 for actual in self.namecolums: if(check.valor.exp2.getval(ent)==actual.getval(ent).valor): condicion2=Terminal(columna.tipo,self.valores[k].getval(ent).valor) k=k+1 n=n+1 correcto=False if operador in ('>','<','>=','<=','='): #print(condicion1.getval(ent).valor,operador,condicion2.getval(ent).valor) nuevaop = Relacional(condicion1,condicion2,operador); if nuevaop.getval(ent): correcto=True else: variables.consola.insert(INSERT,'Error Registro no cumple con condicion check\n') reporteerrores.append(Lerrores("Error Semantico", 'Registro no cumple con condicion check','','')) return elif operador in ('or','and','not'): nuevaop = Logica(condicion1,condicion2,operador); if nuevaop.getval(ent): correcto=True else: variables.consola.insert(INSERT,'Error Registro no cumple con condicion check\n') reporteerrores.append(Lerrores("Error Semantico", 'Registro no cumple con condicion check','','')) return if(verificarnull !=None or verificarprimary!=None or verificarunique!=None): contador=contador+1 i=i+1 #print("contador",contador) if( (len(self.valores) >= contador) and (len(self.valores) == len(self.namecolums)) and (len(self.namecolums)<=len(columnas))): j=0 t=0 correcto=True terminales = [] for columna in columnas: if j < len(self.namecolums): nombre=columna.nombre tipo=columna.tipo util=Tipo(None,None,-1,-1) if isinstance(self.namecolums[j],Identificador): v=self.namecolums[j].getval(ent) if v==None: self.namecolums[j] = Terminal(self.namecolums[j].tipo, self.namecolums[j].nombre) else: self.namecolums[j]=v if(nombre==self.namecolums[j].valor): #print("iguales",nombre,":",self.namecolums[j].getval(ent).valor,"J",j,"t",t) for colunique in columnaunique: if nombre==colunique: #print("UNIQUE",colunique,"colactual",nombre,"valor",self.valores[j].getval(ent).valor,"---") v=self.validarunique(ent,tabla,colunique,self.valores[j].getval(ent).valor) #print("-----",v) if v: variables.consola.insert(INSERT,'Error Violacion de Constraint Unique en columna:'+colunique +' : '+str(self.valores[j].getval(ent).valor)+'\n') reporteerrores.append(Lerrores("Error Semantico", 'Error Violacion de Constraint Unique en columna:'+colunique +' : '+str(self.valores[j].getval(ent).valor),'','')) return buscado=str('ENUM_'+ent.getDataBase()+'_'+tipo.tipo) types:Simbolo= ent.buscarSimbolo(buscado) tipocorrecto = False if types!=None: tiposenum=types.valor print("Comparando Enum") for valenum in tiposenum: if str(valenum.getval(ent).valor).lower() == str(self.valores[j].getval(ent).valor).lower(): tipocorrecto=True if not tipocorrecto: variables.consola.insert(INSERT,str('Error Tipo enum no correcto en valor: '+self.valores[j].getval(ent).valor)+'\n') reporteerrores.append(Lerrores("Error Semantico",str('Tipo enum no correcto en valor: '+self.valores[j].getval(ent).valor),'','')) return if not tipocorrecto: if util.comparetipo(tipo,self.valores[j].getval(ent).tipo): 'todo correcto' else: correcto=False variables.consola.insert(INSERT,'Error los tipos no coinciden con la definicion de la tabla\n') reporteerrores.append(Lerrores("Error Semantico",'Tipo de datos en columanas no son iguales','','')) return terminales.append(self.valores[j].valor) j=j+1 else: #print("diferentes",nombre,":",self.namecolums[j].getval(ent).valor,"J",j,"t",t) terminales.append('') else: terminales.append('') r=DBMS.insert(ent.getDataBase(),self.nombre,terminales) if(r==4): variables.consola.insert(INSERT,'Error violacion de Constraint Primary key\n') reporteerrores.append(Lerrores("Error Semantico",'Violacion de Constraint primary Key','','')) return elif r==0: variables.consola.insert(INSERT, 'Registros Ingresados EXITOSAMENTE\n') else: variables.consola.insert(INSERT,'Error Numero Parametros en tabla '+self.nombre+' Incorrectos\n') reporteerrores.append(Lerrores('Erro semantico','Numero Parametros en tabla '+self.nombre+' Incorrectos','','')) return else: variables.consola.insert(INSERT,'Error Tabla '+self.nombre+' No Existe en la BD actual\n') reporteerrores.append(Lerrores('Error Semantico','Numero Parametros en tabla '+self.nombre+' Incorrectos','','')) return
def ejecutar(self, ent:Entorno): completo=str(self.nombre+'_'+ent.getDataBase()) tabla:Simbolo = ent.buscarSimbolo(completo) if tabla != None: columnas=tabla.valor columnaunique=[] columnacheck=[] if len(self.valores)== len(columnas): i=0 correcto=True for columna in columnas: verificarunique=tabla.valor[i].atributos.get('unique') verificarcheck=tabla.valor[i].atributos.get('check') nombre=columna.nombre tipo=columna.tipo condicion1:Expresion condicion2:Expresion if verificarunique!=None: #print("unique",verificarunique,"m--",nombre) columnaunique.append(columna.nombre) for colunique in columnaunique: if nombre==colunique: #print("UNIQUE",colunique,"colactual",nombre,"valor",self.valores[i].getval(ent).valor,"---") exp=self.valores[i].getval(ent) exp=exp.valor v=self.validarunique(ent,tabla,colunique,exp) #print("-----",v) if v: #print('Error Violacion de Constraint Unique en:',colunique,' : ',self.valores[i].getval(ent).valor) variables.consola.insert(INSERT,'Error Violacion de Constraint Unique en columna:'+colunique +' : '+str(self.valores[i].getval(ent).valor)+'\n') reporteerrores.append(Lerrores("Error Semantico", 'Error Violacion de Constraint Unique en columna:'+colunique +' : '+str(self.valores[i].getval(ent).valor),'','')) return if(verificarcheck!=None): check=ent.buscarSimbolo(verificarcheck) #print("Condicion:",check.valor.exp1.getval(ent).valor,check.valor.simbolo,check.valor.exp2.getval(ent).valor) if isinstance(check.valor.exp1, Identificador): condicion1 = check.valor.exp1.getval(ent) if condicion1 == None: condicion1 = Terminal(columna.tipo, check.valor.exp1.nombre) else: condicion1 = Terminal(columna.tipo, check.valor.exp1.getval(ent).valor) if isinstance(check.valor.exp2, Identificador): condicion2 = check.valor.exp2.getval(ent) if condicion2 == None: condicion2 = Terminal(columna.tipo, check.valor.exp2.nombre) else: condicion2 = Terminal(columna.tipo, check.valor.exp2.getval(ent).valor) operador=check.valor.simbolo l=0 for columna in columnas: #tipo=columna.tipo if isinstance(check.valor.exp1, Identificador): check.valor.exp1 = Terminal(check.valor.exp1.tipo, check.valor.exp1.nombre) if(check.valor.exp1.getval(ent).valor==columna.nombre): condicion1=Terminal(columna.tipo,self.valores[l].getval(ent).valor) l=l+1 n=0 for columna in columnas: if isinstance(check.valor.exp2, Identificador): check.valor.exp2 = Terminal(check.valor.exp2.tipo, check.valor.exp2.nombre) if(check.valor.exp2.getval(ent).valor==columna.nombre): condicion2=Terminal(columna.tipo,self.valores[n].getval(ent).valor) n=n+1 correcto=False if operador in ('>','<','>=','<=','='): #print(condicion1.getval(ent).valor,operador,condicion2.getval(ent).valor) nuevaop = Relacional(condicion1,condicion2,operador) if nuevaop.getval(ent).valor: correcto=True else: variables.consola.insert(INSERT,'Error Registro no cumple con condicion check\n') reporteerrores.append(Lerrores("Error Semantico", 'Registro no cumple con condicion check','','')) return elif operador in ('or','and','not'): nuevaop = Logica(condicion1,condicion2,operador); if nuevaop.getval(ent).valor: correcto=True else: variables.consola.insert(INSERT,'Error Registro no cumple con condicion check\n') reporteerrores.append(Lerrores("Error Semantico", 'Error Registro no cumple con condicion check','','')) return buscado=str('ENUM_'+ent.getDataBase()+'_'+tipo.tipo) types:Simbolo= ent.buscarSimbolo(buscado) tipocorrecto = False if types!=None: tiposenum=types.valor print("Comparando Enum") for valenum in tiposenum: if str(valenum.getval(ent).valor).lower() == str(self.valores[i].getval(ent).valor).lower(): tipocorrecto=True if not tipocorrecto: variables.consola.insert(INSERT,str('Error Tipo enum no correcto en valor: '+self.valores[i].getval(ent).valor)+'\n') reporteerrores.append(Lerrores("Error Semantico",str('Error Tipo enum no correcto en valor: '+self.valores[i].getval(ent).valor),'','')) return if not tipocorrecto: util=Tipo(None,None,-1,-1) #tabla:Simbolo = ent.buscarSimbolo(completo) self.valores[i]=self.valores[i].getval(ent) if util.comparetipo(tipo,self.valores[i].tipo): 'todo correcto' else: correcto=False variables.consola.insert(INSERT,'Error los tipos no coinciden con la definicion de la tabla\n') reporteerrores.append(Lerrores("Error Semantico",'Tipo de datos en columanas no son iguales','','')) return i=i+1 terminales = [] for val in self.valores: terminales.append(val.valor) r=DBMS.insert(ent.getDataBase(),self.nombre,terminales) if(r==4): variables.consola.insert(INSERT,'Error violacion de Constraint Primary key\n') reporteerrores.append(Lerrores("Error Semantico",'Violacion de Constraint primary Key','','')) return variables.consola.insert(INSERT,'Registros Ingresados EXITOSAMENTE\n') return
def ejecutar(self, ent: Entorno,imp=1): #try: tablas = [] result = [] self.encabezado = [] self.aliast=[] if self.distinct is None and self.froms is None and self.where is None and self.group is None and self.having is None and self.order is None and self.combinig is None: resultados = [] newenc=[] for i in range(0,len(self.exps)): exp=self.exps[i] if isinstance(self.exps[i], FuncionesNativas): newenc.append(self.exps[i].identificador+str(i)) elif isinstance(self.exps[i], Alias): newenc.append(self.exps[i].nombre) exp = self.exps[i].expresion elif isinstance(self.exps[i],Identificador): newenc.append(self.exps[i].nombre) else: newenc.append('Exp' + str(len(newenc))) result.append(exp.getval(ent).valor) result=[result] self.encabezado=newenc elif self.froms != None and self.exps != None: for exp in self.froms: if isinstance(exp,Identificador) or isinstance(exp,Terminal): self.aliast.append('') tipo = exp.tipo tablas=self.gettablas(tipo,exp,ent,tablas) elif isinstance(exp,Alias): self.aliast.append(exp.nombre) expre=exp.expresion tipo=expre.tipo tablas=self.gettablas(tipo,expre,ent,tablas) if len(tablas) > 1: 'Obteniendo encabezados de las tablas' for tabla in tablas: cols = tabla.valor for columna in cols: nombre = columna.nombre self.encabezado.append(nombre + "." + tabla.nombre.replace('_' + ent.getDataBase(), '')) 'producto cartesiano' real = tablas[0].nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) self.nombreres = real for i in range(0, len(tablas) - 1): real2 = tablas[i + 1].nombre.replace('_' + ent.getDataBase(), '') self.nombreres += "_" + real2 tabla2 = DBMS.extractTable(ent.getDataBase(), real2) result = self.producto(result, tabla2) else: 'llenar resultado desde backend' real = tablas[0].nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) 'encabezados 1 tabla' if (len(self.encabezado) == 0): for tabla in tablas: cols = tabla.valor for columna in cols: nombre = columna.nombre self.encabezado.append(nombre) # add columnas newenc = [] newres = [] for i in range(0, len(self.exps)): if isinstance(self.exps[i], Terminal) or isinstance(self.exps[i], Identificador): 'aqui no agrego las que ya existen' else: exp = self.exps[i] 'aqui agrego las expresiones que se agregaran para filtrar' if isinstance(self.exps[i], FuncionesNativas): newenc.append(self.exps[i].identificador) elif isinstance(self.exps[i], Alias): newenc.append(self.exps[i].nombre) exp = self.exps[i].expresion elif isinstance(self.exps[i], Identificador): newenc.append(self.exps[i].nombre) else: newenc.append('Exp' + str(len(newenc))) for fila in range(0, len(result)): res = self.resolver(exp, ent, result, tablas, fila) if fila == 0: self.tipos.append([newenc[len(newenc) - 1], res.tipo]) if len(newres) != len(result): newres.append([res.valor]) else: newres[fila].append(res.valor) for i in range(0, len(result)): if newres != []: result[i] = result[i] + newres[i] self.encabezado = (self.encabezado + newenc) # filtros if self.where != None: result = self.optwhere(ent,result,tablas) #DEVUELVO SOLO COLUMNAS PEDIDAS newenc = [] newres = [] for i in range(0, len(self.exps)): if isinstance(self.exps[i],Identificador): for j in range(0, len(self.encabezado)): nombrediv = self.encabezado[j].split('.') nombrecol = nombrediv[0] if self.exps[i].nombre == nombrecol: newenc.append(self.encabezado[j]) for x in range(0, len(result)): valcol = result[x][j] if len(newres) != len(result): newres.append([valcol]) else: newres[x].append(valcol) elif isinstance(self.exps[i], Terminal): if self.exps[i].tipo.tipo == 'acceso': expresion=self.exps[i] campos = expresion.getval(ent).valor.split('.') if campos[1] == '*': tablares=self.getasterisco(campos[0], tablas, result, ent,newres,newenc) newenc=tablares[0] newres=tablares[1] #busco el campo pedido si no es * for j in range(0, len(self.encabezado)): nombrediv = self.encabezado[j].split('.') nombrecol = nombrediv[0] nombretabla = nombrediv[1] nombrecol = nombretabla + '.' + nombrecol if expresion.getval(ent).valor == nombrecol: newenc.append(self.encabezado[j]) for x in range(0, len(result)): dato = result[x][j] if len(newres) != len(result): newres.append([dato]) else: newres[x].append(dato) for k in range(0, len(self.aliast)): nombreacc = self.aliast[k] + '.' + nombrediv[0] if expresion.getval(ent).valor == nombreacc and nombrediv[1] == tablas[k].nombre.replace('_' + ent.getDataBase(), ''): newenc.append(self.encabezado[j]) for x in range(0, len(result)): dato = result[x][j] if len(newres) != len(result): newres.append([dato]) else: newres[x].append(dato) elif len(self.exps)==1 and self.exps[0].valor=='*': newres=result[:] newenc=self.encabezado[:] break else: exp = self.exps[i] if isinstance(self.exps[i],FuncionesNativas): newenc.append(self.exps[i].identificador+str(i)) elif isinstance(self.exps[i], Alias): newenc.append(self.exps[i].nombre) exp = self.exps[i].expresion else: newenc.append('Exp'+len(newenc)) for fila in range(0,len(result)): res=self.resolver(exp,ent,result,tablas,fila) '''if isinstance(res,str): if len(newres) != len(result): newres.append(['']) else: newres[fila].append('') continue''' if len(newres) != len(result) : newres.append([res.valor]) else: newres[fila].append(res.valor) result = newres[:] self.encabezado = newenc[:] # combining(union,intersect,except) if self.combinig != None: datos2 = self.combinig.select.ejecutar(ent, 0) enc2 = datos2[0] res2 = datos2[1] result = self.m_combining(self.combinig, self.encabezado, result, enc2, res2) aber = result # limitar resultados if self.limit != None: a = self.limit result = self.m_limit(result, a.limit, a.off) #distinct if self.distinct!=None: newres=[] 'elimino duplicados' for i in range(0,len(result)): encontrado=False fila=result[i] for j in range(0,len(result)): if j!= i: if fila==result[j]: encontrado=True if encontrado==False: newres.append(fila) result=newres #imprimir resultado solo si no se llamo de un subquery,union,intersect,except if self.agregacion==1: result=[result[0]] if imp == 1: self.mostarresult(result, self.encabezado, self.nombreres) return [self.encabezado, result]
def ejecutar(self, ent: Entorno): completo = self.nombre + '_' + ent.getDataBase() tabla: Simbolo = ent.buscarSimbolo(completo) if tabla != None: columnas = tabla.valor columnaunique = [] columnacheck = [] if len(self.valores) == len(columnas): i = 0 correcto = True for columna in columnas: verificarnull = tabla.valor[i].atributos.get('not null') verificarprimary = tabla.valor[i].atributos.get('primary') verificarunique = tabla.valor[i].atributos.get('unique') verificarcheck = tabla.valor[i].atributos.get('check') nombre = columna.nombre tipo = columna.tipo condicion1: Expresion condicion2: Expresion if verificarunique != None: #print("unique",verificarunique,"m--",nombre) columnaunique.append(columna.nombre) for colunique in columnaunique: if nombre == colunique: #print("UNIQUE",colunique,"colactual",nombre,"valor",self.valores[i].getval(ent),"---") v = self.validarunique(ent, tabla, colunique, self.valores[i].getval(ent)) #print("-----",v) if v: print( 'Error Violacion de Constraint Unique en:', colunique, ' : ', self.valores[i].getval(ent)) return 'Error Violacion de Constraint Unique en columna:' + colunique + ' : ' + self.valores[ i].getval(ent) if (verificarcheck != None): check = ent.buscarSimbolo(verificarcheck) #print("Condicion:",check.valor.exp1.getval(ent),check.valor.simbolo,check.valor.exp2.getval(ent)) condicion1 = Terminal(columna.tipo, check.valor.exp1.getval(ent)) condicion2 = Terminal(columna.tipo, check.valor.exp2.getval(ent)) operador = check.valor.simbolo l = 0 for columna in columnas: tipo = columna.tipo if (check.valor.exp1.getval(ent) == columna.nombre ): condicion1 = Terminal( tipo, self.valores[l].getval(ent)) l = l + 1 n = 0 for columna in columnas: if (check.valor.exp2.getval(ent) == columna.nombre ): condicion2 = Terminal( columna.tipo, self.valores[n].getval(ent)) n = n + 1 correcto = False if operador in ('>', '<', '>=', '<=', '='): #print(condicion1.getval(ent),operador,condicion2.getval(ent)) nuevaop = Relacional(condicion1, condicion2, operador) if nuevaop.getval(ent): correcto = True else: return ( 'Registro no cumple con condicion check') elif operador in ('or', 'and', 'not'): nuevaop = Logica(condicion1, condicion2, operador) if nuevaop.getval(ent): correcto = True else: return ( 'Registro no cumple con condicion Check') util = Tipo(None, None, -1, -1) if isinstance(self.valores[i], FuncionesNativas): self.valores[i] = self.valores[i].getval(ent) if util.comparetipo(tipo, self.valores[i].tipo): 'todo correcto' else: correcto = False return 'Error los tipos de los valores no coinciden con la definicion de la tabla' i = i + 1 terminales = [] for val in self.valores: terminales.append(val.getval(ent)) r = DBMS.insert(ent.getDataBase(), self.nombre, terminales) if (r == 4): return 'Error al Insertar Registro Violacion de Constraint Primary Key' return 'Registros insertados con exito'
def ejecutar(self, ent: Entorno): completo = self.nombre + '_' + ent.getDataBase() tabla: Simbolo = ent.buscarSimbolo(completo) if tabla != None: columnas = tabla.valor i = 0 contador = 0 for columna in columnas: verificarnull = tabla.valor[i].atributos.get('not null') verificarprimary = tabla.valor[i].atributos.get('primary') verificarunique = tabla.valor[i].atributos.get('unique') verificarcheck = tabla.valor[i].atributos.get('check') condicion1: Expresion condicion2: Expresion if (verificarcheck != None): check = ent.buscarSimbolo(verificarcheck) print("Condicion:", check.valor.exp1.getval(ent), check.valor.simbolo, check.valor.exp2.getval(ent)) condicion1 = Terminal(columna.tipo, check.valor.exp1.getval(ent)) condicion2 = Terminal(columna.tipo, check.valor.exp2.getval(ent)) operador = check.valor.simbolo l = 0 for columna in columnas: tipo = columna.tipo if (check.valor.exp1.getval(ent) == columna.nombre): k = 0 for actual in self.namecolums: if (check.valor.exp1.getval(ent) == actual.getval(ent)): condicion1 = Terminal( tipo, self.valores[k].getval(ent)) k = k + 1 l = l + 1 n = 0 for columna in columnas: if (check.valor.exp2.getval(ent) == columna.nombre): k = 0 for actual in self.namecolums: if (check.valor.exp2.getval(ent) == actual.getval(ent)): condicion2 = Terminal( columna.tipo, self.valores[k].getval(ent)) k = k + 1 n = n + 1 correcto = False if operador in ('>', '<', '>=', '<=', '='): print(condicion1.getval(ent), operador, condicion2.getval(ent)) nuevaop = Relacional(condicion1, condicion2, operador) if nuevaop.getval(ent): correcto = True else: return ('Registro no cumple con condicion check') elif operador in ('or', 'and', 'not'): nuevaop = Logica(condicion1, condicion2, operador) if nuevaop.getval(ent): correcto = True else: return ('Registro no cumple con condicion Check') if (verificarnull != None or verificarprimary != None or verificarunique != None): contador = contador + 1 i = i + 1 #print("contador",contador) if ((len(self.valores) >= contador) and (len(self.valores) == len(self.namecolums)) and (len(self.namecolums) <= len(columnas))): j = 0 t = 0 correcto = True terminales = [] for columna in columnas: nombre = columna.nombre tipo = columna.tipo util = Tipo(None, None, -1, -1) if (nombre == self.namecolums[j].getval(ent)): #print("iguales",nombre,":",self.namecolums[j].getval(ent),"J",j,"t",t) if util.comparetipo(tipo, self.valores[j].tipo): 'todo correcto' else: correcto = False return 'Error los tipos de los valores no coinciden con la definicion de la tabla' terminales.append(self.valores[j].getval(ent)) j = j + 1 else: #print("diferentes",nombre,":",self.namecolums[j].getval(ent),"J",j,"t",t) terminales.append('') r = DBMS.insert(ent.getDataBase(), self.nombre, terminales) if (r == 4): return 'Error al Insertar Registro Violacion de Constraint Primary Key' print("Insert: ", terminales) return 'Registro insertado exitosamente' #print("insertando",r) else: return str('Error Numero Parametros en tabla ' + self.nombre + ' Incorrectos') else: return str('Error Tabla ' + self.nombre + ' No Existe en la BD actual')
def ejecutar(self, ent: Entorno): dbActual = ent.getDataBase() if dbActual != None: tam = len(self.listaDef) nuevaTabla = Simbolo(TipoSimbolo.TABLA, (self.id + "_" + dbActual)) listaColumnas = [] listaAtrCol = [] hayPrimaria = False hayForanea = False primariaAdd: Primaria = None foraneaAdd: Foranea = None inicioHerencia = 0 if self.herencia != None: r: Simbolo = ent.buscarSimbolo(self.herencia + "_" + dbActual) if r != None: for colPadre in r.valor: listaColumnas.append(colPadre) if colPadre.atributos.get('primary') != None: coPrimary: Simbolo = ent.buscarSimbolo( colPadre.atributos.get('primary')) if coPrimary != None: self.listPK = coPrimary.valor inicioHerencia = len(r.valor) else: variables.consola.insert( INSERT, "La tabla padre '" + self.herencia + "' no existe") reporteerrores.append( Lerrores( "Error Semántico", "La tabla padre '" + self.herencia + "' no existe", "", "")) for x in range(0, tam, 1): tt = self.listaDef[x] if tt.tipo == AtributosColumna.COLUMNA_SIMPLE: nuevaColumna = Simbolo(tt.tipoDato, tt.identificador) if tt.lista != None: #aca se mete si viene por ejemplo: columna1 integer references tabla2 tamano = len(tt.lista) for y in range(tamano): hayAtr = False nuevoSym = Simbolo("tipo", "nombre") nuevoSym.baseDatos = dbActual nuevoSym.tabla = self.id atrColumna: Atributo = tt.lista[y] if atrColumna.tipo == AtributosColumna.UNICO: hayAtr = True nuevoSym.tipo = TipoSimbolo.CONSTRAINT_UNIQUE if atrColumna.valor != None: #forma de: constraint id UNIQUE #formato de nombre: U_database_tabla_nombreColumna_idConstraint nuevoSym.nombre = str("U_" + dbActual + "_" + self.id + "_" + tt.identificador + "_" + atrColumna.valor) nuevaColumna.atributos.update({ 'unique': str("U_" + dbActual + "_" + self.id + "_" + tt.identificador + "_" + atrColumna.valor) }) else: #forma de: nombreColumna tipo UNIQUE #formato: U_database_tabla_nombreColumna nuevoSym.nombre = str("U_" + dbActual + "_" + self.id + "_" + tt.identificador) nuevaColumna.atributos.update({ 'unique': str("U_" + dbActual + "_" + self.id + "_" + tt.identificador) }) nuevoSym.valor = tt.identificador elif atrColumna.tipo == AtributosColumna.CHECK: hayAtr = True nuevoSym.tipo = TipoSimbolo.CONSTRAINT_CHECK nuevoSym.valor = atrColumna.exp if atrColumna.valor != None: #forma de: constraint id check cond < cond #formato: C_database_tabla_nombreColumna_idConstraint nuevoSym.nombre = str("C_" + dbActual + "_" + self.id + "_" + tt.identificador + "_" + atrColumna.valor) nuevaColumna.atributos.update({ 'check': str("C_" + dbActual + "_" + self.id + "_" + tt.identificador + "_" + atrColumna.valor) }) else: #cuando viene: nombreColumna tipo CHECK cond < cond #formato: C_database_tabla_nombreColumna nuevoSym.nombre = str("C_" + dbActual + "_" + self.id + "_" + tt.identificador) nuevaColumna.atributos.update({ 'check': str("C_" + dbActual + "_" + self.id + "_" + tt.identificador) }) elif atrColumna.tipo == AtributosColumna.DEFAULT: nuevaColumna.atributos.update( {'default': atrColumna.valor}) elif atrColumna.tipo == AtributosColumna.NO_NULO: nuevaColumna.atributos.update( {'not null': True}) elif atrColumna.tipo == AtributosColumna.NULO: nuevaColumna.atributos.update({'null': True}) elif atrColumna.tipo == AtributosColumna.PRIMARY: hayPrimaria = True nuevaColumna.atributos.update({ 'primary': str("PK_" + dbActual + "_" + self.id) }) # PK_database_tabla elif atrColumna.tipo == AtributosColumna.REFERENCES: rr = DBMS.extractTable(dbActual, atrColumna.valor) if rr == None: return str( "La tabla \'" + atrColumna.valor + "\' a la que está referenciando, no existe" ) else: tablaReferencia: Simbolo = ent.buscarSimbolo( atrColumna.valor + "_" + dbActual) colRef = tablaReferencia.valor for col in colRef: nomConstraintPK = col.atributos.get( 'primary') if nomConstraintPK != None: consPK: Simbolo = ent.buscarSimbolo( nomConstraintPK) arrPk = consPK.valor if len(arrPk) == 1: if tablaReferencia.valor[arrPk[ 0]].tipo.tipo == nuevaColumna.tipo.tipo: hayForanea = True hayAtr = True nuevoSym.tipo = TipoSimbolo.CONSTRAINT_FOREIGN # FK_database_tabla_tablaReferencia nuevoSym.nombre = str( "FK_" + dbActual + "_" + self.id + "_" + atrColumna.valor) nuevaColumna.atributos.update( { 'foreign': str("FK_" + dbActual + "_" + self.id + "_" + atrColumna. valor) }) break if not hayForanea: variables.consola.insert( INSERT, "No se puede establecer llave foranea entre tabla '" + self.id + "' y '" + atrColumna.valor + "'\n") reporteerrores.append( Lerrores( "Error Semántico", "No se puede establecer llave foranea entre tabla '" + self.id + "' y '" + atrColumna.valor + "'", "", "")) if hayAtr: listaAtrCol.append(nuevoSym) listaColumnas.append(nuevaColumna) if tt.tipo == AtributosColumna.PRIMARY: if hayPrimaria: variables.consola.insert( INSERT, str("La tabla \'" + self.id + "\' ya contiene llave primaria declarada\n")) reporteerrores.append( Lerrores( "Error Semántico", "La tabla \'" + self.id + "\' ya contiene llave primaria declarada", "", "")) else: primariaAdd: Primaria = tt if tt.tipo == AtributosColumna.REFERENCES: if hayForanea: variables.consola.insert( INSERT, str("La tabla \'" + self.id + "\' ya contiene llave foranea declarada\n")) reporteerrores.append( Lerrores( "Error Semántico", "La tabla \'" + self.id + "\' ya contiene llave foranea declarada", "", "")) else: foraneaAdd: Foranea == tt rr = DBMS.extractTable(dbActual, foraneaAdd.tabla) if tt.tipo == AtributosColumna.CONSTRAINT: if tt.contenido.tipo == AtributosColumna.PRIMARY: if hayPrimaria: variables.consola.insert( INSERT, str("La tabla \'" + self.id + "\' ya contiene llave primaria declarada\n" )) reporteerrores.append( Lerrores( "Error Semántico", "La tabla \'" + self.id + "\' ya contiene llave primaria declarada", "", "")) else: primariaAdd: Primaria = tt.contenido primariaAdd.idConstraint = tt.id elif tt.contenido.tipo == AtributosColumna.REFERENCES: if hayForanea: variables.consola.insert( INSERT, str("La tabla \'" + self.id + "\' ya contiene llave foranea declarada\n") ) reporteerrores.append( Lerrores( "Error Semántico", "La tabla \'" + self.id + "\' ya contiene llave foranea declarada", "", "")) else: foraneaAdd: Foranea == tt rr = DBMS.extractTable(dbActual, foraneaAdd.tabla) elif tt.contenido.tipo == AtributosColumna.UNICO: listUnicas = tt.contenido.unicos for x in listUnicas: for col in listaColumnas: if col.nombre == x.valor: #formato: U_database_tabla_nombreColumna_idConstraint col.atributos.update({ 'unique': str("U_" + dbActual + "_" + self.id + "_" + col.nombre + "_" + tt.id) }) sym = Simbolo( TipoSimbolo.CONSTRAINT_UNIQUE, str("U_" + dbActual + "_" + self.id + "_" + col.nombre + "_" + tt.id)) ent.nuevoSimbolo(sym) elif tt.contenido.tipo == AtributosColumna.CHECK: #formato: C_database_tabla_nombreColumna_idConstraint nombreColCheck = str( tt.contenido.condiciones.exp1.valor) for x in listaColumnas: if x.nombre == nombreColCheck: x.atributos.update({ 'check': str("C_" + dbActual + "_" + self.id + "_" + x.nombre + "_" + tt.id) }) sym = Simbolo( TipoSimbolo.CONSTRAINT_CHECK, str("C_" + dbActual + "_" + self.id + "_" + x.nombre + "_" + tt.id)) sym.tabla = self.id sym.baseDatos = dbActual sym.valor = tt.contenido.condiciones listaAtrCol.append(sym) break nuevaTabla.valor = listaColumnas estado = DBMS.createTable(dbActual, self.id, len(listaColumnas)) if estado == 0: nuevaTabla.baseDatos = dbActual r = ent.nuevoSimbolo(nuevaTabla) if r == "ok": for x in listaAtrCol: ent.nuevoSimbolo(x) alreadyPrimary = False for x in range(inicioHerencia, len(listaColumnas), 1): if not alreadyPrimary: pk = listaColumnas[x].atributos.get('primary') if pk != None: self.listPK.append(x) rrr = DBMS.alterAddPK(dbActual, self.id, self.listPK) if rrr != 0: variables.consola.insert( INSERT, "No se ha podido agregar PK en tabla \'" + self.id + "\'\n") reporteerrores.append( Lerrores( "Error Semántico", "No se ha podido agregar PK en tabla \'" + self.id + "'", "", "")) else: alreadyPrimary = True sym1 = Simbolo( TipoSimbolo.CONSTRAINT_PRIMARY, str("PK_" + dbActual + "_" + self.id)) sym1.valor = self.listPK sym1.tabla = self.id sym1.baseDatos = dbActual ent.nuevoSimbolo(sym1) if not alreadyPrimary: tablaB: Simbolo = ent.buscarSimbolo(nuevaTabla.nombre) if tablaB != None: if primariaAdd != None: listaPrim = primariaAdd.primarias for p in listaPrim: for col in range(len(tablaB.valor)): if p.valor == tablaB.valor[col].nombre: self.listPK.append(col) #print(p.valor) #print(col.nombre) if len(self.listPK) > 0: n = DBMS.alterAddPK( dbActual, self.id, self.listPK) if n != 0: variables.consola.insert( INSERT, "No se ha podido agregar PK en tabla \'" + self.id + "\'\n") reporteerrores.append( Lerrores( "Error Semántico", "No se ha podido agregar PK en tabla \'" + self.id + "'", "", "")) else: idPk = "" alreadyPrimary = True sym: Simbolo = None if primariaAdd.idConstraint != "": idPk = str( "PK_" + dbActual + "_" + self.id + "_" + primariaAdd.idConstraint) sym = Simbolo( TipoSimbolo.CONSTRAINT_PRIMARY, idPk) else: idPk = str("PK_" + dbActual + "_" + self.id) sym = Simbolo( TipoSimbolo.CONSTRAINT_PRIMARY, idPk) for y in self.listPK: tablaB.valor[y].atributos.update( {'primary': idPk}) sym.valor = self.listPK sym.tabla = self.id sym.baseDatos = dbActual ent.nuevoSimbolo(sym) DBMS.showCollection() variables.consola.insert( INSERT, str("Tabla " + self.id + " creada exitosamente\n")) return return r
def ejecutar(self, ent: Entorno): dbActual = ent.getDataBase() if dbActual != None: tablaAlterada: Simbolo = ent.buscarSimbolo(self.tabla + "_" + dbActual) if tablaAlterada != None: for opcionX in self.opciones: if opcionX.tipoAlter == TipoAlter.ADDCOLUMNA: addColumna: AddColumn = opcionX res = DBMS.alterAddColumn(dbActual, self.tabla, None) if res == 0: nuevaCol: Simbolo = Simbolo( addColumna.tipo, addColumna.id) nuevaCol.tabla = self.tabla nuevaCol.baseDatos = dbActual tablaAlterada.valor.append(nuevaCol) e = ent.editarSimbolo(self.tabla + "_" + dbActual, tablaAlterada) if e == "ok": variables.consola.insert( INSERT, "Se agregó nueva columna '" + str(addColumna.id) + "' a la tabla '" + str(self.tabla) + "'\n") else: reporteerrores.append( Lerrores( "Error Semantico", "No se ha podido agregar la columna '" + addColumna.id + "' a la tabla " + self.tabla, 0, 0)) variables.consola.insert( INSERT, "No se ha podido agregar la columna '" + addColumna.id + "' a la tabla ") elif opcionX.tipoAlter == TipoAlter.ADDCHECK: #formato: C_database_tabla_nombreColumna addCheck: AddCheck = opcionX nombreColCheck: str = str( addCheck.condicion.exp1.valor) for col in tablaAlterada.valor: if col.nombre == nombreColCheck: idCheck: str = str("C_" + dbActual + "_" + self.tabla + "_" + col.nombre) if addCheck.constraint != None: idCheck += "_" + str(addCheck.constraint) col.atributos.update({'check': idCheck}) nuevoSym: Simbolo = Simbolo( TipoSimbolo.CONSTRAINT_CHECK, idCheck, addCheck.condicion) nuevoSym.baseDatos = dbActual nuevoSym.tabla = self.tabla ent.nuevoSimbolo(nuevoSym) variables.consola.insert( INSERT, "Condición check agegada en columna '" + str(col.nombre) + "' en la tabla '" + str(self.tabla) + "'\n") break elif opcionX.tipoAlter == TipoAlter.ADDUNIQUE: addUnique: AddUnique = opcionX for add in addUnique.columnas: for col in tablaAlterada.valor: if col.nombre == add.valor: idUnique: str = str("U_" + dbActual + "_" + self.tabla + "_" + col.nombre) if addUnique.constraint != None: idUnique += "_" + str( addUnique.constraint) col.atributos.update({'unique': idUnique}) nuevoSym: Simbolo = Simbolo( TipoSimbolo.CONSTRAINT_UNIQUE, idUnique, col.nombre) nuevoSym.baseDatos = dbActual nuevoSym.tabla = self.tabla ent.nuevoSimbolo(nuevoSym) variables.consola.insert( INSERT, "Condición Unique agregada en columna '" + str(col.nombre) + "' en la tabla '" + str(self.tabla) + "'\n") elif opcionX.tipoAlter == TipoAlter.ADDFOREIGN: addForeign: AddForeign = opcionX tablaReferenciada: Simbolo = ent.buscarSimbolo( addForeign.referenceTable + "_" + dbActual) if tablaReferenciada != None: if len(addForeign.colAddForeign) == len( addForeign.colReferences): idFk: str = str("FK_" + dbActual + "_" + self.tabla + "_" + addForeign.referenceTable) if addForeign.constraint != None: idFk += "_" + addForeign.constraint n: Simbolo = Simbolo( TipoSimbolo.CONSTRAINT_FOREIGN, idFk) n.baseDatos = dbActual n.tabla = self.tabla ent.nuevoSimbolo(n) variables.consola.insert( INSERT, "Llave Foránea referenciando a tabla '" + str(addForeign.referenceTable) + "' en la tabla '" + str(self.tabla) + "'\n") else: variables.consola.insert( INSERT, "La cantidad de columnas no coinciden en llave foránea de la tabla '" + str(self.tabla) + "'\n") reporteerrores.append( Lerrores( "Error Semántico", "La cantidad de columnas no coinciden en llave foránea de tabla '" + self.tabla + "'", "", "")) elif opcionX.tipoAlter == TipoAlter.ADDNULL: addNulo: AddNull = opcionX for col in tablaAlterada.valor: if col.nombre == addNulo.columna: if addNulo.nulo: #setea a nulos col.atributos.update({'null': True}) else: col.atributos.update({'not null': True}) break elif opcionX.tipoAlter == TipoAlter.DROPCONSTRAINT: #formato : CONSTRAINT_database_tabla_nombreCol_idConstraint dropConstr: DropConstraint = opcionX opcConstraint = ["C", "U", "F", "P"] constr = ['check', 'unique', 'foreign', 'primary'] encontrado = False concat: str = "_" + dbActual + "_" + self.tabla + "_" for col in tablaAlterada.valor: for x in range(len(opcConstraint)): idCo: str = opcConstraint[ x] + concat + col.nombre + "_" + dropConstr.constraint r: Simbolo = ent.buscarSimbolo(idCo) if r != None: encontrado = True ent.eliminarSimbolo(idCo) del col.atributos[constr[x]] variables.consola.insert( INSERT, "El constraint '" + str(dropConstr.constraint) + "' ha sido eliminado\n") break if not encontrado: variables.consola.insert( INSERT, "El constraint '" + str(dropConstr.constraint) + "' no existe'\n") reporteerrores.append( Lerrores( "Error Semántico", "El constraint '" + str(dropConstr.constraint) + "' no existe", "", "")) elif opcionX.tipoAlter == TipoAlter.ALTERTYPE: alterTipo: AlterType = opcionX for col in tablaAlterada.valor: if col.nombre == alterTipo.columna: col.tipo = alterTipo.nuevoTipo variables.consola.insert( INSERT, "El tipo de la columna '" + str(col.nombre) + "' de la tabla '" + self.tabla + "' cambió a '" + col.tipo.tipo + "'\n") return elif opcionX.tipoAlter == TipoAlter.RENAMECOLUMN: rCol: RenameColumn = opcionX for col in tablaAlterada.valor: if col.nombre == rCol.oldColumn: col.nombre = rCol.newColumn variables.consola.insert( INSERT, "El nombre de la columna '" + str(rCol.oldColumn) + "' de la tabla '" + self.tabla + "' cambió a '" + str(rCol.newColumn) + "'\n") return elif opcionX.tipoAlter == TipoAlter.DROPCHECK: dChe: DropCheck = opcionX for col in tablaAlterada.valor: idd = "C_" + dbActual + "_" + self.tabla + "_" + str( col.nombre) + "_" + dChe.iden r: Simbolo = ent.buscarSimbolo(idd) if r != None: ent.eliminarSimbolo(idd) variables.consola.insert( INSERT, "Se ha eliminado la condición check '" + str(dChe.iden) + "'\n") break elif opcionX.tipoAlter == TipoAlter.DROPCOLUMN: index = [] dropC: DropColumns = opcionX for drop in dropC.columnas: for x in range(len(tablaAlterada.valor)): if tablaAlterada.valor[x].nombre == drop.valor: r = DBMS.alterDropColumn( dbActual, self.tabla, x) if r == 0: for z in tablaAlterada.valor[ x].atributos.values(): ent.eliminarSimbolo(z) variables.consola.insert( INSERT, "Se ha eliminado la columna '" + str(drop.valor) + "' de la tabla '" + str(self.tabla) + "'\n") index.append(x) for g in index: tablaAlterada.valor.pop(g) ent.editarSimbolo(self.tabla + "_" + dbActual, tablaAlterada)
def ejecutar(self, ent:Entorno): dbActual = ent.getDataBase() tam = len(self.listaDef) print (tam) nuevaTabla = Simbolo(TipoSimbolo.TABLA,self.id) listaColumnas = [] for x in range(0,tam,1): tt = self.listaDef[x] if tt.tipo == AtributosColumna.COLUMNA_SIMPLE: self.numColumnas += 1 nuevaColumna = Simbolo(tt.tipoDato,tt.identificador) if tt.lista != None: #aca se mete si viene por ejemplo: columna1 integer references tabla2 tamano = len(tt.lista) for y in range(tamano): atrColumna = tt.lista[y] if atrColumna.tipo == AtributosColumna.UNICO: nuevoUnico = Simbolo(TipoSimbolo.CONSTRAINT_UNIQUE,atrColumna.valor) nuevoUnico.baseDatos = dbActual nuevoUnico.tabla = self.id ent.nuevoSimbolo(nuevoUnico) nuevaColumna.atributos.update({'unique':atrColumna.valor}) elif atrColumna.tipo == AtributosColumna.CHECK: nuevoCheck = Simbolo(TipoSimbolo.CONSTRAINT_CHECK,atrColumna.valor) nuevoCheck.baseDatos = dbActual nuevoCheck.tabla = self.id ent.nuevoSimbolo(nuevoCheck) nuevaColumna.atributos.update({'check':atrColumna.valor}) elif atrColumna.tipo == AtributosColumna.DEFAULT: nuevaColumna.atributos.update({'default':atrColumna.valor}) elif atrColumna.tipo == AtributosColumna.NO_NULO: nuevaColumna.atributos.update({'not null':True}) elif atrColumna.tipo == AtributosColumna.NULO: nuevaColumna.atributos.update({'null':True}) elif atrColumna.tipo == AtributosColumna.PRIMARY: nuevaPrimaria = Simbolo(TipoSimbolo.CONSTRAINT_PRIMARY,str("PK_" + self.id)) nuevaPrimaria.baseDatos = dbActual nuevaPrimaria.tabla = self.id ent.nuevoSimbolo(nuevaPrimaria) nuevaColumna.atributos.update({'primary':str("PK_" + self.id)}) elif atrColumna.tipo == AtributosColumna.REFERENCES: rr = DBMS.extractTable(dbActual,atrColumna.valor) if rr == []: return str("La tabla \'" + atrColumna.valor + "\' a la que está referenciando, no existe") else: nuevaForanea = Simbolo(TipoSimbolo.CONSTRAINT_FOREIGN,str("FK_" + self.id)) nuevaForanea.baseDatos = dbActual nuevaForanea.tabla = self.id ent.nuevoSimbolo(nuevaForanea) nuevaColumna.atributos.update({'foreign':str("FK_" + self.id)}) listaColumnas.append(nuevaColumna) #considerar la situacion de cuando no se haya creado la tabla pero ya se hayan #agregado los constraint a la tabla de simbolos nuevaTabla.valor = listaColumnas if dbActual != None: estado = DBMS.createTable(dbActual,self.id, self.numColumnas) if estado == 0: nuevaTabla.baseDatos = dbActual ent.nuevoSimbolo(nuevaTabla) DBMS.showCollection() return str("Tabla " + nuevaTabla.nombre + " creada exitosamente")
def ejecutar(self, ent: Entorno): self.encabezado.clear() dbActual = ent.getDataBase() result = [] result.clear() llavesprim = [] llavesprim.clear() if dbActual != None: tabla: Simbolo = ent.buscarSimbolo(self.tabla + "_" + dbActual) if tabla != None: 'obtengo tabla' real = tabla.nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) columnas = tabla.valor 'lleno encabezado' for col in columnas: self.encabezado.append(col.nombre) colsupdate = [] poscolsupdate = [] newvals = [] colsupdate.clear() poscolsupdate.clear() newvals.clear() for i in range(0, len(self.listaCampos)): nombrecol = self.listaCampos[i].columna expresion = self.listaCampos[i].exp contenido = expresion.getval(ent).valor colsupdate.append(nombrecol) newvals.append(contenido) for x in range(0, len(colsupdate)): for y in range(0, len(self.encabezado)): print("comparando" + colsupdate[x]) print("con+" + self.encabezado[y]) if (colsupdate[x] == self.encabezado[y]): poscolsupdate.append(y) print(poscolsupdate) for i in range(0, len(result)): resexp = self.resolver(self.where, ent, result, tabla, i) try: if resexp.valor: cont = 0 for a in poscolsupdate: result[i][a] = newvals[cont] cont += 1 llavePrim = [] for column in tabla.valor: prim: Simbolo = ent.buscarSimbolo( column.atributos.get('primary')) llavePrim = prim.valor break except: reporteerrores.append( Lerrores( "Error Semantico", 'Error el resultado del where no es booleano', 0, 0)) variables.consola.insert( INSERT, 'Error el resultado del where no es booleano \n') llavesprim = llavePrim self.resultupdate(result, self.tabla, ent.getDataBase(), llavesprim) else: variables.consola.insert( INSERT, "La tabla '" + self.tabla + "' que desea actualizar no existe\n") reporteerrores.append( Lerrores( "Error Semántico", "La tabla '" + self.tabla + "' que desea actualizar no existe", "", ""))
def ejecutar(self,ent:Entorno): tablas = [] result = [] self.encabezado = [] 'Metodo Abstracto para ejecutar la instruccion' if self.distinct is None and self.froms is None and self.where is None and self.group is None and self.having is None and self.order is None and self.combinig is None: resultados = []; for exp in self.exps: if exp != None: resultados.append(exp.getval(ent)) return resultados elif self.froms != None and self.exps!= None: for exp in self.froms: if exp != None: tipo =exp.tipo; if tipo.tipo=='identificador': nombre=exp.getval(ent) self.nombreres = nombre tabla=ent.buscarSimbolo(nombre+"_"+ent.getDataBase()) if tabla!=None: tablas.append(tabla) else: return ("ERROR >> En la instrucción Select, la tabla: "+nombre+" NO EXISTE") else: return ("ERROR >> En la instrucción Select, ingreso un nombre de tabla incorrecto") else: return ("Algo paso") if len(tablas)>1: 'producto cartesiano' 'Obteniendo encabezados de las tablas' postab = 1 for tabla in tablas: cols = tabla.valor for columna in cols: nombre = columna.nombre self.encabezados.append(nombre+"_T"+str(postab)) postab = postab +1 'producto cartesiano' real = tablas[0].nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) self.nombreres = real+"(T1)" for i in range(0, len(tablas)-1): real2 = tablas[i+1].nombre.replace('_' + ent.getDataBase(), '') self.nombreres += '_' + real2 + "(T"+str(i+2)+")" tabla2 = DBMS.extractTable(ent.getDataBase(), real2) result = self.producto(result, tabla2) else: 'llenar resultado desde backend' real=tablas[0].nombre.replace('_'+ent.getDataBase(),'') result=DBMS.extractTable(ent.getDataBase(),real) #filtros if self.where != None: result=self.execwhere(ent,tablas) else: if (len(self.encabezados)==0): for tabla in tablas: cols = tabla.valor for columna in cols: nombre = columna.nombre self.encabezados.append(nombre) #acceder a columnas if len(self.exps) == 1: if self.exps[0].getval(ent) == '*': self.mostarresult(result, self.nombreres) elif self.exps[0].tipo.tipo=='identificador': 'obtengo solo columnas pedidas' else: 'pendientes subconsultas y funciones'
def ejecutar(self, ent: Entorno, imp=1): try: tablas = [] result = [] self.encabezado = [] aliast = [] 'Metodo Abstracto para ejecutar la instruccion' if self.distinct is None and self.froms is None and self.where is None and self.group is None and self.having is None and self.order is None and self.combinig is None: resultados = [] for exp in self.exps: if exp != None: res = exp.getval(ent) resultados.append(res.valor) variables.consola.insert(INSERT, str(res.valor)) variables.consola.insert(INSERT, '\n') return resultados elif self.froms != None and self.exps != None: for exp in self.froms: if isinstance(exp, Terminal): aliast.append('') tipo = exp.tipo tablas = self.gettablas(tipo, exp, ent, tablas) elif isinstance(exp, Alias): aliast.append(exp.nombre) expre = exp.expresion tipo = exp.tipo tablas = self.gettablas(tipo, expre, ent, tablas) if len(tablas) > 1: 'Obteniendo encabezados de las tablas' for tabla in tablas: cols = tabla.valor for columna in cols: nombre = columna.nombre self.encabezado.append( nombre + "." + tabla.nombre.replace('_' + ent.getDataBase(), '')) 'producto cartesiano' real = tablas[0].nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) self.nombreres = real for i in range(0, len(tablas) - 1): real2 = tablas[i + 1].nombre.replace( '_' + ent.getDataBase(), '') self.nombreres += "_" + tabla.nombre.replace( '_' + ent.getDataBase(), '') tabla2 = DBMS.extractTable(ent.getDataBase(), real2) result = self.producto(result, tabla2) else: 'llenar resultado desde backend' real = tablas[0].nombre.replace('_' + ent.getDataBase(), '') result = DBMS.extractTable(ent.getDataBase(), real) 'encabezados 1 tabla' if (len(self.encabezado) == 0): for tabla in tablas: cols = tabla.valor for columna in cols: nombre = columna.nombre self.encabezado.append(nombre) #lleno arreglo de alias for exp in self.exps: self.aliast.append('') for x in range(0, len(self.exps)): if isinstance(self.exps[x], Alias): self.aliast[i] = self.exps[i].nombre # filtros if self.where != None: result = self.optwhere(ent, result, tablas) # combining(union,intersect,except) if self.combinig != None: datos2 = self.combinig.select.ejecutar(ent, 0) enc2 = datos2[0] res2 = datos2[1] result = self.m_combining(self.combinig, self.encabezado, result, enc2, res2) aber = result # limitar resultados if self.limit != None: a = self.limit result = self.m_limit(result, a.limit, a.off) # acceder a columnas if len(self.exps) == 1: if self.exps[0].tipo.tipo == 'identificador': newenc = [] 'obtengo solo columnas pedidas' for i in range(0, len(self.encabezado)): nombrediv = self.encabezado[i].split('.') nombrecol = nombrediv[0] if self.exps[0].getval(ent).valor == nombrecol: for x in range(0, len(result)): valcol = result[x][i] result[x] = [valcol] if (len(newenc) == 0): newenc.append(self.encabezado[i]) self.encabezado = newenc else: '' else: newenc = [] newres = [] for i in range(0, len(self.exps)): if isinstance(self.exps[i], Terminal): if self.exps[i].tipo.tipo == 'identificador': for j in range(0, len(self.encabezado)): nombrediv = self.encabezado[j].split('.') nombrecol = nombrediv[0] if self.exps[i].getval( ent).valor == nombrecol: newenc.append(self.encabezado[j]) for x in range(0, len(result)): valcol = result[x][j] if len(newres) != len(result): newres.append([valcol]) else: newres[x].append(valcol) else: if isinstance(self.exps[i], FuncionesNativas): newenc.append(self.exps[i].identificador) else: newenc.append('Exp' + len(newenc)) for fila in range(0, len(result)): exp = self.exps[i] res = self.resolver(exp, ent, result, tablas, fila) if len(newres) != len(result): newres.append([res.valor]) else: newres[fila].append(res.valor) result = newres self.encabezado = newenc #distinct if self.distinct != None: newres = [] 'elimino duplicados' for i in range(0, len(result)): encontrado = False fila = result[i] for j in range(0, len(result)): if j != i: if fila == result[j]: encontrado = True if encontrado == False: newres.append(fila) result = newres if imp == 1: self.mostarresult(result, self.encabezado, self.nombreres) return [self.encabezado, result] except Exception as inst: print(inst) return