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 = 1 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 checkInsert(dbName, tableName, columns, values): lstErr.clear() table = S.extractTable(dbName, tableName) if table == 0: syntaxPostgreErrors.append("Error: 42000: La base de datos " + str(dbName) + " no existe") return ["Error: No existe la base de datos"] elif table == 1: syntaxPostgreErrors.append("Error: 42P01: La tabla " + str(tableName) + " no existe") return ["Error: No existe la tabla"] if columns != None: if len(columns) != len(values): syntaxPostgreErrors.append( "Error: 42611: definicion en numero de columnas invalida ") return ["Columnas fuera de los limites"] else: if len(values) != len(table["columns"]): syntaxPostgreErrors.append( "Error: 42611: definicion en numero de columnas invalida ") return ["Columnas fuera de los limites"] values = S.getValues(table, columns, values) if not values: syntaxPostgreErrors.append("Error: 42P10: Columnas no identificadas ") return ["Error: Columnas no identificadas"] pks = [] indexCol = 0 for col in table["columns"]: x = Type.get(col["type"]) value = values[indexCol] if not isinstance(value, Primitive): value = Primitive(x, value, 0, 0, 0) values[indexCol] = value if col["PK"]: pks.append(indexCol) indexCol += 1 # Validar la llave primaria if pks: validatePrimary(dbName, tableName, values, pks) indexCol = 0 for value in values: column = table["columns"][indexCol] if value.value != None and value.type != TYPE.NULL: value.value = convertDateTime(value.value, column["type"]) if column["Unique"]: validateUnique(dbName, tableName, value.value, indexCol) if column["FK"] != None: validateForeign(dbName, column["FK"], value.value) if column["Constraint"] != None: validateConstraint(column["Constraint"], values, dbName, tableName, column["type"]) select(column, value) else: value.value = None validateNotNull(column["NN"], column["name"]) indexCol += 1 return [listError(), values]
def execute(self, environment): Struct.load() Index = File.importFile("Index") exists = Index.get(self.name) result = [] if not exists: if self.exists: result.append("El INDEX : " + self.name + " no existe") else: result.append("Error: El INDEX : " + self.name + " no existe") return result if not self.id: exists = Index.get(self.newName) if not exists: Index[self.newName] = Index.pop(self.name) result.append("Se cambio el nombre del INDEX : " + self.name + " a " + self.newName) else: result.append("Error: El INDEX : " + self.newName + " ya existe") else: column = self.newName index = Index[self.name] for c in index["Columns"]: if c["Name"] == column: if type(self.id) == int: table = index["Table"] columns = Struct.extractColumns( instruction.dbtemp, table) if columns: if self.id > len(columns): result.append("Error fatal: INDEX " + self.name + "numero de columna invalido") else: col = columns[self.id - 1].name c["Name"] = col result.append("INDEX : " + self.name + " cambio la columna " + column + " por " + col) else: result.append("Error fatal: INDEX " + self.name) else: c["Name"] = self.id result.append("INDEX : " + self.name + " cambio la columna " + column + " por " + self.id) Index[self.name] = index break if result == []: result.append("Error fatal: INDEX " + self.name + " columna invalida : " + self.newName) File.exportFile(Index, "Index") return result
def execute(self, environment): Struct.load() lista = [] for value in self.values: lista.append(value.execute(environment).value) result = Struct.createType(self.exists, self.name, lista) if result == None: report = "Type creado" else: report = result return report
def execute(self, environment): Struct.load() try: if self.option == "RENAME": form_data = {'nameDBold': self.name, 'nameDBnew': self.newname} resp = requests.post('http://127.0.0.1:9998/DB/alterDatabase', json=form_data) json1 = json.loads(resp.text) valor = json1["code"] if valor == 2: instruction.semanticErrors.append([ "La base de datos " + str(self.name) + " no existe", self.row ]) instruction.syntaxPostgreSQL.append( "Error: 42000: La base de datos " + str(self.name) + " no existe") return "La base de datos no existe: '" + self.name + "'." if valor == 3: instruction.semanticErrors.append([ "La base de datos " + str(self.newname) + " ya existe", self.row, ]) instruction.syntaxPostgreSQL.append( "Error: 42P04: La base de datos " + str(self.newname) + " ya existe") return "El nuevo nombre para la base de datos existe" if valor == 1: instruction.syntaxPostgreSQL.append( "Error: XX000: Error interno") return "Hubo un problema en la ejecucion de la sentencia" if valor == 0: # Struct.alterDatabaseRename(self.name, self.newname) return ("Base de datos renombrada: " + self.name + " - " + self.newname) return "Error ALTER DATABASE RENAME: " + self.newname elif self.option == "OWNER": valor = 0 if valor == 0: return "Instruccion ejecutada con exito ALTER DATABASE OWNER" instruction.syntaxPostgreSQL.append( "Error: XX000: Error interno") return "Error ALTER DATABASE OWNER" instruction.syntaxPostgreSQL.append("Error: XX000: Error interno") return "Fatal Error ALTER DATABASE: " + self.newname except: instruction.syntaxPostgreSQL.append( "Error: P0001: Error en la instruccion ALTER DATABASE")
def execute(self, environment): form_data = {'nameDB': instruction.dbtemp, 'nameTab': self.name} resp = requests.post('http://127.0.0.1:9998/TABLE/extractTable', json=form_data) json1 = json.loads(resp.text) valor = json1["code"] if valor == 1: instruction.semanticErrors.append([ "La tabla " + str(self.name) + " no pertenece a la base de datos " + instruction.dbtemp, self.row, ]) instruction.syntaxPostgreSQL.append("Error: 42P01: la relacion " + instruction.dbtemp + "." + str(self.name) + " no existe") return "FATAL ERROR TABLE ID" # Almacena una lista con con el nombre y tipo de cada columna lst = Struct.extractColumns(instruction.dbtemp, self.name) columns = [l.name for l in lst] newColumns = [self.name + "." + col for col in columns] df = pd.DataFrame(result, columns=newColumns) environment.addTable(self.name) tempTypes = {} for i in range(len(newColumns)): tempTypes[newColumns[i]] = lst[i].type return [df, tempTypes]
def execute(self, environment): Struct.load() tempDf = None for i in range(len(self.tables)): exec = self.tables[i].execute(environment) data = exec[0] types = exec[1] if isinstance(self.tables[i], Select): newNames = {} subqAlias = self.aliases[i] for (columnName, columnData) in data.iteritems(): colSplit = columnName.split(".") if len(colSplit) >= 2: newNames[columnName] = subqAlias + "." + colSplit[1] types[subqAlias + "." + colSplit[1]] = columnName else: newNames[columnName] = subqAlias + "." + colSplit[0] types[subqAlias + "." + colSplit[0]] = columnName data.rename(columns=newNames, inplace=True) environment.addVar(subqAlias, subqAlias, "TABLE", self.row, self.column) else: sym = Symbol( self.tables[i].name, None, self.tables[i].row, self.tables[i].column, ) environment.addSymbol(self.tables[i].name, sym) if self.aliases[i]: environment.addSymbol(self.aliases[i], sym) if i == 0: tempDf = data else: tempDf = self.crossJoin([tempDf, data]) environment.dataFrame = tempDf try: environment.types.update(types) except: instruction.syntaxPostgreSQL.append( "Error: P0001: Error en la instruccion SELECT clausula FROM" ) return
def execute(self, environment): Struct.load() name = self.idIndex if self.existIndex(name): return "Error: ya existe un index con el nombre " + name table = Struct.extractTable(instruction.dbtemp, self.idTable) if table == 1 or table == 0: return ( "Error: no existe la tabla " + self.idTable + " en la base de datos " + instruction.dbtemp ) try: Index = File.importFile("Index") indexBody = {} indexBody["Table"] = self.idTable indexBody["Unique"] = self.unique indexBody["Method"] = self.usingMethod indexBody["Columns"] = [] for c in self.optList: col = {} col["Name"] = c[0] col["Order"] = c[1] if c[2]: nulls = c[2][0] if c[2][1]: nulls += " " + c[2][1] else: if col["Order"] == "DESC": nulls = "NULLS FIRST" else: nulls = "NULLS LAST" col["Nulls"] = nulls indexBody["Columns"].append(col) Index[name] = indexBody File.exportFile(Index, "Index") return "Index " + name + " creado" except: return "Error fatal"
def execute(self, environment): Struct.load() # alter = Struct.alterColumnsTable(instruction.dbtemp, self.table, self.params) if ((self.params[0])[0] == "ADD"): form_data = { 'nameDB': instruction.dbtemp, 'nameTab': self.table, 'default': self.params } resp = requests.post('http://127.0.0.1:9998/TABLE/alterAddColumn', json=form_data) json1 = json.loads(resp.text) valor = json1["code"] if valor == 0: alter = "Tabla alterada: " + self.table elif valor == 1: alter = "Error la modificar la tabla" + self.table elif valor == 2: alter = "La base de datos" + instruction.dbtemp + " no existe" elif valor == 3: alter = "La tabla " + self.table + " no existe en la base de datos" else: ArraySplit = (((self.params[0])[1])[1]).split("_") form_data = { 'nameDB': instruction.dbtemp, 'nameTab': self.table, 'numCol': int(ArraySplit[1]) } resp = requests.post('http://127.0.0.1:9998/TABLE/alterDropColumn', json=form_data) json1 = json.loads(resp.text) valor = json1["code"] if valor == 0: alter = "Tabla alterada: " + self.table elif valor == 1: alter = "Error la modificar la tabla" + self.table elif valor == 2: alter = "La base de datos" + instruction.dbtemp + " no existe" elif valor == 3: alter = "La tabla " + self.table + " no existe en la base de datos" return alter
def validateConstraint(values, record, database, table, type_): # values = [name,[exp1,exp2,op,type1,type2]] # record = [val1,val2,...,valn] name = values[0] value1 = values[1][0] value2 = values[1][1] op = values[1][2] type1 = values[1][3] type2 = values[1][4] index1 = 0 index1 = 0 if type1 == "ID": index1 = S.getIndex(database, table, value1) value1 = record[index1].value if type2 == "ID": index2 = S.getIndex(database, table, value2) value2 = record[index2].value insert = CheckOperation(value1, value2, type_, op) try: if not insert: lstErr.append("El registro no cumple con la restriccion: ", name) syntaxPostgreErrors.append( "Error: 23000: El registro no cumple con la restriccion " + str(name)) elif insert: return else: lstErr.append(insert) except: lstErr.append(insert)
def checkValue(dbName, tableName): lstErr.clear() table = S.extractTable(dbName, tableName) if table == 0 and table == 1: return for col in table["columns"]: if col["Default"] != None: if col["Default"][1] != 9: value = Primitive(TypeNumber.get(col["Default"][1]), col["Default"][0], 0, 0, 0) select(col, value) if len(lstErr) != 0: col["Default"] = None else: col["Default"] = None return listError()
def validateForeign(database, values, value): # values = [references,column] references = values[0] column = values[1] records = jsonMode.extractTable(database, references) if records == []: syntaxPostgreErrors.append("Error: 23503: El valor " + str(value) + " no es una llave foranea ") lstErr.append("El Valor " + str(value) + " no es una llave foranea") return index = S.getIndex(database, references, column) for record in records: if value == record[index]: return lstErr.append("El Valor " + str(value) + " no es una llave primaria") syntaxPostgreErrors.append("Error: 23505: El valor " + str(value) + " no es una llave primaria ")
def ambiguityBetweenColumns(self, column): """ Encargada de buscar ambiguedad de una columna entre todas las tablas de la clausula FROM """ env = self i = 0 table = None for t in env.tables: lst = Struct.extractColumns(env.database, t) for l in lst: if l.name == column: i += 1 table = t break if i > 1: print("Error: Existe ambiguedad entre la culumna:", column) return [True, None] return [False, table]
def execute(self, environment): Struct.load() form_data = {'nameDB': self.name} resp = requests.post('http://127.0.0.1:9998/DB/CreateDB', json=form_data) """ 0: insert 1: error 2: exists """ json1 = json.loads(resp.text) result = json1["code"] if self.mode == None: self.mode = 1 if result == 0: Struct.createDatabase(self.name, self.mode, self.owner) report = "Base de datos: " + self.name + " insertada." elif result == 1: instruction.syntaxPostgreSQL.append("Error: XX000: Error interno") report = "Error al insertar la base de datos: " + self.name elif result == 2 and self.replace: Struct.replaceDatabase(self.name, self.mode, self.owner) form_data = {'nameDB': self.name} resp = requests.post('http://127.0.0.1:9998/DB/dropDatabase', json=form_data) form_data = {'nameDB': self.name} resp = requests.post('http://127.0.0.1:9998/DB/CreateDB', json=form_data) report = "Base de datos '" + self.name + " ' reemplazada." elif result == 2 and self.exists: report = "Base de datos no insertada, " + self.name + " ya existe." else: instruction.semanticErrors.append([ "La base de datos " + str(self.name) + " ya existe", self.row ]) instruction.syntaxPostgreSQL.append( "Error: 42P04: La base de datos " + str(self.name) + " ya existe") report = "Error: La base de datos ya existe" return report
def execute(self, environment): Struct.load() # insert = [posiblesErrores,noColumnas] insert = Struct.insertTable( instruction.dbtemp, self.name, self.columns, self.inherits ) error = insert[0] nCol = insert[1] if not error: error = True """ Result 0: insert 1: error 2: not found database 3: exists table """ if True: form_data = {'nameDB': instruction.dbtemp, 'nameTab': self.name, 'numCol': nCol} resp = requests.post('http://127.0.0.1:9998/TABLE/createTable', json=form_data) json1 = json.loads(resp.text) result = json1["code"] if result == 0: pass elif result == 1: instruction.syntaxPostgreSQL.append("Error: XX000: Error interno") return "Error: No se puede crear la tabla: " + self.name elif result == 2: instruction.semanticErrors.append( "La base de datos " + instruction.dbtemp + " no existe" ) instruction.syntaxPostgreSQL.append( "Error: 3F000: base de datos" + instruction.dbtemp + " no existe" ) return "Error: Base de datos no encontrada: " + instruction.dbtemp elif result == 3 and self.exists: instruction.semanticErrors.append( ["La tabla " + str(self.name) + " ya existe", self.row] ) instruction.syntaxPostgreSQL.append( "Error: 42P07: La tabla " + str(self.name) + " ya existe" ) return "La tabla ya existe en la base de datos" else: instruction.semanticErrors.append( ["La tabla " + str(self.name) + " ya existe", self.row] ) instruction.syntaxPostgreSQL.append("Error: 42P07: tabla duplicada") return "Error: ya existe la tabla " + self.name pk = "" addPK = 0 if pk: addPK = jsonMode.alterAddPK(instruction.dbtemp, self.name, pk) if addPK != 0: instruction.syntaxPostgreSQL.append( "Error: 23505: Error en llaves primarias de la instruccion CREATE TABLE de la tabla " + str(self.name) ) return "Tabla " + self.name + " creada" else: # Struct.dropTable(instruction.dbtemp, self.name) return error
import sys sys.path.append("../../..") # from storage.storageManager import jsonMode from team29.analizer.typechecker.Metadata import Struct from team29.analizer.typechecker import Checker from team29.analizer.reports import Nodo from team29.analizer.abstract import instruction import requests import json # carga de datos Struct.load() class InsertInto(instruction.Instruction): def __init__(self, tabla, columns, parametros, row, column): instruction.Instruction.__init__(self, row, column) self.tabla = tabla self.parametros = parametros self.columns = columns def execute(self, environment): Struct.load() lista = [] params = [] tab = self.tabla for p in self.parametros: params.append(p.execute(environment))
def execute(self, environment): Struct.load() if self.structure == "TABLE": if instruction.dbtemp != "": form_data = { 'nameDB': instruction.dbtemp, 'nameTab': self.name } resp = requests.post('http://127.0.0.1:9998/TABLE/dropTable', json=form_data) json1 = json.loads(resp.text) valor = json1["code"] if valor == 2: instruction.semanticErrors.append([ "La base de datos " + str(instruction.dbtemp) + " no existe", self.row, ]) instruction.syntaxPostgreSQL.append( "Error: 42000: La base de datos " + str(instruction.dbtemp) + " no existe") return "La base de datos no existe" if valor == 3: instruction.semanticErrors.append([ "La tabla " + str(self.name) + " no existe", self.row ]) instruction.syntaxPostgreSQL.append( "Error: 42P01: La tabla " + str(self.name) + " no existe") return "La tabla no existe en la base de datos" if valor == 1: instruction.syntaxPostgreSQL.append( "Error: XX000: Error interno") return "Hubo un problema en la ejecucion de la sentencia DROP" if valor == 0: Struct.dropTable(instruction.dbtemp, self.name) return "DROP TABLE Se elimino la tabla: " + self.name instruction.syntaxPostgreSQL.append( "Error: 42000: Base de datos no especificada ") return "El nombre de la base de datos no esta especificado operacion no realizada" else: form_data = {'nameDB': self.name} resp = requests.post('http://127.0.0.1:9998/DB/dropDatabase', json=form_data) json1 = json.loads(resp.text) valor = json1["code"] if valor == 1: instruction.syntaxPostgreSQL.append( "Error: XX000: Error interno") return "Hubo un problema en la ejecucion de la sentencia" if valor == 2: instruction.semanticErrors.append([ "La base de datos " + str(self.name) + " no existe", self.row, ]) instruction.syntaxPostgreSQL.append( "Error: 42000: La base de datos " + str(self.name) + " no existe") return "La base de datos no existe" if valor == 0: Struct.dropDatabase(self.name) return "Instruccion ejecutada con exito DROP DATABASE" instruction.syntaxPostgreSQL.append( "Error: XX000: Error interno DROPTABLE") return "Fatal Error: DROP TABLE"
def execute(self, environment): Struct.load() lista = [] params = [] tab = self.tabla for p in self.parametros: params.append(p.execute(environment)) if True: for p in params: if p == None: lista.append(p) else: lista.append(p.value) form_data = {'nameDB': instruction.dbtemp, 'nameTab': tab, 'registrer': lista} resp = requests.post('http://127.0.0.1:9998/TUPLA/insert', json=form_data) json1 = json.loads(resp.text) res = json1["code"] if res == 2: instruction.semanticErrors.append( [ "La base de datos " + instruction.dbtemp + " no existe", self.row, ] ) instruction.syntaxPostgreSQL.append( "Error: 42000: La base de datos " + str(instruction.dbtemp) + " no existe" ) return "La base de datos no existe" elif res == 3: instruction.semanticErrors.append( ["La tabla " + str(tab) + " no existe", self.row] ) instruction.syntaxPostgreSQL.append( "Error: 42P01: La tabla " + str(tab) + " no existe" ) return "No existe la tabla" elif res == 5: instruction.semanticErrors.append( [ "La instruccion INSERT tiene mas o menos registros que columnas", self.row, ] ) instruction.syntaxPostgreSQL.append( "Error: 42611: INSERT tiene mas o menos registros que columnas " ) return "Columnas fuera de los limites" elif res == 4: instruction.semanticErrors.append( [ "El valor de la clave esta duplicada, viola la restriccion unica", self.row, ] ) instruction.syntaxPostgreSQL.append( "Error: 23505: el valor de clave esta duplicada, viola la restricción única " ) return "Llaves primarias duplicadas" elif res == 1: instruction.syntaxPostgreSQL.append("Error: XX000: Error interno") return "Error en la operacion" elif res == 0: return "Fila Insertada correctamente" else: return res
import team29.analizer.typechecker.Metadata.Struct as S from team29.analizer.abstract.expression import Expression from team29.analizer.statement.expressions.primitive import Primitive from team29.analizer.typechecker.Types.Type import Type from team29.analizer.typechecker.Types.Type import TypeNumber from team29.analizer.typechecker.Types.Validations import Number as N from team29.analizer.typechecker.Types.Validations import Character as C from team29.analizer.typechecker.Types.Validations import Time as T # from storage.storageManager import jsonMode from team29.analizer.abstract.expression import TYPE from datetime import datetime lstErr = [] dbActual = "" S.load() syntaxPostgreErrors = [] def addError(error): if error != None: lstErr.append(error) def unir(errors): for err in errors: lstErr.append(err) def numeric(col, val): x = col["type"]