Пример #1
0
 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")
Пример #2
0
 def f_elimnar_db(self):
     dll_db = simpledialog.askstring("Delete DB", "Ingresar nombre")
     query = "drop database " + dll_db + ";"
     #print(query)
     self.send_scritp(query)
     databases.load()
     self.f_charge_treeview()
Пример #3
0
 def execute(self, environment):
     if self.option == "RENAME":
         valor = jsonMode.alterDatabase(self.name, self.newname)
         if valor == 2:
             sintaxPostgreSQL.insert(
                 len(sintaxPostgreSQL),
                 "Error: 42P01: La base de datos  " + str(self.name) +
                 " no existe",
             )
             return "La base de datos no existe"
         if valor == 3:
             semanticErrors.insert(
                 len(semanticErrors),
                 "El nuevo nombre para la base da datos ya existe",
             )
             return "El nuevo nombre para la base de datos existe"
         if valor == 1:
             sintaxPostgreSQL.insert(len(sintaxPostgreSQL),
                                     "Error: XX000: Error interno")
             return "Hubo un problema en la ejecucion de la sentencia"
         if valor == 0:
             Struct.alterDatabaseRename(self.name, self.newname)
             return "Instruccion ejecutada con exito ALTER DATABASE RENAME"
         return "Error ALTER DATABASE RENAME"
     elif self.option == "OWNER":
         valor = Struct.alterDatabaseOwner(self.name, self.newname)
         if valor == 0:
             return "Instruccion ejecutada con exito ALTER DATABASE OWNER"
         sintaxPostgreSQL.insert(len(sintaxPostgreSQL),
                                 "Error: XX000: Error interno")
         return "Error ALTER DATABASE OWNER"
     return "Fatal Error ALTER DATABASE"
Пример #4
0
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")
        elif insert:
            return
        else:
            lstErr.append(insert)

    except:
        lstErr.append(insert)
Пример #5
0
    def execute(self, environment):
        result = jsonMode.createDatabase(self.name)
        """
        0: insert
        1: error
        2: exists
        """

        if self.mode == None:
            self.mode = 1

        if result == 0:
            Struct.createDatabase(self.name, self.mode, self.owner)
            report = "Base de datos insertada"
        elif result == 1:
            sintaxPostgreSQL.insert(len(sintaxPostgreSQL),
                                    "Error: XX000: Error interno")
            report = "Error al insertar la base de datos"
        elif result == 2 and self.replace:
            Struct.replaceDatabase(self.name, self.mode, self.owner)
            report = "Base de datos reemplazada"
        elif result == 2 and self.exists:
            report = "Base de datos no insertada, la base de datos ya existe"
        else:
            report = "Error: La base de datos ya existe"
            sintaxPostgreSQL.insert(len(sintaxPostgreSQL),
                                    "Error: 42P04: 	base de datos duplicada")
        return report
Пример #6
0
 def execute(self, environment):
     nCol = self.count()
     result = jsonMode.createTable(dbtemp, self.name, nCol)
     """
     Result
     0: insert
     1: error
     2: not found database
     3: exists table
     """
     if result == 0:
         insert = Struct.insertTable(dbtemp, self.name, self.columns,
                                     self.inherits)
         if insert == None:
             report = "Tabla " + self.name + " creada"
         else:
             jsonMode.dropTable(dbtemp, self.name)
             Struct.dropTable(dbtemp, self.name)
             report = insert
     elif result == 1:
         report = "Error: No se puedo crear la tabla: " + self.name
     elif result == 2:
         report = "Error: Base de datos no encontrada: " + dbtemp
     elif result == 3 and self.exists:
         report = "Tabla no creada, ya existe en la base de datos"
     else:
         report = "Error: ya existe la tabla " + self.name
     return report
Пример #7
0
    def execute(self, environment):
        result = jsonMode.createDatabase(self.name)
        """
        0: insert
        1: error
        2: exists
        """

        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)
            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
Пример #8
0
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]
Пример #9
0
 def execute(self, environment):
     alter = Struct.alterColumnsTable(dbtemp, self.table, self.params)
     if alter == None:
         alter = Checker.checkValue(dbtemp, self.table)
         Struct.save()
     if alter == None:
         alter = "Tabla alterada: " + self.table
     return alter
Пример #10
0
 def execute(self, environment):
     try:
         if self.structure == "TABLE":
             if instruction.dbtemp != "":
                 valor = jsonMode.dropTable(instruction.dbtemp, self.name)
                 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:
             valor = jsonMode.dropDatabase(self.name)
             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"
     except:
         instruction.syntaxPostgreSQL.append(
             "Error: P0001: Error en la instruccion DROP")
Пример #11
0
 def execute(self, environment):
     # insert = [posiblesErrores,noColumnas]
     insert = Struct.insertTable(instruction.dbtemp, self.name,
                                 self.columns, self.inherits)
     error = insert[0]
     nCol = insert[1]
     if not error:
         error = Checker.checkValue(instruction.dbtemp, self.name)
     """
     Result
     0: insert
     1: error
     2: not found database
     3: exists table
     """
     if not error:
         result = jsonMode.createTable(instruction.dbtemp, self.name, nCol)
         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 = Struct.extractPKIndexColumns(instruction.dbtemp, self.name)
         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
Пример #12
0
 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
Пример #13
0
 def execute(self, environment):
     try:
         if self.structure == "TABLE":
             if dbtemp != "":
                 valor = jsonMode.dropTable(dbtemp, self.name)
                 if valor == 2:
                     sintaxPostgreSQL.insert(
                         len(sintaxPostgreSQL),
                         "Error: 42P01: La base de datos  " +
                         str(self.name) + " no existe",
                     )
                     return "La base de datos no existe"
                 if valor == 3:
                     sintaxPostgreSQL.insert(
                         len(sintaxPostgreSQL),
                         "Error: 42P01: La tabla  " + str(self.name) +
                         " no existe",
                     )
                     return "La tabla no existe en la base de datos"
                 if valor == 1:
                     sintaxPostgreSQL.insert(len(sintaxPostgreSQL),
                                             "Error: XX000: Error interno")
                     return "Hubo un problema en la ejecucion de la sentencia"
                 if valor == 0:
                     Struct.dropTable(dbtemp, self.name)
                     return "Instruccion ejecutada con exito DROP TABLE"
             return "El nombre de la base de datos no esta especificado operacion no realizada"
         else:
             valor = jsonMode.dropDatabase(self.name)
             if valor == 1:
                 sintaxPostgreSQL.insert(len(sintaxPostgreSQL),
                                         "Error: XX000: Error interno")
                 return "Hubo un problema en la ejecucion de la sentencia"
             if valor == 2:
                 sintaxPostgreSQL.insert(
                     len(sintaxPostgreSQL),
                     "Error: 42P01: 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"
         sintaxPostgreSQL.insert(len(sintaxPostgreSQL),
                                 "Error: XX000: Error interno")
         return "Fatal Error: DropTable"
     except:
         raise
Пример #14
0
 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"
Пример #15
0
 def execute(self, environment):
     result = jsonMode.extractTable(instruction.dbtemp, self.name)
     if result == None:
         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]
Пример #16
0
 def execute(self, environment):
     Struct.load()
     try:
         if self.option == "RENAME":
             valor = jsonMode.alterDatabase(self.name, self.newname)
             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 = Struct.alterDatabaseOwner(self.name, self.newname)
             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")
Пример #17
0
def checkInsert(dbName, tableName, columns, values):
    lstErr.clear()
    S.load()

    if columns != None:
        if len(columns) != len(values):
            return "Columnas fuera de los limites 1"

    table = S.extractTable(dbName, tableName)
    values = S.getValues(table, columns, values)

    if table == 0:
        return "No existe la base de datos"
    elif table == 1:
        return "No existe la tabla"
    elif len(table["columns"]) != len(values):
        return "Columnas fuera de los limites 2"
    else:
        pass

    indexCol = 0
    for value in values:
        column = table["columns"][indexCol]
        if value != None and value.type != TYPE.NULL:

            if column["Unique"] or column["PK"]:
                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:
            validateNotNull(column["NN"], column["name"])

        indexCol += 1

    return [listError(), values]
Пример #18
0
 def execute(self, environment):
     nCol = self.count()
     result = jsonMode.createTable(dbtemp, self.name, nCol)
     """
     Result
     0: insert
     1: error
     2: not found database
     3: exists table
     """
     if result == 0:
         insert = Struct.insertTable(dbtemp, self.name, self.columns,
                                     self.inherits)
         if insert == None:
             pk = Struct.extractPKIndexColumns(dbtemp, self.name)
             addPK = 0
             if pk:
                 addPK = jsonMode.alterAddPK(dbtemp, self.name, pk)
             if addPK != 0:
                 print("Error en llaves primarias del CREATE TABLE:",
                       self.name)
             report = "Tabla " + self.name + " creada"
         else:
             jsonMode.dropTable(dbtemp, self.name)
             Struct.dropTable(dbtemp, self.name)
             report = insert
     elif result == 1:
         sintaxPostgreSQL.insert(len(sintaxPostgreSQL),
                                 "Error: XX000: Error interno")
         report = "Error: No se puede crear la tabla: " + self.name
     elif result == 2:
         sintaxPostgreSQL.insert(
             len(sintaxPostgreSQL),
             "Error: 3F000: base de datos" + dbtemp + " no existe",
         )
         report = "Error: Base de datos no encontrada: " + dbtemp
     elif result == 3 and self.exists:
         report = "Tabla no creada, ya existe en la base de datos"
     else:
         report = "Error: ya existe la tabla " + self.name
         sintaxPostgreSQL.insert(len(sintaxPostgreSQL),
                                 "Error: 42P07: tabla duplicada")
     return report
Пример #19
0
 def execute(self, environment):
     if self.option == "RENAME":
         valor = jsonMode.alterDatabase(self.name, self.newname)
         if valor == 2:
             return "La base de datos no existe"
         if valor == 3:
             return "El nuevo nombre para la base de datos existe"
         if valor == 1:
             return "Hubo un problema en la ejecucion de la sentencia"
         if valor == 0:
             Struct.alterDatabaseRename(self.name, self.newname)
             return "Instruccion ejecutada con exito ALTER DATABASE RENAME"
         return "Error ALTER DATABASE RENAME"
     elif self.option == "OWNER":
         valor = Struct.alterDatabaseOwner(self.name, self.newname)
         if valor == 0:
             return "Instruccion ejecutada con exito ALTER DATABASE OWNER"
         return "Error ALTER DATABASE OWNER"
     return "Fatal Error ALTER DATABASE"
Пример #20
0
    def execute(self, environment):
        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
Пример #21
0
 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
Пример #22
0
 def execute(self, environment):
     result = jsonMode.extractTable(dbtemp, self.name)
     if result == None:
         return "FATAL ERROR TABLE ID"
     # Almacena una lista con con el nombre y tipo de cada columna
     lst = Struct.extractColumns(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)
     return df
Пример #23
0
    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"
Пример #24
0
    def execute(self, environment):
        result = jsonMode.createDatabase(self.name)
        """
        0: insert
        1: error
        2: exists
        """

        if self.mode == None:
            self.mode = 1

        if result == 0:
            Struct.createDatabase(self.name, self.mode, self.owner)
            report = "Base de datos insertada"
        elif result == 1:
            report = "Error al insertar la base de datos"
        elif result == 2 and self.replace:
            Struct.replaceDatabase(self.name, self.mode, self.owner)
            report = "Base de datos reemplazada"
        elif result == 2 and self.exists:
            report = "Base de datos no insertada, la base de datos ya existe"
        else:
            report = "Error: La base de datos ya existe"
        return report
Пример #25
0
 def execute(self, environment):
     if self.structure == "TABLE":
         if dbtemp != "":
             valor = jsonMode.dropTable(dbtemp, self.name)
             if valor == 2:
                 return "La base de datos no existe"
             if valor == 3:
                 return "La tabla no existe en la base de datos"
             if valor == 1:
                 return "Hubo un problema en la ejecucion de la sentencia"
             if valor == 0:
                 Struct.dropTable(dbtemp, self.name)
                 return "Instruccion ejecutada con exito DROP TABLE"
         return "El nombre de la base de datos no esta especificado operacion no realizada"
     else:
         valor = jsonMode.dropDatabase(self.name)
         if valor == 1:
             return "Hubo un problema en la ejecucion de la sentencia"
         if valor == 2:
             return "La base de datos no existe"
         if valor == 0:
             Struct.dropDatabase(self.name)
             return "Instruccion ejecutada con exito DROP DATABASE"
     return "Fatal Error: DropTable"
Пример #26
0
 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")
Пример #27
0
def validateForeign(database, values, value):
    # values = [references,column]
    references = values[0]
    column = values[1]

    records = jsonMode.extractTable(database, references)

    if records == []:
        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")
Пример #28
0
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 = expression.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()
Пример #29
0
 def ambiguityBetweenColumns(self, column):
     """
     Encarga de buscar ambiguedad de una columna entre todas las tablas de
     la clausula FROM
     """
     env = self
     i = 0
     table = ""
     for t in env.tables:
         lst = Struct.extractColumns(env.database, t)
         for l in lst:
             if l.name == column:
                 i += 1
                 table = t
     if i > 1:
         print("Error: Existe ambiguedad entre la culumna:", column)
         return
     return table
Пример #30
0
 def execute(self, environment):
     result = jsonMode.extractTable(dbtemp, self.name)
     if result == None:
         sintaxPostgreSQL.insert(
             len(sintaxPostgreSQL),
             "Error: 42P01: la relacion " + 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(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]