def execute(self, environment):
        result2 = jsonMode.createDatabase(self.name)
        result = avlMode.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 #2
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:
             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 #3
0
 def execute(self, environment):
     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 #4
0
 def execute(self, environment):
     try:
         if self.structure == "TABLE":
             if instruction.dbtemp != "":
                 valor = storage.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 = storage.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 #5
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)
         result = avlMode.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:
             addPK2 = jsonMode.alterAddPK(instruction.dbtemp, self.name, pk)
             addPK = avlMode.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):
        """
        0: insert
        1: error
        2: exists
        """

        if self.mode == None:
            self.mode = 'avl'
        elif self.mode == 1:
            self.mode = 'avl'
        elif self.mode == 2:
            self.mode = 'b'
        elif self.mode == 3:
            self.mode = 'bplus'
        elif self.mode == 4:
            self.mode = 'dict'
        elif self.mode == 5:
            self.mode = 'isam'
        elif self.mode == 6:
            self.mode = 'json'
        elif self.mode == 7:
            self.mode = 'hash'

        result = storage.createDatabase(self.name, self.mode)
        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 #7
0
 def execute(self, environment):
     try:
         if self.option == "RENAME":
             valor = storage.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 #8
0
 def execute(self, environment):
     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 #9
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: ", name)
            syntaxPostgreErrors(
                "Error: 23000: El registro no cumple con la restriccion " + str(name)
            )
        elif insert:
            return
        else:
            lstErr.append(insert)

    except:
        lstErr.append(insert)
Beispiel #10
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 = 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()
Beispiel #11
0
def validateForeign(database, values, value):
    # values = [references,column]
    references = values[0]
    column = values[1]
    records = jsonMode.extractTable(database, references)
    if records == []:
        syntaxPostgreErrors(
            "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(
        "Error: 23505: El valor " + str(value) + " no es una llave primaria "
    )
Beispiel #12
0
 def execute(self, environment):
     result = storage.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]
Beispiel #13
0
import sys

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

# carga de datos
Struct.load()


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

    def execute(self, environment):
        try:
            # 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)
Beispiel #14
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]
Beispiel #15
0
import Fase1.analizer.typechecker.Metadata.Struct as S
from Fase1.analizer.abstract.expression import Expression
from Fase1.analizer.statement.expressions.primitive import Primitive
from Fase1.analizer.typechecker.Types.Type import Type
from Fase1.analizer.typechecker.Types.Type import TypeNumber
from Fase1.analizer.typechecker.Types.Validations import Number as N
from Fase1.analizer.typechecker.Types.Validations import Character as C
from Fase1.analizer.typechecker.Types.Validations import Time as T
from Fase1.storage.storageManager import jsonMode
from Fase1.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"]