|
|
@@ -0,0 +1,39 @@
|
|
|
+from tinydb import Query
|
|
|
+from cerberus import Validator
|
|
|
+
|
|
|
+
|
|
|
+class DbValidator(Validator):
|
|
|
+ def __init__(self, db, **kwargs):
|
|
|
+ super().__init__(**kwargs)
|
|
|
+ self.db = db
|
|
|
+
|
|
|
+ def _validate_is_fk(self, table_name, field, value):
|
|
|
+ """ {'type': 'string'} """
|
|
|
+ table = self.db.table(table_name)
|
|
|
+ if not table.get(doc_id=value):
|
|
|
+ self._error(field, "No value found in {}".format(table_name))
|
|
|
+
|
|
|
+ def _validate_is_unique(self, table_name, field, value):
|
|
|
+ """{'type': 'string'} """
|
|
|
+ Q = Query()
|
|
|
+ table = self.db.table(table_name)
|
|
|
+ if table.search(Q[field] == value):
|
|
|
+ self._error(field, "Value '{}' is already present in the database".format(value))
|
|
|
+
|
|
|
+ def _validate_is_unique_with(self, defs, field, value):
|
|
|
+ """ {'type': ('dict'),
|
|
|
+ 'validator': 'dependencies'} """
|
|
|
+ def get_value(f):
|
|
|
+ return self._lookup_field(f)[1]
|
|
|
+
|
|
|
+ def make_query(*fields):
|
|
|
+ Q = Query()
|
|
|
+ for f in fields:
|
|
|
+ Q_temp = Query()
|
|
|
+ Q = Q & (Q_temp[f] == get_value(f))
|
|
|
+ return Q
|
|
|
+
|
|
|
+ table = self.db.table(defs['table'])
|
|
|
+ all_fields = field, *defs['fields']
|
|
|
+ if table.search(make_query(*all_fields)):
|
|
|
+ self._error(field, "Value '{}' is already present in the database".format(value))
|