Ejemplo n.º 1
0
    def TryDecodeSQL(self, sql):
        """ Try all possible types of queries and return the correct type

        """
        # Clean the SQL query from comments and such
        sql = self.CleanSQL(sql)

        # CREATE DATABASE:

        # CREATE TABLE:
        out = self.try_CreateTable(sql)
        if out["type"] == "CREATE TABLE" or out["type"] == "ERROR":
            return out

        # INSERT
        out = self.try_insert(sql)
        if out["type"] == "INSERT" or out["type"] == "ERROR":
            return out

        # SELECT
        out = self.try_select(sql)
        if (out["type"] == "SELECT"):
            return out

        # The update query path:
        # The remove query path:
        # The select query path:
        return err.COMMANDNOTFOUNDERROR(sql)
Ejemplo n.º 2
0
    def TryCreateTable(self, name, fields):
        """ TODO: Description
        """
        # Check if all types exist, if one doesn't raise an error
        fbuild = {}
        for field in fields.keys():
            if not fields[field][0] in typeTable:
                return err.TYPENOTFOUNDERROR(fields[field][0])
            fbuild[field] = fields[field][0]

        self.name = name
        self.fields = fbuild  # Fields & types
        self.rows = []
        self.caster = TypeCaster()

        # Set constraints
        self.primary = "ID"
        self.setConstraints(fields)

        self.primaryIndex = {
        }  # Elke insert krijgt de primary key hier + de index ervan in de rows

        return res.DBResponse(type="SUCCESS",
                              operation="CREATE TABLE",
                              table=name)
Ejemplo n.º 3
0
    def Select(self, fields, conditions=[]):
        """ Select the fields for the rows for which the conditions are true.
        """
        out = []

        exec_cond = []

        # Turn the conditions into something useful
        for cond_field, action, value in conditions:
            # Typecheck conditions
            cond_type, cond_val = self.caster.TypeCast(value)
            if not self.fields[cond_field] == cond_type:
                return err.TYPEERROR(cond_field, self.fields[cond_field],
                                     cond_type)

            fun = False
            # Unpack the condition into a function
            if action == "=":  # WHERE A = B
                fun = lambda f: f[cond_field] == cond_val
            elif action == ">=":  # WHERE A >= B
                fun = lambda f: f[cond_field] >= cond_val
            elif action == "<=":  # WHERE A <= B
                fun = lambda f: f[cond_field] <= cond_val

            if not fun:
                # TODO: define an error for this
                return err.ERROR("INVALID CONDITIONING OPERATOR")

            exec_cond.append(fun)

        # Do the actual searching
        for row in self.rows:
            r = []
            use = True

            # Execute the conditions
            for cond in exec_cond:
                use = cond(row)

            # If all conditions hold, subset the row
            if use:
                for f in fields:
                    r.append(row[f])

                # If the row is usable
                out.append(r)
        return out
Ejemplo n.º 4
0
 def readCount(lineData):
     if lineData[0] == "|" and lineData[-1] == "|":
         lineData = lineData[1:-1]
     lineData = BEAT_COUNT + lineData[1:]
     try:
         targetValues["counter"] = registry.findMaster(lineData)
     except KeyError:
         raise DBErrors.BadCount(lineData)
Ejemplo n.º 5
0
    def select(self, table, fields, conditions):
        """ Select specified fields, of rows where all conditions are met
        """

        res = err.TABLENOTFOUNDERROR(table)
        if table in self.tablenames:
            res = self.tables[table].Select(fields, conditions)

        return res
Ejemplo n.º 6
0
    def insert(self, tbl, kvpairs):
        """ Insert a row into a table
        input:
            tbl     : string              : The name of the target table
            kvpairs : [(string, string)]  : A list of key-value pairs of values to insert into fields

        """
        res = err.TABLENOTFOUNDERROR(tbl)

        # TODO: THIS IS A TEST
        if tbl in self.tablenames:
            res = self.tables[tbl].Insert(kvpairs)

        return res
Ejemplo n.º 7
0
    def Insert(self, kvpairs):
        """ Check for uniqueness in the primary key and types, then finally add the type-cast value to the db
        """

        row = {}

        # Check whether the table has the key and ifso insert into row
        for key, value in kvpairs:
            if not self.fields.has_key(key):  # Check if key exists
                return err.KEYNOTFOUNDERROR(key, self.name)

                # Check for primary uniqueness
                if key == self.primary:
                    if value in self.self.primaryIndex.keys():
                        # TODO: Raise proper error
                        return err.ERROR(
                            text="Tried to insert not-unique primary key!")

                # Check types and typecast
                if not self.fields[key] == "TEXT":
                    type, cast = self.caster.TypeCast(value)
                    if type == self.fields[key]:  # Check for correct type
                        row[key] = cast
                    else:
                        return err.TYPEERROR(key, self.fields[key], type)
                else:
                    row[key] = value

        # Now fill up the missed keys in the row
        for key in self.fields.keys():
            if not row.has_key(key):
                row[key] = self.Defaults(key)

        # Finally add the row to the database
        self.rows.append(row)
        return res.DBResponse("SUCCESS", operation="INSERT", table=self.name)
Ejemplo n.º 8
0
 def _process(self):
     linesRead = 0
     for lineType, lineData in self._iterator:
         if lineData == None:
             lineData = self._convertNone
         if lineType == self._startLine:
             pass
         elif lineType == self._endLine:
             break
         elif lineType in self._lines:
             self._lines[lineType](lineData)
         else:
             raise DBErrors.UnrecognisedLine(self._iterator)
         if self._readLines is not None:
             linesRead += 1
             if linesRead == self._readLines:
                 break
Ejemplo n.º 9
0
    def setConstraints(self, constraints):
        """ Fills in a list of lambda functions for each of the fields
        input:
            TODO
        returns:
            DBResponse  :   The response of filling in the constraints; can be a type error
        """
        self.consts = {}

        for field in constraints.keys():
            funcs = []

            # Check the type consrtaint
            if not constraints[field][0] in typeTable:
                return err.TYPENOTFOUNDERROR(constraints[field][0])

            # Set the type constraint
            # type, cast = self.caster.TypeCast(value)
            print constraints[field][0]
            f = None
            if constraints[field][0] == "TEXT":
                f = lambda x: True
            else:
                f = lambda x: self.caster.TypeCast(x)[0] == constraints[field][
                    0]

            funcs.append(f)

            # The other constraitns
            for c in constraints[field][1:]:
                # primary:
                funcs.append(lambda x: not x in self.primaryIndex.keys())

                continue

            self.consts[field] = funcs

        return res.Response("ACC")
Ejemplo n.º 10
0
 def _parseNonNegativeInteger(self, data, lineName):
     data = self._parseInteger(data, lineName)
     if data < 0:
         raise DBErrors.InvalidNonNegativeInteger(self._iterator)
     return data
Ejemplo n.º 11
0
 def _parsePositiveInteger(self, data, lineName):
     data = self._parseInteger(data, lineName)
     if data <= 0:
         raise DBErrors.InvalidPositiveInteger(self._iterator)
     return data
Ejemplo n.º 12
0
 def _parseInteger(self, data, lineName):
     try:
         data = int(data)
     except (TypeError, ValueError):
         raise DBErrors.InvalidInteger(self._iterator)
     return data