Ejemplo n.º 1
0
def cmdb_update_execute(self):
    conn = self.database.get_conn()
    tbl = self.model_class._meta.db_table
    pk = self.model_class._meta.primary_key
    conn.lock(tbl)
    try:
        sql = ""
        for fld in self.model_class._meta.fields.values():
            if fld.unique:
                sql += " OR " if len(sql) > 0 else " WHERE "
                sql += "{0} = ?".format(fld.name)
        if len(sql) > 0:
            sql = "SELECT {1} FROM {0}".format(tbl, pk.name) + sql
            params = []
            for fld in self.model_class._meta.fields.values():
                if fld.unique:
                    params.append(self._update[fld])
            cursor = self.database.execute_sql(sql, params, False)
            res = cursor.fetchall()
            if len(res) > 1 or\
               (len(res) == 1 and res[0][0] != self._where.rhs):
                raise peewee.IntegrityError('unique constraint')
        return super(peewee.UpdateQuery, self)._execute()
    finally:
        conn.unlock(tbl)
Ejemplo n.º 2
0
def cmdb_insert_execute(self):
    conn = self.database.get_conn()
    tbl = self.model_class._meta.db_table
    conn.lock(['cmdbidtable', tbl])
    try:
        sql = ""
        for fld in self.model_class._meta.fields.values():
            if fld.unique:
                sql += " OR " if len(sql) > 0 else " WHERE "
                sql += "{0} = ?".format(fld.name)
        if len(sql) > 0:
            sql = "SELECT * FROM {0}".format(tbl) + sql
            for r in self._rows:
                params = []
                for fld in self.model_class._meta.fields.values():
                    if fld.unique:
                        params.append(r[fld])
                cursor = self.database.execute_sql(sql, params, False)
                if len(cursor.fetchall()) > 0:
                    raise peewee.IntegrityError('unique constraint')
        sql = "UPDATE cmdbidtable SET id = id + 1 WHERE name=?"
        pk = self.model_class._meta.primary_key
        params = (pk.sequence, )
        self.database.execute_sql(sql, params, False)
        sql = "SELECT id FROM cmdbidtable WHERE name=?"
        cursor = self.database.execute_sql(sql, params, False)
        id = cursor.fetchone()[0]
        field_dict = self._rows[0]
        field_dict[pk.db_column] = id
        return super(peewee.InsertQuery, self)._execute()
    finally:
        conn.unlock(['cmdbidtable', tbl])
Ejemplo n.º 3
0
def add_customer(
        customer_id,
        name,
        lastname,
        home_address,
        phone_number,  # pylint: disable=R0913
        email_address,
        status,
        credit_limit):
    """
    This function will add a new customer to the sqlite3 database.
    """
    try:
        new_customer = Customer.create(customer_id=customer_id,
                                       name=name,
                                       lastname=lastname,
                                       home_address=home_address,
                                       phone_number=phone_number,
                                       email_address=email_address,
                                       status=status,
                                       credit_limit=credit_limit)
        new_customer.save()
    except peewee.IntegrityError as exception:
        if 'unique' in str(exception).lower():
            LOGGER.warning(
                'Tried to add a customer_id that already exists: %s',
                customer_id)
            raise peewee.IntegrityError(
                'Tried to add a customer_id that already exists: {}'.format(
                    customer_id))
        LOGGER.debug("Integrity Error in add_customer: %s", str(exception))
    except Exception as exception:
        LOGGER.debug('add_customer exception: %s', str(exception))
        raise Exception('add_customer raised this error: {}'.format(
            str(exception)))
Ejemplo n.º 4
0
    def test_update_customer_credit_errors(self):
        """
        Validates value error thrown when updating a customer's credit limit
        if an exception (IntegrityError or OperationalError) is thrown.
        """
        mock_module = "basic_operations.Customers.get_or_none"
        with patch(mock_module) as get_none:
            get_none.side_effect = [
                peewee.IntegrityError("integrity"),
                peewee.OperationalError("operational")
            ]

            with self.assertRaises(ValueError):
                BaseOps.update_customer_credit("[]", 2.71)

            with self.assertRaises(ValueError):
                BaseOps.update_customer_credit("[]", 2.71)
Ejemplo n.º 5
0
    def save(self, *args: Any, **kwargs: Any) -> None:
        if not self._ignore_save_assert:
            assert (
                self.name not in (".", "..", "")
                and "/" not in self.name
                and not self.name.isdigit()
            ), f"Invalid folder name '{self.name}'"
            assert self.parent is not None, "Need to specify a parent folder"
        self._ignore_save_assert = False

        # can never be its own parent
        if self.parent == self:
            raise pw.IntegrityError("Folder can not be its own parent")

        self.updated_at = datetime.datetime.now()

        return super().save(*args, **kwargs)
Ejemplo n.º 6
0
    def test_write_customer_errors(self):
        """ Validates errors on writing customers to the DB """
        db_module = "create_customers_db.Customers.get_or_create"
        with patch(db_module) as db_helper:
            db_helper.side_effect = [
                peewee.IntegrityError("integrity"),
                peewee.OperationalError("operational")
            ]

            customer_list = [
                "1,2,3,4,5,6,active,2.01", "2,3,4,5,6,7,active,2.01"
            ]

            with self.assertLogs() as mock_logger:
                CreateDb.write_customers(customer_list)
                msg = "ERROR:root:integrity"
                self.assertIn(msg, mock_logger.output)

                msg = "ERROR:root:operational"
                self.assertIn(msg, mock_logger.output)
Ejemplo n.º 7
0
    def test_add_customer_exceptions(self):
        """
        Validates add customer exceptions (IntegrityError and OperationalError)
        are handled and elegantly logged.
        """
        with patch("basic_operations.Customers.get_or_create") as handle_get:
            handle_get.side_effect = [
                peewee.IntegrityError("integrity"),
                peewee.OperationalError("operational")
            ]

            with self.assertLogs() as mock_logger:
                BaseOps.add_customer("123", "Amelia", "Bedelia",
                                     "123 Starshine Ln.", "Pennsylvania 65000",
                                     "*****@*****.**", "active", 3.14)
                msg = "ERROR:basic_operations:integrity"
                self.assertIn(msg, mock_logger.output)

                BaseOps.add_customer("123", "Amelia", "Bedelia",
                                     "123 Starshine Ln.", "Pennsylvania 65000",
                                     "*****@*****.**", "active", 3.14)
                msg = "ERROR:basic_operations:operational"
                self.assertIn(msg, mock_logger.output)
Ejemplo n.º 8
0
	def validate_email(self, email):
		user = User.get_or_none(User.email == email)
		if user:
			raise pw.IntegrityError('Email address has already been taken')
Ejemplo n.º 9
0
	def validate_username(self, username):
		user = User.get_or_none(User.username == username)
		if user:
			raise pw.IntegrityError('Username has already been taken')