Create validating function for passed schema.
@this   Ajv
@param  {Object} schema schema object
@param  {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
@return {Function} validating function
541923
function compile(schema, _meta) {
  var schemaObj = this._addSchema(schema, undefined, _meta);
  return schemaObj.validate || this._compile(schemaObj);
}
358499
function Meta() {
  var self = this;

  var _meta = [];
  Object.defineProperty(self, "_meta", {
    get: function() {
      return _meta;
    },
    set: function(value) {
      if (_.isArray(value)) {
        _meta = value;
      }
    }
  });
}
588679
function (values, schema, options, callback) {
    var newValues = {}
        , errors = []
        , modelList = find(schema)
        , val;

    for (var model in modelList) {
        if (_.isArray(modelList[model])) {

            if (values === undefined) {
                val = undefined;
            }
            else {
                val = values[model];
            }

            // Empty array defined in schema
            if (_.isEmpty(modelList[model])) {
                if (val) {
                    newValues[model] = val;
                }
            }
            else {
                // Set value to empty array if empty given
                if (val == undefined) {
                    if (options && options.partial == true) {
                        // Do nothing
                    }
                    else {
                        newValues[model] = [];
                    }
                }
                else {
                    // Sub model defined in schema
                    for (var thisSubSchema in modelList[model]) {
                        if (_.isArray(val)) {
                            for (var thisValue in val) {

                                // Check if type array or plain array
                                if (typeof val[thisValue] == "object") {
                                    modelCompare(val[thisValue], modelList[model][thisSubSchema], options, function (err, data) {
                                        if (err) {
                                            errors = _.union(errors, err);
                                        }
                                        if (data !== null) {
                                            if (!newValues[model]) {
                                                newValues[model] = [];
                                            }
                                            newValues[model][thisValue] = data;
                                        }
                                    });
                                }
                                else {
                                    rulesMatch(thisValue, val[thisValue], modelList[model][thisSubSchema], options, function (err, data) {
                                        if (err) {
                                            errors.push(err);
                                        }
                                        if (data !== undefined) {
                                            if (!newValues[model]) {
                                                newValues[model] = [];
                                            }
                                            newValues[model][thisValue] = data;
                                        }
                                    });
                                }
                            }
                        }
                        else {
                            modelCompare(val, modelList[model][thisSubSchema], options, function (err, data) {
                                if (err) {
                                    errors = _.union(errors, err);
                                }
                                if (data !== null) {
                                    newValues[model] = data;
                                }
                            });
                        }
                    }
                }
            }
        } else {
            // Check for definition of {} in model to allow any data for this node without validation
            if (_.isEmpty(modelList[model])) {
                for (var index in values) {
                    var filter = new RegExp("^" + model);
                    if (index.match(filter)) {
                        newValues[index] = values[index];
                    }
                }
            }
            else {
                if (values === undefined) {
                    val = undefined;
                }
                else {
                    val = values[model];
                }

                rulesMatch(model, val, modelList[model], options, function (err, data) {
                    if (err) {
                        errors.push(err);
                    }
                    if (data !== undefined) {
                        newValues[model] = data;
                    }
                });
            }
        }
    }

    if (_.isEmpty(errors)) {
        errors = null;
    }
    else {
        errors = {name: 'ValidationError', err: errors};
    }
    if (_.isEmpty(newValues)) {
        newValues = null;
    }
    callback(errors, newValues);
}
469583
function onRequestSchemaValidation(context, req, reply, next) {
  if (context.matchedAction && context._schemaCompiler) {
    const { schema } = context.matchedAction
    const ret = context._schemaCompiler(schema)(req.payload.pattern)
    if (ret) {
      // promise
      if (typeof ret.then === 'function') {
        // avoid to create a seperate promise
        // eslint-disable-next-line promise/catch-or-return
        ret.then(modifiedPattern => {
          if (modifiedPattern) {
            req.payload.pattern = modifiedPattern
          }
          next()
        }, next)
        return
      }
      if (ret.error) {
        return next(ret.error)
      }
      if (ret.value) {
        req.payload.pattern = ret.value
        return next()
      }
    }
  }
  next()
}
1374334
public function create($schema, $meta)
    {
        $up = $this->createSchemaForUpMethod($schema, $meta);
        $down = $this->createSchemaForDownMethod($schema, $meta);

        return compact('up', 'down');
    }
75193
function autoValidate(object) {
  const seq = (object) ? object.seq : undefined;
  const action = (object) ? object.action : undefined;

  const schema = identifySchema(object)

  if (schema) {
    const {error, value} = validate(object, schema);

    if (error) {
      return { isValid: false, seq, action, error };
    } else {
      return { isValid: true, seq, action, value };
    }
  } else {
    return { isValid: false, seq, action,
      error: new Error('No matching schema found.') };
  }
}
1198097
function _generate(schemaName) {
  var schema = generateSchema(schemaName, this._instructions, this._macros, this._opts.strict);
  this.ajv.removeSchema(schema.id);
  return schema;
}
798102
private function createSchemaForUpMethod($schema, $meta)
    {
        //dd($schema);
        $fields = $this->constructSchema($schema);


        if ($meta['action'] == 'create') {
            return $this->insert($fields)->into($this->getCreateSchemaWrapper());
        }

        if ($meta['action'] == 'add') {
            return $this->insert($fields)->into($this->getChangeSchemaWrapper());
        }

        if ($meta['action'] == 'remove') {
            $fields = $this->constructSchema($schema, 'Drop');

            return $this->insert($fields)->into($this->getChangeSchemaWrapper());
        }

        // Otherwise, we have no idea how to proceed.
        throw new GeneratorException;
    }
176761
function generateValidationFn(schema) {
        return function (req) {

            // if already an error, return without doing any additional validation
            if (req.error) { return req; }

            var keys = Object.keys(schema);
            var len = (req.value && req.value.trim().length) || 0;
            var i, key, originalKey;

            for (i = 0; i < keys.length; i++) {
                key = originalKey = keys[i];
                if (key.indexOf('ui-') === 0) {
                    key = key.substring(3);
                }

                // if validation function exists but it returns false then we have error
                if (check[key] && !check[key](schema, req.value)) {
                    var errMsg = schema[key + 'Desc'] || errorMessage[key] || 'Invalid input';
                    req.error = errMsg
                        .replace('{' + key + '}', schema[originalKey])
                        .replace('{value}', req.value)
                        .replace('{length}', len);
                    break;
                }
            }

            return req;
        };
    }
1080462
function (schema) {

    var extendList = find(schema, 'extend');
    for (var extendElem in extendList) {
        if (extendList[extendElem] && extendList[extendElem].extend && _.isFunction(extendList[extendElem].extend)) {
            schema[extendElem] = extendList[extendElem].extend();
        }
    }
    return schema;
}
266951
function validateMetaType(name, metaType) {
        assert(_.isObject(metaType), ERR_METATYPE_OBJECT, { name: name });
        assert(metaType.name, ERR_REQUIRE_FIELD, { metaType: metaType, field: "name" });
        assert(metaType.kind === "enum" || metaType.kind === "class", ERR_METATYPE_KIND, { metaType: metaType });

        // Enum MetaType
        if (metaType.kind === "enum") {
            var lits = metaType.literals;
            assert(Array.isArray(lits) && lits.length > 0, ERR_ENUM_HAS_LITERALS, { metaType: metaType });

            // Check duplicated literal
            _.each(lits, function (lit1) {
                var len = _.filter(lits, function (lit2) { return lit2 === lit1; }).length;
                assert(len === 1, ERR_DUPLICATED_LITERAL, { metaType: metaType, literal: lit1 });
            });
        }

        // Class MetaType
        if (metaType.kind === "class") {

            // Check .super
            if (metaType.super) {
                assert(metaType.super && _global.meta[metaType.super], ERR_TYPE_NOT_FOUND, { metaType: metaType, type: metaType.super, field: "super" });
            }

            // Check Attributes
            if (metaType.attributes) {
                assert(Array.isArray(metaType.attributes), ERR_FIELD_TYPE, { metaType: metaType, field: "attributes", type: "Array" });
                _.each(metaType.attributes, function (attribute) {

                    // check 'name'
                    assert(attribute.name, ERR_UNNAMED_ATTRIBUTE, { metaType: metaType });

                    // Check 'kind'
                    assert(_.contains(["prim", "enum", "var", "ref", "refs", "obj", "objs", "custom"], attribute.kind), ERR_ATTRIBUTE_KIND, { metaType: metaType, attribute: attribute });

                    // Check 'type'
                    if (attribute.kind === "prim") {
                        assert(_.contains(["Integer", "String", "Boolean", "Real"], attribute.type), ERR_ATTRIBUTE_PRIM_TYPE, { metaType: metaType, attribute: attribute });
                    } else if (attribute.kind !== "custom") {
                        assert(_global.meta[attribute.type], ERR_TYPE_NOT_FOUND, { metaType: metaType, type: attribute.type, field: attribute.name + ".type" });
                    }

                    // Check duplicated attribute in all inherited attributes
                    var len = _.filter(getMetaAttributes(metaType.name), function (attr) { return attr.name === attribute.name; }).length;
                    assert(len === 1, ERR_DUPLICATED_ATTRIBUTE, { metaType: metaType, attribute: attribute });
                });
            }
        }
    }
1284561
function schema (args) {
    // get args object
    args = requireValidOptionalObject(args)
    // get colunmn and index information from database
    return Promise.all([
        this.mysql().query(sql.describe(this)),
        this.mysql().query(sql.showCreateTable(this)),
        this.mysql().query(sql.showIndexes(this)),
    ])
    // build schema from database response
    .then(res => {
        // get columns and indexes from describe and show index queries
        var columns = res[0][0]
        var createTable = res[1][0]
        var indexes = res[2][0]
        // schema data
        var schema = {
            columns: {},
            indexes: [],
        }
        // get first and only create table record
        createTable = _.get(createTable, "[0]['Create Table']", '')
        // get engine and charset from create table sql
        var engine = createTable.match(/ENGINE=(\w+)/)
        schema.engine = engine && engine[1] || ''
        var charset = createTable.match(/DEFAULT CHARSET=(\w+)/)
        schema.charset = charset && charset[1] || ''
        // build column data
        _.each(columns, dbColumn => {
            var column = schema.columns[dbColumn.Field] = {}
            // check unsigned
            if (dbColumn.Type.match(/unsigned$/)) {
                column.unsigned = true
                dbColumn.Type = dbColumn.Type.replace(/ unsigned/, '')
            }
            // char id column
            if (dbColumn.Type === 'char(32)') {
                // model must not be set for binary ids
                assert.ok(this.binaryIds === false, 'binaryIds must be disabled for char id columns')
                // set type
                column.type = 'id'
            }
            // binary id column
            else if (dbColumn.Type === 'binary(16)') {
                // model must be set for binary ids
                assert.ok(this.binaryIds === true, 'binaryIds must be enabled for binary id columns')
                // set type
                column.type = 'id'
            }
            // all other column types
            else  {
                // require valid type
                assert.ok(sql.columnTypesInverse[dbColumn.Type], 'unrecognized column type '+dbColumn.Type)
                // map database to internal type
                column.type = sql.columnTypesInverse[dbColumn.Type]
            }
            // is column nullable
            if (dbColumn.Null === 'NO') {
                column.null = false
            }
            // set default if not null
            if (dbColumn.Default) {
                column.default = dbColumn.Default
                // convert boolean
                if (column.type === 'boolean') {
                    column.default = column.default === '1' ? true : false
                }
            }
        })
        // map of indexes by key name since keys may cover multiple columns
        var indexesByKey = {}
        // build map of indexes by key name
        _.each(indexes, dbIndex => {
            // create entry for index if it does not already exist
            if (!indexesByKey[dbIndex.Key_name]) {
                indexesByKey[dbIndex.Key_name] = {
                    columns: {}
                }
            }
            // get entry for index
            var index = indexesByKey[dbIndex.Key_name]
            // add column with sequence in index
            index.columns[dbIndex.Column_name] = parseInt(dbIndex.Seq_in_index)
            // add unique flag if true
            if (dbIndex.Non_unique === '0') {
                index.unique = true
            }
        })
        // add indexes to schema
        _.each(indexesByKey, (index, name) => {
            var indexColumns = _.keys(index.columns)
            // multi-column index
            if (indexColumns.length > 1) {
                // sort index columns by the Seq_in_index value - these may
                // always be in order so this may not be needed
                indexColumns = _.sortBy(indexColumns, indexColumn => index.columns[indexColumn])
                // create schema index entry
                var schemaIndex = {
                    columns: indexColumns,
                }
                // set unique flag
                if (index.unique) {
                    schemaIndex.unique = true
                }
                // add index to schema
                schema.indexes.push(schemaIndex)
            }
            // single column index
            else {
                // get first and only column
                var indexColumn = indexColumns[0]
                // PRIMARY KEY
                if (name === 'PRIMARY') {
                    schema.columns[indexColumn].primary = true
                }
                // unique index
                else if (index.unique) {
                    schema.columns[indexColumn].unique = true
                }
                // non-unique index
                else {
                    schema.columns[indexColumn].index = true
                }
            }
        })
        // resolve with schema
        return schema
    })
    .catch(err => {
        // reject on anything besides a table does not exist error
        // if table does not exist resolve with undefined
        if (err.errno !== 1146) {
            throw err
        }
    })
}
361570
function generateSchemas() {
  // this.ajv.addMetaSchema(_generate.call(this, 'evaluate_metaschema'));
  this._validate = this.ajv.compile(_generate.call(this, 'schema'));
  this._expandMacros = this.ajv.compile(_generate.call(this, 'expand_macros'));
  this._evaluate = this.ajv.compile(_generate.call(this, 'evaluate'));
  // console.log(this._validate.toString().length, this._evaluate.toString().length);
}
737705
function validateObject(node, schema, key) {
    if (typeof node == "object") {
      try {
        validateModel(node, schema[SCHEMADATA]);
      } catch (e) {
        throw new ValidationException(e.message + " at " + key + ".");
      }
    } else {
      throw new ValidationException("Expected object for " + key);
    }
  }
348762
function() {
    let schemas = utils.parseArg(arguments);
    schemas.forEach(function(schema) {
      utils.assert(schema.isOvt, `${utils.obj2Str(schema)} is not a valid ovt schema`);
    });
  }
1106652
function validate(doc, schema, prefix, options) {
  schema.validate(doc, prefix, options);
}
75495
def validate(document, schema, log_qualifier = True):
    
    if isinstance(schema, ValidatorNode):
        if not validate(document, schema.content):
            return False
        if not schema.validator(document, schema.content):
            if log_qualifier:
                LOG.error("%r failed to validate with qualifier %s", document, schema.validator.__name__)
            return False
        return True
    elif isinstance(schema, dict):
        if not isinstance(document, dict):
            LOG.error("wanted a dictionary, got a %s", document.__class__.__name__)
            return False
        generic = []
        optional = {}
        optionalnull = {}
        mandatory = []
        for key, schema_val in schema.iteritems():
            if isinstance(key, ValidatorNode):
                if key.mode == 'mandatory':
                    mandatory.append((key, schema_val))
                else:
                    generic.append((key, schema_val))
            elif isinstance(schema_val, Optional):
                optional[key] = schema_val
            elif isinstance(schema_val, OptionalNull):
                optional[key] = schema_val
                optionalnull[key] = True
            else:
                mandatory.append((key, schema_val))

        doc_copy = document.copy()

        for key, schema_val in mandatory:
            if isinstance(key, ValidatorNode):
                nb = 0
                rm = []
                for doc_key, doc_val in doc_copy.iteritems():
                    if not validate(doc_key, key, False):
                        continue

                    nb += 1

                    if validate(doc_val, schema_val):
                        rm.append(doc_key)
                    else:
                        return False

                if nb == 0:
                    LOG.error("missing document %r for qualifier: %r", key.content, key.validator.__name__)
                    return False
                elif key.min is not None and nb < key.min:
                    LOG.error("no enough document %r for qualifier: %r (min: %r, found: %r)", key.content, key.validator.__name__, key.min, nb)
                    return False
                elif key.max is not None and nb > key.max:
                    LOG.error("too many document %r for qualifier: %r (max: %r, found: %r)", key.content, key.validator.__name__, key.max, nb)
                    return False
                else:
                    for x in rm:
                        del doc_copy[x]
                    continue

            doc_val = doc_copy.get(key, Nothing)
            if doc_val is Nothing:
                LOG.error("missing key %r in document", key)
                return False

            if helpers.is_scalar(schema_val):
                if not validate(doc_val, schema_val):
                    return False
                del doc_copy[key]
                continue

            if schema_val.modifier:
                for modname in schema_val.modifier:
                    if modname in _modifiers:
                        document[key] = _modifiers[modname](document[key])
                        doc_val = _modifiers[modname](doc_val)
                    elif hasattr(doc_val, modname):
                        document[key] = getattr(document[key], modname)()
                        doc_val = getattr(doc_val, modname)()

            if _valid_len(key, doc_val, schema_val.min_len, schema_val.max_len) is False:
                return False
            if not validate(doc_val, schema_val.content):
                return False
            del doc_copy[key]

        for key, schema_val in generic:
            nb = 0
            rm = []

            for doc_key, doc_val in doc_copy.iteritems():
                if not validate(doc_key, key, False):
                    continue

                nb += 1

                if validate(doc_val, schema_val):
                    rm.append(doc_key)
                else:
                    return False

            if key.min is not None and nb < key.min:
                LOG.error("no enough document %r for qualifier: %r (min: %r, found: %r)", key.content, key.validator.__name__, key.min, nb)
                return False
            elif key.max is not None and nb > key.max:
                LOG.error("too many document %r for qualifier: %r (max: %r, found: %r)", key.content, key.validator.__name__, key.max, nb)
                return False
            else:
                for x in rm:
                    del doc_copy[x]
                continue

        for key, doc_val in doc_copy.iteritems():
            schema_val = optional.get(key, Nothing)
            if schema_val is Nothing:
                LOG.error("forbidden key %s in document", key)
                return False
            elif optionalnull.has_key(key) and doc_val is None:
                continue
            elif schema_val.min_len == 0 and doc_val is "":
                continue

            if schema_val.modifier:
                for modname in schema_val.modifier:
                    if modname in _modifiers:
                        document[key] = _modifiers[modname](document[key])
                        doc_val = _modifiers[modname](doc_val)
                    elif hasattr(doc_val, modname):
                        document[key] = getattr(document[key], modname)()
                        doc_val = getattr(doc_val, modname)()
                if optionalnull.has_key(key) and doc_val is None:
                    continue
                elif schema_val.min_len == 0 and doc_val is "":
                    continue

            if _valid_len(key, doc_val, schema_val.min_len, schema_val.max_len) is False:
                return False
            if not validate(doc_val, schema_val.content):
                return False
        return True
    elif isinstance(schema, list):
        if not isinstance(document, list):
            LOG.error("wanted a list, got a %s", document.__class__.__name__)
        for elt in document:
            # XXX: give a meaning when there are multiple element in a sequence of a schema?
            if len(schema) < 2:
                if not validate(elt, schema[0]):
                    return False
            elif isinstance(schema[0], dict):
                tmp = {}
                for x in schema:
                    for key, val in x.iteritems():
                        tmp[key] = val
                if not validate(elt, tmp):
                    return False
            else:
                if not validate(elt, schema[0]):
                    return False
        return True
    elif isinstance(schema, Any):
        return True
    elif isinstance(schema, Scalar):
        return helpers.is_scalar(document)
    else: # scalar
        if isinstance(schema, str):
            schema = unicode(schema)
        if isinstance(document, str):
            document = unicode(document, 'utf8')
        if schema.__class__ != document.__class__:
            LOG.error("wanted a %s, got a %s", schema.__class__.__name__, document.__class__.__name__)
            return False
        return True