Beispiel #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")
Beispiel #2
0
    def execute(self, environment):
        Struct.load()
        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
Beispiel #3
0
 def execute(self, environment):
     Struct.load()
     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")
Beispiel #4
0
 def execute(self, environment):
     Struct.load()
     alter = Struct.alterColumnsTable(instruction.dbtemp, self.table, self.params)
     if alter == None:
         alter = Checker.checkValue(instruction.dbtemp, self.table)
         Struct.save()
     if alter == None:
         alter = "Tabla alterada: " + self.table
     return alter
Beispiel #5
0
 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 = 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
Beispiel #6
0
    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
Beispiel #7
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
Beispiel #8
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"
         )
Beispiel #9
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
Beispiel #10
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"
Beispiel #11
0
import Parser.analizer.typechecker.Metadata.Struct as S
from Parser.analizer.abstract.expression import Expression
from Parser.analizer.statement.expressions.primitive import Primitive
from Parser.analizer.typechecker.Types.Type import Type
from Parser.analizer.typechecker.Types.Type import TypeNumber
from Parser.analizer.typechecker.Types.Validations import Number as N
from Parser.analizer.typechecker.Types.Validations import Character as C
from Parser.analizer.typechecker.Types.Validations import Time as T
from Parser.storage.storageManager import jsonMode
from Parser.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"]
Beispiel #12
0
import sys

sys.path.append("../../..")
from Parser.storage.storageManager import jsonMode
from Parser.analizer.typechecker.Metadata import Struct
from Parser.analizer.symbol.environment import Environment
from Parser.analizer.reports import Nodo
from Parser.analizer.abstract import instruction

# carga de datos
Struct.load()


class Delete(instruction.Instruction):
    def __init__(self, fromcl, wherecl, row, column):
        instruction.Instruction.__init__(self, row, column)
        self.wherecl = wherecl
        self.fromcl = fromcl

    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 cerca de ,", 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)
Beispiel #13
0
    def execute(self, environment):
        try:
            Struct.load()
            lista = []
            params = []
            tab = self.tabla

            for p in self.parametros:
                params.append(p.execute(environment))

            result = Checker.checkInsert(instruction.dbtemp, self.tabla,
                                         self.columns, params)

            if result[0] == None:
                for p in result[1]:
                    if p == None:
                        lista.append(p)
                    else:
                        lista.append(p.value)
                res = jsonMode.insert(instruction.dbtemp, tab, lista)
                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 result[0]
        except:
            instruction.syntaxPostgreSQL.append(
                "Error: P0001: Error en la instruccion INSERT")
            pass