<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def ensureExists(cls, values, defaults=None, **context):
 """ Defines a new record for the given class based on the inputted set of keywords. If a record already exists for the query, the first found record is returned, otherwise a new record is created and returned. :param values | <dict> """

        # require at least some arguments to be set
        if not values:
            return cls()

        # lookup the record from the database
        q = orb.Query()

        for key, value in values.items():
            column = cls.schema().column(key)
            if not column:
                raise orb.errors.ColumnNotFound(schema=cls.schema(), column=key)
            elif column.testFlag(column.Flags.Virtual):
                continue

            if (isinstance(column, orb.AbstractStringColumn) and
                not column.testFlag(column.Flags.CaseSensitive) and
                not column.testFlag(column.Flags.I18n) and
                isinstance(value, (str, unicode))):
                q &= orb.Query(key).lower() == value.lower()
            else:
                q &= orb.Query(key) == value

        record = cls.select(where=q).first()
        if record is None:
            record = cls(context=orb.Context(**context))
            record.update(values)
            record.update(defaults or {})
            record.save()

        return record