database.py 2.35 KB
import sqlite3
from enums import Table, States, Services, Datatypes

class DBconnection:

  tables = ["msg","history"]

  states = [States.queued,States.delivered]

  structure = {
    Table.id : "integer PRIMARY KEY"
    Table.file : "text"
    Table.serv : "text"
    Table.dest : "text"
    Table.type : "text"
    Table.state : "text"
  }

  def __init__(self,db):
    ipdb.set_trace()
    self.db = db
    query = "CREATE TABLE IF NOT EXISTS msg("
    for column in DBconnection.structure:
      query += column + " " + DBconnection.structure[column] + ","
    query[-1] = ")"
    # main table
    self.query(query)
    # delivered messages that were informed
    self.query(query.replace("msg","history",1))

  def query(self,query,*args):
    if query.upper().find("INSERT") == 0:
      return "Use la funcion insert() para insertar"
    entities = None
    for ar in args:
      entities = ar
    con = sqlite3.connect(self.db)
    cursor = con.cursor()
    if entities:
      cursor.execute(query,entities)
    else:
      cursor.execute(query)
    rows = cursor.fetchall()
    con.commit()
    con.close()
    return rows

  def insert(self,table,insertions):
    if not table in DBconnection.tables:
      return "La tabla " + table + " no existe o no está contemplada"
    query = "INSERT INTO " table + "("
    values = " VALUES("
    for column in insertions:
      if not check(column,insertions[column]):
        return "El dato '" + insertions[column] + "' no es valido"
      query += column + ","
      values += insertions[column] + ","
    query[-1] = ")"
    values[-1] = ")"
    con = sqlite3.connect(self.db)
    cursor = con.cursor()
    cursor.execute(query + values)
    cursor.execute("SELECT last_insert_rowid()")
    id = cursor.fetchall()[0][0]
    con.commit()
    con.close()
    return id

  def check(self,column,data):
    if column == Table.serv:
      return Services.validate(data)
    if column == Table.dest and len(data) <= 13:
      return True
    if column == Table.type:
      return Datatypes.validate(data)
    if column == Table.state:
      return (data in DBconnection.states)
    return False

  @staticmethod
  def parseToTable(rows):
    dictarray = []
    for row in rows:
      dictrow = {}
      i = 0
      for column in DBconnection.structure:
        dictrow[column] = row[i]
        i = i + 1
      dictarray.append(dictrow)
    return dictarray