Ejemplo n.º 1
0
def p_EXPV1(t):
    'EXP : EXP like cadena  %prec predicates'
    tipo = Tipo('varchar', t[3], -1, -1)
    tipo.getTipo()
    ter = Terminal(tipo, t[3])

    t[0] = Relacional(t[1], ter, 'like')
Ejemplo n.º 2
0
    def ejecutar(self, ent: Entorno):
        completo = self.nombre + '_' + ent.getDataBase()
        tabla: Simbolo = ent.buscarSimbolo(completo)
        if tabla != None:
            columnas = tabla.valor
            if len(self.valores) == len(columnas):
                i = 0
                correcto = True
                for columna in columnas:
                    nombre = columna.nombre
                    tipo = columna.tipo
                    util = Tipo(None, None, -1, -1)
                    if util.comparetipo(tipo, self.valores[i].tipo):
                        'todo correcto'
                    else:
                        correcto = False
                        return 'Error los tipos de los valores no coinciden con la definicion de la tabla'
                    i = i + 1
                terminales = []
                for val in self.valores:
                    terminales.append(val.getval(ent))
                    print("T ", terminales)

                r = DBMS.insert(ent.getDataBase(), self.nombre, terminales)
                if (r == 4):
                    return 'Error al Insertar Registro Violacion de Constraint Primary Key'

                return 'Registros insertados con exito'
Ejemplo n.º 3
0
def p_EXPV2(t):
    'EXP : EXP not like cadena  %prec predicates '
    tipo = Tipo('varchar', t[4], -1, -1)
    tipo.getTipo()
    ter = Terminal(tipo, t[4])
    rel = Relacional(t[1], ter, 'like')
    t[0] = Unaria(rel, 'not')
Ejemplo n.º 4
0
def p_TIPO(t):
    '''TIPO : smallint
            | integer
            | r_int
            | bigint
            | real
            | double precision
            | money
            | text
            | timestamp
            | date
            | time
            | interval
            | boolean
            | record
            | varchar'''

    listaBNF.append("TIPO ::= " + str(t[1]).lower())
    if str(t[1]).lower() == 'timestamp':
        tipo = Tipo('timestamp without time zone', None, -1, -1)
        t[0] = tipo
    elif str(t[1]).lower() == 'time':
        tipo = Tipo('time without time zone', None, -1, -1)
        t[0] = tipo
    else:
        t[0] = Tipo(t[1], None, -1, -1)
Ejemplo n.º 5
0
def p_EXP_FuncNativas2(t):
    '''EXP : id para parc '''
    tipo = None
    if t[1].lower() == 'now':
        tipo = Tipo('timestamp without time zone', t[1], len(t[1]), -1)
    elif t[1].lower() == 'random':
        tipo = Tipo('double', t[1], len(t[1]), -1)
    elif t[1].lower() == 'pi':
        tipo = Tipo('double', t[1], len(t[1]), -1)

    t[0] = Terminal(tipo, t[1].lower())
Ejemplo n.º 6
0
def p_TIPOE3(t):
    '''TIPO : numeric para int coma int parc
    | numeric para int parc
    | numeric '''
    tipo = None
    if len(t) == 7:
        tipo = Tipo('decimal', None, t[3], t[5])
    elif len(t) == 5:
        tipo = Tipo('decimal', None, t[3], -1)
    elif len(t) == 2:
        tipo = Tipo('decimal', None, -1, -1)

    t[0] = tipo
Ejemplo n.º 7
0
def p_TIPOE2(t):
    '''TIPO : decimal para  int coma int parc
            | decimal para int parc
            | decimal '''
    tipo = None
    if len(t) == 7:
        tipo = Tipo('decimal', None, t[3], t[5])
    elif len(t) == 5:
        tipo = Tipo('decimal', None, t[3], -1)
    elif len(t) == 2:
        tipo = Tipo('decimal', None, -1, -1)

    t[0] = tipo
Ejemplo n.º 8
0
class Aritmetica(Binaria):
    def __init__(self, exp1, exp2, operador):
        'Se usan los valores de las clases padres'
        Binaria.__init__(self,exp1,exp2,operador)

    def getval(self,entorno):
         if (self.exp1.tipo.tipo == 'identificador' or self.exp2.tipo.tipo == 'identificador'):
            return self

        valizq=self.exp1.getval(entorno);
        valder=self.exp2.getval(entorno);


        if type(valizq) not in (int, float, complex) or type(valder) not in (int, float, complex) :
            return 'Error ambos operandos deben ser numericos'

        if self.operador == '+':
            self.val = valizq+valder;
        elif self.operador == '-':
            self.val = valizq - valder;
        elif self.operador ==  '*':
            self.val = valizq * valder;
        elif self.operador == '/':
            self.val = valizq / valder;
        elif self.operador == '%':
            self.val = valizq % valder;
        elif self.operador == '^':
            self.val = valizq ** valder;

        tipo= Tipo(self.val,'decimal')
        self.tipo=tipo
        return self.val
Ejemplo n.º 9
0
    def getval(self, entorno):
        valizq = self.exp1.getval(entorno)
        valder = self.exp2.getval(entorno)

        if type(valizq) not in (int, float,
                                complex) or type(valder) not in (int, float,
                                                                 complex):
            return 'Error ambos operandos deben ser numericos'

        if self.operador == '+':
            self.val = valizq + valder
        elif self.operador == '-':
            self.val = valizq - valder
        elif self.operador == '*':
            self.val = valizq * valder
        elif self.operador == '/':
            self.val = valizq / valder
        elif self.operador == '%':
            self.val = valizq % valder
        elif self.operador == '^':
            self.val = valizq**valder

        tipo = Tipo(self.val, 'decimal')
        self.tipo = tipo
        return self.val
Ejemplo n.º 10
0
    def getval(self,entorno):

        valizq=self.exp1.getval(entorno)
        valder=self.exp2.getval(entorno)
        if valizq == None or valder == None:
            return self
        valizq=float(valizq.valor)
        valder=float(valder.valor)



        if type(valizq) not in (int, float, complex) or type(valder) not in (int, float, complex) :
            reporteerrores.append(Lerrores("Error Semantico",
                                           "Error los valores de los operandos deben ser numericos",
                                           0, 0))
            variables.consola.insert(INSERT,
                                     "Error los valores de los operandos deben ser numericos")

        if self.operador == '+':
            self.valor = valizq+valder
        elif self.operador == '-':
            self.valor = valizq - valder
        elif self.operador ==  '*':
            self.valor = valizq * valder
        elif self.operador == '/':
            self.valor = valizq / valder
        elif self.operador == '%':
            self.valor = valizq % valder
        elif self.operador == '^':
            self.valor = valizq ** valder

        tipo= Tipo(self.valor,'decimal')
        self.tipo=tipo
        return self
Ejemplo n.º 11
0
    def traducir(self,ent):
        'traduccion proc'
        nl=ent.newlabel()
        cad='goto ' + nl+'\n'
        cad+='label '+ent.newlabel('p_'+self.nombre)+'\n'
        cont=0
        lenparams=0
        if self.params != None:
            lenparams=len(self.params)

        for i in range(0,lenparams):
            val='stack['+str(i)+']'
            term=Terminal(Tipo('stack',None,-1,-1),val)
            d=Declaracion(self.params[i].nombre,False,self.params[i].tipo,term)
            c3d=d.traducir(ent).codigo3d
            cad+=c3d
            cont=i

        if self.instrucciones!=None:
            for inst in self.instrucciones:
                if inst !=None:
                    c3d= inst.traducir(ent).codigo3d
                    cad+=c3d
        cad+='temp=stack['+str(lenparams)+']\n'
        cad+='stack=[]\n'
        cad+='goto temp\n'
        cad+='label ' +nl+'\n'
        self.codigo3d=cad
        self.ejecutar(ent)
        return self
Ejemplo n.º 12
0
    def FunctionWithBucket(self, funcion, parametros, exp1, exp2, exp3, exp4):
        if (parametros == 4):
            if (exp1 < exp2 or exp1 > exp3):
                reporteerrores.append(
                    Lerrores("Error Semantico", "Valor" + str(exp1) + "no se encuentra en el rango", 0, 0))
                return "Error: El valor: " + str(exp1) + " no esta en el rango de: (" + str(exp2) + "," + str(
                    exp3) + ")"
            else:
                contador = 1
                for x in range(exp2, exp3):
                    contador = contador + 1

                columnas = int(contador / exp4)
                inicio = int(exp2)
                final = int(exp2) + (columnas)
                posbucket = 0
                for fila in range(0, exp4):
                    for valores in range(inicio, final):
                        if (exp1 == valores):
                            posbucket = fila + 1
                            msg="El valor de: " + str(exp1) + " esta en el bucket: " + str(posbucket)
                            tipo =Tipo('varchar',self.l(msg),-1,-1)
                            return Terminal(tipo,msg)
                    inicio = final
                    final = final + columnas
        else:
            reporteerrores.append(
                Lerrores("Error Semantico", "La funcion" + funcion + "solo recibe 2 parametros", 0, 0))
            return "Error: La funcion: " + funcion + " recibe 4 parametro"
Ejemplo n.º 13
0
def p_TIPOE3(t):
    '''TIPO : numeric para int coma int parc
    | numeric para int parc
    | numeric '''
    tipo = None
    srBNF: str = "TIPO ::= numeric"
    if len(t) == 7:
        srBNF += " para " + str(t[3]) + " coma " + str(t[5]) + " parc"
        tipo = Tipo('decimal', None, t[3], t[5])
    elif len(t) == 5:
        srBNF += " para " + str(t[3]) + " parc"
        tipo = Tipo('decimal', None, t[3], -1)
    elif len(t) == 2:
        tipo = Tipo('decimal', None, -1, -1)

    listaBNF.append(srBNF)
    t[0] = tipo
Ejemplo n.º 14
0
    def FunctionWithTreeParameter(self, funcion, parametros, exp1, exp2, exp3):
        if (parametros == 3):
            if (funcion == "substring"):
                inicio = exp2 - 1
                fin = inicio + exp3
                sub = exp1[inicio:fin]
                return Terminal(Tipo('decimal', sub, self.l(sub), -1), sub)

            elif (funcion == "substr"):
                inicio = exp2 - 1
                fin = inicio + exp3
                sub = exp1[inicio:fin]
                return Terminal(Tipo('decimal', sub, self.l(sub), -1), sub)
        else:
            reporteerrores.append(
                Lerrores("Error Semantico", "La funcion" + funcion + "solo recibe 3 parametros", 0, 0))
            return "Error: La funcion: " + funcion + " recibe 3 parametro"
Ejemplo n.º 15
0
def p_TIPOE2(t):
    '''TIPO : decimal para  int coma int parc
            | decimal para int parc
            | decimal '''
    strBNF: str = "TIPO ::= decimal "
    tipo = None
    if len(t) == 7:
        strBNF += "para " + str(t[3]) + " coma " + str(t[5]) + " parc"
        tipo = Tipo('decimal', None, t[3], t[5])
    elif len(t) == 5:
        strBNF += "para " + str(t[3]) + " parc"
        tipo = Tipo('decimal', None, t[3], -1)
    elif len(t) == 2:
        tipo = Tipo('decimal', None, -1, -1)

    listaBNF.append(strBNF)
    t[0] = tipo
Ejemplo n.º 16
0
    def unpack_byte_array(self, byte_array):
        datos = unpack('BIBBBBBf', byte_array)

        self.rand_id = datos[0]
        self.date = datos[1]
        self.sensor_id = SensorId(
            [Equipo(datos[2]), datos[3], datos[4], datos[5]])
        self.type = Tipo(datos[6])
        self.data = datos[7]
Ejemplo n.º 17
0
 def ejecutar(self, ent):
     'ejecucion de la definicion del procedimiento'
     simbolo = Simbolo(Tipo('Procedure', None, -1, -1), '_P' + self.nombre,
                       [self.params, self.instrucciones], -1)
     s = ent.nuevoSimbolo(simbolo)
     if s != 'ok':
         variables.consola.insert(
             INSERT, 'La funcion ' + self.nombre +
             ' no se pudo crear porque ya existe\n')
Ejemplo n.º 18
0
    def __init__(self, poke_file):
        try:
            print("Nome: ")
            self.__nome = Validacao(poke_file.readline(), str).validar()
            print("Level: ")
            self.__level = Validacao(int(poke_file.readline()), int).validar()
            self.__atributo = Atributo(poke_file)
            print("Tipo1: ")
            self.__tipo1 = Validacao(Tipo.get_tipo(poke_file.readline().strip()), Tipo).validar()
            print("Tipo2: ")
            self.__tipo2 = Validacao(Tipo.get_tipo(poke_file.readline().strip()), Tipo).validar()
            self.__lista_ataques = Ataques_List(poke_file).list

        except IndexError:
            print ("Arquivo de configuração do pokemon incorreto")

        except:
            raise
Ejemplo n.º 19
0
 def getval(self,entorno):
     'spliteo el timestamp'
     splited=self.timestamp.split(' ')
     fecha= splited[0]
     hora = splited[1]
     splitedfecha= fecha.split('-')
     splitedhora = hora.split(':')
     if self.field=='year':
         tipo=Tipo('integer',None,-1,-1)
         return Terminal(tipo,splitedfecha[0])
     elif self.field=='month':
         tipo = Tipo('integer', None, -1, -1)
         return Terminal(tipo,splitedfecha[1])
     elif self.field == 'day':
         tipo = Tipo('integer', None, -1, -1)
         return Terminal(tipo,splitedfecha[2])
     elif self.field=='hour':
         tipo = Tipo('integer', None, -1, -1)
         return Terminal(tipo,splitedhora[0])
     elif self.field=='minute':
         tipo = Tipo('integer', None, -1, -1)
         return Terminal(tipo,splitedhora[1])
     elif self.field == 'second':
         tipo = Tipo('integer', None, -1, -1)
         return Terminal(tipo,splitedhora[2])
Ejemplo n.º 20
0
    def ejecutar(self, ent:Entorno):
        tabla:Simbolo = ent.buscarSimbolo(self.nombre)
        if tabla != None:
            columnas=tabla.valor
            if len(self.valores)== len(columnas):
                i=0
                correcto=True
                for columna in columnas:
                    nombre=columna.nombre
                    tipo=columna.tipo
                    util=Tipo(None,None,-1,-1)
                    if util.comparetipo(tipo,self.valores[i].tipo):
                        'todo correcto'
                    else:
                        correcto=False
                        return 'Error los tipos de los valores no coinciden con la definicion de la tabla'
                    i=i+1
                terminales = []
                for val in self.valores:
                    terminales.append(val.getval(ent))

                DBMS.insert(ent.getDataBase(),tabla.nombre,terminales)
Ejemplo n.º 21
0
def p_TIPO(t):
    '''TIPO : smallint
            | integer
            | bigint
            | real
            | double precision
            | money
            | text
            | timestamp
            | date
            | time
            | interval
            | boolean'''
    t[0] = Tipo(t[1], None, -1, -1)
Ejemplo n.º 22
0
    def calcular_dano(self, pokemon_ataca, pokemon_defende, ataque):
        ataque = Validacao(ataque, Ataque).validar()

        if(self._acertar_ataque(ataque.acuracia)):
            STAB = 1.5 if (pokemon_ataca.tipo1 == ataque.tipo or pokemon_ataca.tipo2 == ataque.tipo)  else 1

            type = Tipo.get_type_multiplier(ataque.tipo, pokemon_defende.tipo1) * Tipo.get_type_multiplier(ataque.tipo, pokemon_defende.tipo2)
            if (type > 1): self.type = True
            elif (type == 0): self.type = None
            else: self.type = False



            #Other não implementado
            other = 1

            modifier = STAB * type * self._critical_multiplier(pokemon_ataca) * other * uniform(0.85, 1)

            damage = ( (2 * pokemon_ataca.level + 10)/250 * (pokemon_ataca.atributo.ATK/pokemon_defende.atributo.DEF) * ataque.poder + 2) * modifier

            return damage

        else: return 0
Ejemplo n.º 23
0
    def traducir(self, ent):
        'traduccion func'
        nl = ent.newlabel()
        cad = 'goto ' + nl + '\n'
        cad += 'label ' + ent.newlabel('f_' + self.nombre) + '\n'
        cont = 0
        lenparams = 0
        if self.params != None:
            lenparams = len(self.params)

        for i in range(0, lenparams):
            val = 'stack[' + str(i) + ']'
            term = Terminal(Tipo('stack', None, -1, -1), val)
            d = Declaracion(self.params[i].nombre, False, self.params[i].tipo,
                            term)
            c3d = d.traducir(ent).codigo3d
            cad += c3d
            cont = i

        if self.instrucciones != None:
            for inst in self.instrucciones:
                if inst != None:
                    c3d = inst.traducir(ent).codigo3d
                    cad += c3d
        cad += 'temp=stack[' + str(lenparams) + ']\n'
        cad += 'stack=[]\n'
        cad += 'goto temp\n'
        cad += 'label ' + nl + '\n'
        self.codigo3d = cad

        # string quemado
        sql = 'ci.ejecutarsql("create function ' + self.nombre + '('
        if self.params != None:
            for i in range(0, len(self.params)):
                if i > 0:
                    sql += ','
                if self.params[i].modo != None:
                    sql += 'inout '

                sql += self.params[i].nombre + ' ' + self.params[i].tipo.tipo

        sql += ') returns ' + self.tipo.tipo + ' as $$ '

        if self.instrucciones != None:
            for ins in self.instrucciones:
                sql += ins.traducir(ent).stringsql
        sql += ' $$ language plpgsql;\")\n'
        self.codigo3d = sql + self.codigo3d
        return self
Ejemplo n.º 24
0
    def ejecutar(self, ent: Entorno):
        'ejecutar asignacion'
        sim = ent.buscarSimbolo(self.nombre)
        if sim == None:
            reporteerrores.append(
                Lerrores("Error Semantico",
                         'Error,no existe la variable ' + self.nombre, 0, 0))
            variables.consola.insert(
                INSERT, 'Error,no existe la variable ' + self.nombre + '\n')
            return

        util = Tipo(None, None, -1, -1)
        if util.comparetipo(sim.Tipo, self.valor.tipo):
            sim.valor = self.valor.getval()
        else:
            reporteerrores.append(
                Lerrores(
                    "Error Semantico",
                    'Error,El valor que se desea asignar no coincide con el tipo de la variable '
                    + self.nombre, 0, 0))
            variables.consola.insert(
                INSERT,
                'Error,El valor que se desea asignar no coincide con el tipo sde la variable '
                + self.nombre + '\n')
Ejemplo n.º 25
0
def p_TIPO(t):
    '''TIPO : smallint
            | integer
            | r_int
            | bigint
            | real
            | double precision
            | money
            | text
            | timestamp
            | date
            | time
            | interval
            | boolean'''

    listaBNF.append("TIPO ::= " + str(t[1]).lower())
    t[0] = Tipo(t[1], None, -1, -1)
Ejemplo n.º 26
0
    def __init__(self, poke_file):
        self.__lista_ataques = list()

        print("Número de ataques: ")
        numero_de_ataques = Validacao(int(poke_file.readline()), int).validar()
        id_ataque = 0
        for i in range(0, numero_de_ataques):
            print("Nome do ataque: ")
            nome_ataque = Validacao(poke_file.readline().strip(), str).validar()
            print("Tipo do ataque: ")
            tipo_ataque = Tipo.get_tipo(Validacao(poke_file.readline().strip(), str).validar())
            print("Acurácia do ataque: ")
            acuracia_ataque = Validacao(int(poke_file.readline()), int).validar()
            print("Poder do ataque: ")
            poder_ataque = Validacao(int(poke_file.readline()), int).validar()
            print("Pontos do ataque: ")
            pontos_ataque = Validacao(int(poke_file.readline()), int).validar()

            self.__lista_ataques.append(Ataque(i+1, nome_ataque, tipo_ataque, acuracia_ataque, poder_ataque, pontos_ataque))
Ejemplo n.º 27
0
    def getval(self, entorno):

        if self.tipo.tipo == 'identificador':
            'buscar columna'

        if self.valor == 'CURRENT_DATE':
            self.tipo = Tipo('date', None, -1, -1)
            self.valor = str(date.today())
            return self
        elif self.valor == 'CURRENT_TIME':
            'retornar solo  la hora'
            now = datetime.now()
            self.tipo = Tipo('time without time zone', None, -1, -1)
            self.valor = str(now.hour)
            return self
        elif self.valor == 'now' and self.tipo.tipo == 'timestamp without time zone':
            self.valor = str(datetime.now())
            return self

        elif (self.valor == 'random'):
            value = rn.uniform(0, 1)
            self.tipo = Tipo('double', None, -1, -1)
            self.valor = value
            return self
        elif (self.valor == "pi"):

            self.valor = math.pi
            self.tipo = Tipo('numeric', None, len(str(self.valor)), -1)
            return self
        else:
            if str(self.valor).count('-') == 2 and str(
                    self.valor).count(':') == 2:
                if len(str(self.valor)) > 10:
                    self.tipo = Tipo('timestamp without time zone', None, -1,
                                     -1)
            elif str(self.valor).count('-') == 2:
                if len(str(self.valor)) == 10:
                    self.tipo = Tipo('date', None, -1, -1)
            elif str(self.valor).count(':') == 2:
                if len(str(self.valor)) >= 8:
                    self.tipo = Tipo('time without time zone', None, -1, -1)
            return self
Ejemplo n.º 28
0
    def getval(self, ent:Entorno):
        'ejecucion llamada funcinon'
        sim=ent.buscarSimbolo('_f'+self.nombre)
        if sim != None:
            tipo=sim.tipo
            defparams=sim.valor[0]
            instrucciones=sim.valor[1]
            newent=Entorno(ent)
            if self.parametros!=None and defparams!=None:
                if len(defparams)==len(self.parametros):
                    for i in range(0,len(defparams)):
                        param=defparams[i]
                        dec=Declaracion(param.nombre,False,param.tipo,self.parametros[i])
                        dec.ejecutar(newent)
                    for inst in instrucciones:
                        v=  inst.ejecutar(newent)
                        if v!=None:
                            util=Tipo('',None,-1,-1)
                            if util.comparetipo(v.tipo,tipo):
                                return v
                            else:
                                reporteerrores.append(Lerrores("Error Semantico", "Error el tipo devuelto no coincide con el de la funcion",  0, 0))
                                variables.consola.insert(INSERT, "Error el tipo devuelto no coincide con el de la funcion")

                else:
                    reporteerrores.append(Lerrores("Error Semantico","Error Los parametros no coinciden con la definicion de la funcion",0, 0))
                    variables.consola.insert(INSERT,"Error Los parametros no coinciden con la definicion de la funcion")
                    return
            else:
                for inst in instrucciones:
                    v = inst.ejecutar(newent)
                    if v != None:
                        util = Tipo('', None, -1, -1)
                        if util.comparetipo(v.tipo, tipo):
                            return v
                        else:
                            reporteerrores.append(
                                Lerrores("Error Semantico", "Error el tipo devuelto no coincide con el de la funcion",
                                         0, 0))
                            variables.consola.insert(INSERT, "Error el tipo devuelto no coincide con el de la funcion")
        else:
            reporteerrores.append(
                Lerrores("Error Semantico", "Error la funcion no existe",
                         0, 0))
            variables.consola.insert(INSERT, "Error la funcion no existe")
Ejemplo n.º 29
0
    def ejecutar(self, ent):
        'ejecutar asignacion'
        sim = ent.buscarSimbolo(self.nombre)
        if sim == None:
            reporteerrores.append(
                Lerrores("Error Semantico",
                         'Error,no existe la variable ' + self.nombre, 0, 0))
            variables.consola.insert(
                INSERT, 'Error,no existe la variable ' + self.nombre + '\n')
            return

        util = Tipo(None, None, -1, -1)
        if isinstance(self.valor, Select):
            val = self.valor.ejecutar(ent, 0)
            val = val[1][0]
            self.valor = Terminal(sim.tipo, val[0])
        if isinstance(self.valor, Terminal):
            sim.valor = self.valor.getval(ent).valor
            ent.editarSimbolo(self.nombre, sim)

        else:
            self.valor = self.valor.getval(ent)
            sim.valor = self.valor.getval(ent).valor
            ent.editarSimbolo(self.nombre, sim)
Ejemplo n.º 30
0
    def ejecutar(self, ent:Entorno):
        completo=str(self.nombre+'_'+ ent.getDataBase())
        tabla:Simbolo = ent.buscarSimbolo(completo)
        if tabla != None:
            columnas=tabla.valor
            i=0
            contador=0
            columnaunique=[]
            for columna in columnas:

                verificarnull=tabla.valor[i].atributos.get('not null')
                verificarprimary=tabla.valor[i].atributos.get('primary')
                verificarunique=tabla.valor[i].atributos.get('unique')
                verificarcheck=tabla.valor[i].atributos.get('check')

                condicion1:Expresion
                condicion2:Expresion
                if verificarunique!=None:
                    columnaunique.append(columna.nombre)



                if(verificarcheck!=None):
                    check=ent.buscarSimbolo(verificarcheck)
                    #print("Condicion:",check.valor.exp1.getval(ent).valor,check.valor.simbolo,check.valor.exp2.getval(ent).valor)

                    if isinstance(check.valor.exp1,Identificador):
                        condicion1=check.valor.exp1.getval(ent)
                        if condicion1==None:

                            condicion1=Terminal(columna.tipo, check.valor.exp1.nombre)
                    else:
                        condicion1 = Terminal(columna.tipo, check.valor.exp1.getval(ent).valor)

                    if isinstance(check.valor.exp2, Identificador):
                        condicion2 = check.valor.exp2.getval(ent)
                        if condicion2 == None:
                            condicion2 = Terminal(columna.tipo, check.valor.exp2.nombre)
                    else:
                        condicion2 = Terminal(columna.tipo, check.valor.exp2.getval(ent).valor)


                    operador=check.valor.simbolo
                    l=0
                    for columna in columnas:
                        #tipo=columna.tipo
                        if(check.valor.exp1.getval(ent)==columna.nombre):
                            k=0
                            for actual in self.namecolums:
                                if(check.valor.exp1.getval(ent)==actual.getval(ent).valor):
                                    condicion1=Terminal(columna.tipo,self.valores[k].getval(ent).valor)
                                k=k+1
                        l=l+1

                    n=0
                    for columna in columnas:
                        if(check.valor.exp2.getval(ent)==columna.nombre):
                            k=0
                            for actual in self.namecolums:
                                if(check.valor.exp2.getval(ent)==actual.getval(ent).valor):
                                    condicion2=Terminal(columna.tipo,self.valores[k].getval(ent).valor)
                                k=k+1
                        n=n+1

                    correcto=False
                    if operador in ('>','<','>=','<=','='):
                        #print(condicion1.getval(ent).valor,operador,condicion2.getval(ent).valor)
                        nuevaop = Relacional(condicion1,condicion2,operador);
                        if nuevaop.getval(ent):
                            correcto=True
                        else:
                            variables.consola.insert(INSERT,'Error Registro no cumple con condicion check\n')
                            reporteerrores.append(Lerrores("Error Semantico", 'Registro no cumple con condicion check','',''))
                            return

                    elif operador in ('or','and','not'):
                        nuevaop = Logica(condicion1,condicion2,operador);
                        if nuevaop.getval(ent):
                            correcto=True
                        else:
                            variables.consola.insert(INSERT,'Error Registro no cumple con condicion check\n')
                            reporteerrores.append(Lerrores("Error Semantico", 'Registro no cumple con condicion check','',''))
                            return




                if(verificarnull !=None or verificarprimary!=None or verificarunique!=None):
                    contador=contador+1
                i=i+1

                #print("contador",contador)
            if( (len(self.valores) >= contador) and (len(self.valores) == len(self.namecolums)) and (len(self.namecolums)<=len(columnas))):
                j=0
                t=0
                correcto=True
                terminales = []

                for columna in columnas:
                    if j < len(self.namecolums):
                        nombre=columna.nombre
                        tipo=columna.tipo
                        util=Tipo(None,None,-1,-1)
                        if isinstance(self.namecolums[j],Identificador):
                            v=self.namecolums[j].getval(ent)
                            if v==None:
                                self.namecolums[j] = Terminal(self.namecolums[j].tipo, self.namecolums[j].nombre)
                            else:
                                self.namecolums[j]=v

                        if(nombre==self.namecolums[j].valor):
                            #print("iguales",nombre,":",self.namecolums[j].getval(ent).valor,"J",j,"t",t)

                            for colunique in columnaunique:
                                if nombre==colunique:
                                    #print("UNIQUE",colunique,"colactual",nombre,"valor",self.valores[j].getval(ent).valor,"---")
                                    v=self.validarunique(ent,tabla,colunique,self.valores[j].getval(ent).valor)
                                    #print("-----",v)
                                    if v:
                                        variables.consola.insert(INSERT,'Error Violacion de Constraint Unique en columna:'+colunique +' : '+str(self.valores[j].getval(ent).valor)+'\n')
                                        reporteerrores.append(Lerrores("Error Semantico", 'Error Violacion de Constraint Unique en columna:'+colunique +' : '+str(self.valores[j].getval(ent).valor),'',''))
                                        return


                            buscado=str('ENUM_'+ent.getDataBase()+'_'+tipo.tipo)
                            types:Simbolo= ent.buscarSimbolo(buscado)

                            tipocorrecto = False

                            if types!=None:
                                tiposenum=types.valor
                                print("Comparando Enum")
                                for valenum in tiposenum:
                                    if str(valenum.getval(ent).valor).lower() == str(self.valores[j].getval(ent).valor).lower():
                                        tipocorrecto=True
                                if not tipocorrecto:
                                    variables.consola.insert(INSERT,str('Error Tipo enum no correcto en valor: '+self.valores[j].getval(ent).valor)+'\n')
                                    reporteerrores.append(Lerrores("Error Semantico",str('Tipo enum no correcto en valor: '+self.valores[j].getval(ent).valor),'',''))
                                    return



                            if not tipocorrecto:
                                if util.comparetipo(tipo,self.valores[j].getval(ent).tipo):
                                    'todo correcto'
                                else:
                                    correcto=False
                                    variables.consola.insert(INSERT,'Error los tipos no coinciden con la definicion de la tabla\n')
                                    reporteerrores.append(Lerrores("Error Semantico",'Tipo de datos en columanas no son iguales','',''))
                                    return


                            terminales.append(self.valores[j].valor)
                            j=j+1
                        else:
                            #print("diferentes",nombre,":",self.namecolums[j].getval(ent).valor,"J",j,"t",t)
                            terminales.append('')
                    else:
                        terminales.append('')
                r=DBMS.insert(ent.getDataBase(),self.nombre,terminales)
                if(r==4):
                    variables.consola.insert(INSERT,'Error violacion de Constraint Primary key\n')
                    reporteerrores.append(Lerrores("Error Semantico",'Violacion de Constraint primary Key','',''))
                    return
                elif r==0:
                    variables.consola.insert(INSERT, 'Registros Ingresados EXITOSAMENTE\n')





            else:
                variables.consola.insert(INSERT,'Error Numero Parametros en tabla '+self.nombre+' Incorrectos\n')
                reporteerrores.append(Lerrores('Erro semantico','Numero Parametros en tabla '+self.nombre+' Incorrectos','',''))
                return

        else:
            variables.consola.insert(INSERT,'Error Tabla '+self.nombre+' No Existe en la BD actual\n')
            reporteerrores.append(Lerrores('Error Semantico','Numero Parametros en tabla '+self.nombre+' Incorrectos','',''))
            return
Ejemplo n.º 31
0
    def ejecutar(self, ent:Entorno):
        completo=str(self.nombre+'_'+ent.getDataBase())
        tabla:Simbolo = ent.buscarSimbolo(completo)
        if tabla != None:
            columnas=tabla.valor
            columnaunique=[]
            columnacheck=[]

            if len(self.valores)== len(columnas):
                i=0
                correcto=True
                for columna in columnas:
                    verificarunique=tabla.valor[i].atributos.get('unique')
                    verificarcheck=tabla.valor[i].atributos.get('check')
                    nombre=columna.nombre
                    tipo=columna.tipo

                    condicion1:Expresion
                    condicion2:Expresion
                    if verificarunique!=None:
                        #print("unique",verificarunique,"m--",nombre)
                        columnaunique.append(columna.nombre)

                    for colunique in columnaunique:
                        if nombre==colunique:
                            #print("UNIQUE",colunique,"colactual",nombre,"valor",self.valores[i].getval(ent).valor,"---")
                            exp=self.valores[i].getval(ent)
                            exp=exp.valor
                            v=self.validarunique(ent,tabla,colunique,exp)
                            #print("-----",v)
                            if v:
                                #print('Error Violacion de Constraint Unique en:',colunique,' : ',self.valores[i].getval(ent).valor)
                                variables.consola.insert(INSERT,'Error Violacion de Constraint Unique en columna:'+colunique +' : '+str(self.valores[i].getval(ent).valor)+'\n')
                                reporteerrores.append(Lerrores("Error Semantico", 'Error Violacion de Constraint Unique en columna:'+colunique +' : '+str(self.valores[i].getval(ent).valor),'',''))
                                return

                    if(verificarcheck!=None):
                        check=ent.buscarSimbolo(verificarcheck)
                        #print("Condicion:",check.valor.exp1.getval(ent).valor,check.valor.simbolo,check.valor.exp2.getval(ent).valor)

                        if isinstance(check.valor.exp1, Identificador):
                            condicion1 = check.valor.exp1.getval(ent)
                            if condicion1 == None:
                                condicion1 = Terminal(columna.tipo, check.valor.exp1.nombre)
                        else:
                            condicion1 = Terminal(columna.tipo, check.valor.exp1.getval(ent).valor)

                        if isinstance(check.valor.exp2, Identificador):
                            condicion2 = check.valor.exp2.getval(ent)
                            if condicion2 == None:
                                condicion2 = Terminal(columna.tipo, check.valor.exp2.nombre)
                        else:
                            condicion2 = Terminal(columna.tipo, check.valor.exp2.getval(ent).valor)
                        operador=check.valor.simbolo
                        l=0
                        for columna in columnas:
                            #tipo=columna.tipo
                            if isinstance(check.valor.exp1, Identificador):
                                check.valor.exp1 = Terminal(check.valor.exp1.tipo, check.valor.exp1.nombre)

                            if(check.valor.exp1.getval(ent).valor==columna.nombre):
                                condicion1=Terminal(columna.tipo,self.valores[l].getval(ent).valor)
                            l=l+1

                        n=0
                        for columna in columnas:
                            if isinstance(check.valor.exp2, Identificador):
                                check.valor.exp2 = Terminal(check.valor.exp2.tipo, check.valor.exp2.nombre)

                            if(check.valor.exp2.getval(ent).valor==columna.nombre):

                                condicion2=Terminal(columna.tipo,self.valores[n].getval(ent).valor)
                            n=n+1

                        correcto=False
                        if operador in ('>','<','>=','<=','='):
                            #print(condicion1.getval(ent).valor,operador,condicion2.getval(ent).valor)
                            nuevaop = Relacional(condicion1,condicion2,operador)
                            if nuevaop.getval(ent).valor:
                                correcto=True
                            else:
                                variables.consola.insert(INSERT,'Error Registro no cumple con condicion check\n')
                                reporteerrores.append(Lerrores("Error Semantico", 'Registro no cumple con condicion check','',''))
                                return

                        elif operador in ('or','and','not'):
                            nuevaop = Logica(condicion1,condicion2,operador);
                            if nuevaop.getval(ent).valor:
                                correcto=True
                            else:
                                variables.consola.insert(INSERT,'Error Registro no cumple con condicion check\n')
                                reporteerrores.append(Lerrores("Error Semantico", 'Error Registro no cumple con condicion check','',''))
                                return

                    buscado=str('ENUM_'+ent.getDataBase()+'_'+tipo.tipo)
                    types:Simbolo= ent.buscarSimbolo(buscado)

                    tipocorrecto = False

                    if types!=None:
                        tiposenum=types.valor
                        print("Comparando Enum")
                        for valenum in tiposenum:
                             if str(valenum.getval(ent).valor).lower() == str(self.valores[i].getval(ent).valor).lower():
                                  tipocorrecto=True
                        if not tipocorrecto:
                            variables.consola.insert(INSERT,str('Error Tipo enum no correcto en valor: '+self.valores[i].getval(ent).valor)+'\n')
                            reporteerrores.append(Lerrores("Error Semantico",str('Error Tipo enum no correcto en valor: '+self.valores[i].getval(ent).valor),'',''))
                            return


                    if not tipocorrecto:


                        util=Tipo(None,None,-1,-1)
                        #tabla:Simbolo = ent.buscarSimbolo(completo)


                        self.valores[i]=self.valores[i].getval(ent)

                        if util.comparetipo(tipo,self.valores[i].tipo):
                            'todo correcto'

                        else:
                            correcto=False
                            variables.consola.insert(INSERT,'Error los tipos no coinciden con la definicion de la tabla\n')
                            reporteerrores.append(Lerrores("Error Semantico",'Tipo de datos en columanas no son iguales','',''))
                            return

                    i=i+1
                terminales = []
                for val in self.valores:
                    terminales.append(val.valor)

                r=DBMS.insert(ent.getDataBase(),self.nombre,terminales)
                if(r==4):
                    variables.consola.insert(INSERT,'Error violacion de Constraint Primary key\n')
                    reporteerrores.append(Lerrores("Error Semantico",'Violacion de Constraint primary Key','',''))
                    return
                variables.consola.insert(INSERT,'Registros Ingresados EXITOSAMENTE\n')

                return
Ejemplo n.º 32
0
    def resolver(self,expresion,entorno,result,tablas,fila):
        #para expresion binaria
        if not isinstance(expresion,Terminal) and not isinstance(expresion,Unaria) and not isinstance(expresion,FuncionesNativas) and not isinstance(expresion,Identificador):
            'resuelvo logicas,aritmeticas y relacionales'
            exp1=expresion.exp1
            exp2=expresion.exp2
            res1=self.resolver(exp1,entorno,result,tablas,fila)
            res2=self.resolver(exp2,entorno,result,tablas,fila)

            op=None
            if isinstance(expresion,Logica):
                op=Logica(res1, res2, expresion.operador)
            if isinstance(expresion,Relacional):
                op =Relacional(res1, res2, expresion.operador)
            if isinstance(expresion,Aritmetica):
                op =Aritmetica(res1, res2, expresion.operador)

            return op.getval(entorno)
        elif isinstance(expresion,Unaria): #para expresion unaria
            exp=expresion.exp1
            res= self.resolver(exp,entorno,result,tablas,fila)
            op = Unaria(res,expresion.operador)
            return op.getval(entorno)

        else:
            'aqui resuelvo los terminales y funciones'
            if isinstance(expresion,Identificador):
                ''
                term=expresion.getval(entorno)
                if term!= None:
                    return term
                else:
                    for i in range(0, len(self.encabezado)):
                        nombrediv = self.encabezado[i].split('.')
                        nombrecol = nombrediv[0]
                        if expresion.nombre == nombrecol:
                            dato=result[fila][i]
                            tipo = None
                            if len(nombrediv) > 1:
                                tipo = self.gettipo(entorno, tablas, nombrediv[0], nombrediv[1])
                            else:
                                tipo = self.gettipo(entorno, tablas, nombrediv[0])
                            term=Terminal(tipo,dato)
                            return term
            elif isinstance(expresion,Terminal):
                if expresion.tipo.tipo=='acceso':
                    return self.getacceso(entorno,expresion,result,fila,tablas)
                else:
                    return expresion

            elif isinstance(expresion,FuncionesNativas):
                if expresion.identificador.lower()=='count':
                    t=Tipo('integer',None,-1,-1)
                    self.agregacion=1
                    return Terminal(t,len(result))
                tempexp=[]
                for exp in expresion.expresiones:
                    tempexp.append(exp)

                for j in range(0, len(expresion.expresiones)):
                    if isinstance(expresion.expresiones[j],Identificador):
                        val = expresion.expresiones[j].nombre
                        for i in range(0, len(self.encabezado)):
                            nombrediv = self.encabezado[i].split('.')
                            nombrecol = nombrediv[0]
                            if val == nombrecol:
                                tipo=None
                                if len(nombrediv)>1:
                                    tipo = self.gettipo(entorno, tablas, val,nombrediv[1])
                                else:
                                    tipo = self.gettipo(entorno, tablas, val)
                                dato = result[fila][i]
                                tempexp[j]=Terminal(tipo,dato)
                    func=FuncionesNativas(expresion.identificador, tempexp)
                return func.getval(entorno)
Ejemplo n.º 33
0
def p_TIPOE(t):
    'TIPO : interval cadena'
    listaBNF.append("TIPO ::= interval " + str(t[2]))
    tipo = Tipo('interval', None, -1, -1)
    t[0] = tipo