we are going to need to walk the query tree to validate it before executing it
185350
@SuppressWarnings("unchecked")
    private static void validateSelector(Map<String, Object> selector) throws QueryException {
        String topLevelOp = (String) selector.keySet().toArray()[0];

        // top level op can only be $and or $or after normalisation
        if (topLevelOp.equals(AND) || topLevelOp.equals(OR)) {
            Object topLevelArg = selector.get(topLevelOp);
            if (topLevelArg instanceof List) {
                // safe we know its a List
                validateCompoundOperatorClauses((List<Object>) topLevelArg,
                                                       new Boolean[]{ false });
            }
        }
    }
39113
def _validate_select_where(self):
        
        # check that there's either a =, a IN or a CONTAINS (collection)
        # relationship with a primary key or indexed field. We also allow
        # custom indexes to be queried with any operator (a difference
        # between a secondary index)
        equal_ops = [self.model._get_column_by_db_name(w.field) \
                     for w in self._where if not isinstance(w.value, Token)
                     and (isinstance(w.operator, EqualsOperator)
                          or self.model._get_column_by_db_name(w.field).custom_index)]
        token_comparison = any([w for w in self._where if isinstance(w.value, Token)])
        if not any(w.primary_key or w.has_index for w in equal_ops) and not token_comparison and not self._allow_filtering:
            raise QueryException(
                ('Where clauses require either  =, a IN or a CONTAINS '
                 '(collection) comparison with either a primary key or '
                 'indexed field. You might want to consider setting '
                 'custom_index on fields that you manage index outside '
                 'cqlengine.'))

        if not self._allow_filtering:
            # if the query is not on an indexed field
            if not any(w.has_index for w in equal_ops):
                if not any([w.partition_key for w in equal_ops]) and not token_comparison:
                    raise QueryException(
                        ('Filtering on a clustering key without a partition '
                         'key is not allowed unless allow_filtering() is '
                         'called on the queryset. You might want to consider '
                         'setting custom_index on fields that you manage '
                         'index outside cqlengine.'))
230193
function validateProp(key, value) {
  const type = typeof value;

  switch (key) {
  case 'orderByKey':
  case 'orderByPriority':
  case 'orderByValue':
    if (!value) {
      throw new Error(`"query.${key}" should not be set to false. Set it off by setting an other order.`);
    }
    break;

  case 'orderByChild':
    if (value == null) {
      throw new Error('"query.orderByChild" should not be set to null. Set it off by setting an other order.');
    }
    if (type !== 'string') {
      throw new Error('"query.orderByChild" should be a string or null.');
    }
    break;

  case 'startAt':
  case 'endAt':
  case 'equalTo':
    if (
      value !== null &&
      type !== 'string' &&
      type !== 'number' &&
      type !== 'boolean'
    ) {
      throw new Error(`query.${key} should be a string, a number, a boolean or null.`);
    }
    break;

  case 'limitToFirst':
  case 'limitToLast':
    if (value != null && type !== 'number') {
      throw new Error(`query.${key} should be a number or null.`);
    }
    break;

  default:
    throw new Error(`"${key}" is not a query parameter.`);
  }
}
145872
private void validate(QPath path) throws RepositoryException, AccessDeniedException, ReferentialIntegrityException
   {

      List<ItemState> changes = changesLog.getAllStates();
      for (ItemState itemState : changes)
      {

         if (itemState.isInternallyCreated())
         {
            // skip internally created
            if (itemState.isMixinChanged())
            {
               // ...except of check of ACL correct size for internally created
               // items.
               // If no permissions in the list throw exception.
               if (itemState.isDescendantOf(path))
               {
                  if (((NodeData)itemState.getData()).getACL().getPermissionsSize() < 1)
                  {
                     throw new RepositoryException("Node " + itemState.getData().getQPath().getAsString()
                        + " has wrong formed ACL.");
                  }
               }
               validateMandatoryItem(itemState);
            }
         }
         else
         {
            if (itemState.isDescendantOf(path))
            {
               validateAccessPermissions(itemState);
               validateMandatoryItem(itemState);
            }

            if (path.isDescendantOf(itemState.getAncestorToSave()))
            {
               throw new ConstraintViolationException(path.getAsString()
                  + " is the same or descendant of either Session.move()'s destination or source node only "
                  + path.getAsString());
            }
         }
      }
   }
525254
def validate(self):
        """"""
        if not isinstance(self.location, Location):
            raise TypeError(u'Expected Location location, got: {} {}'.format(
                type(self.location).__name__, self.location))

        if not self.location.field:
            raise ValueError(u'Expected Location object that points to a field, got: '
                             u'{}'.format(self.location))

        if not is_graphql_type(self.field_type):
            raise ValueError(u'Invalid value of "field_type": {}'.format(self.field_type))

        stripped_field_type = strip_non_null_from_type(self.field_type)
        if isinstance(stripped_field_type, GraphQLList):
            inner_type = strip_non_null_from_type(stripped_field_type.of_type)
            if GraphQLDate.is_same_type(inner_type) or GraphQLDateTime.is_same_type(inner_type):
                # This is a compilation error rather than a ValueError as
                # it can be caused by an invalid GraphQL query on an otherwise valid schema.
                # In other words, it's an error in writing the GraphQL query, rather than
                # a programming error within the library.
                raise GraphQLCompilationError(
                    u'Lists of Date or DateTime cannot currently be represented as '
                    u'OutputContextField objects: {}'.format(self.field_type))
562535
protected function before_validate() {
        $this->beforeupdate = null;

        // During update.
        if ($this->get('id')) {
            $this->beforeupdate = new self($this->get('id'));
        }
    }
799480
@Override
    public void validateTerms(Set<ValueIndexTerm> queryTerms) throws IllegalArgumentException {
        checkNotNullAndNotEmpty(queryTerms);

        checkInvalidAndRequiredTerms(queryTerms,
                                     NAME,
                                     new String[]{
                                             ResourceType.JAVA.toString(),
                                             null, null // not required
                                     },
                                     (t) -> (t.getTerm().equals(ResourceType.JAVA.toString())),
                                     (t) -> (t instanceof ValueModuleNameIndexTerm),
                                     (t) -> (t instanceof ValueBranchNameIndexTerm)
        );
    }
1252458
private void validateEntities(JsonNode data) throws InvalidInputException {
    for (JsonNode node : data.findParents(INDEX_START)) {

      for (String key : new String[] {INDEX_START, INDEX_END, ID, TYPE}) {
        if (node.path(key).isMissingNode()) {
          throw new InvalidInputException("Required field \"" + key + "\" missing from the entity payload");
        }
      }

      int startIndex = node.get(INDEX_START).intValue();
      int endIndex = node.get(INDEX_END).intValue();

      if (endIndex <= startIndex) {
        throw new InvalidInputException(String.format("Invalid entity payload: %s (start index: %s, end index: %s)",
            node.get(ID).textValue(), startIndex, endIndex));
      }

    }
  }
426657
def validate_query_structure(query):
    
    query_dict = dict(query)
    filters = query_dict.pop('_filters', None)
    if filters:
        try:
            f = json.loads(filters)
        except ValueError:
            msg = '_filters field can not be serialized'
            raise JsonValidaitonError(msg)
        else:
            query_dict['_filters'] = f
    try:
        q = ListQuery(query_dict)
    except t.DataError as exc:
        msg = '_filters query invalid'
        raise JsonValidaitonError(msg, **as_dict(exc))

    return q
1160199
protected void performInvalidation() {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[PERFORM_INVALIDATION]);
        }

        long now = System.currentTimeMillis();
        PreparedStatement ps1 = null;
        ResultSet rs1 = null;
        PreparedStatement ps2 = null;

        boolean ps1Closed = false;
        boolean ps2Closed = false;

        Connection nukerCon = null;

        // do some initializations
        String appName = getIStore().getId(); //bhSessionContext.getAppName();

        boolean doInvals = false;
        boolean doDatabaseInval = doScheduledInvalidation();
        nukerCon = getConnection(false);

        if (nukerCon == null) {
            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
                LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[PERFORM_INVALIDATION], "Connection is null");
            }
            return;
        }

        try {

            // handle last acc times for manual update irregardless
            // of whether this thread will scan for time outs
            if (!_smc.getEnableEOSWrite()) {
                writeCachedLastAccessedTimes(nukerCon);
            }

            //check the value of doDatabaseInval
            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE,methodClassName, methodNames[PERFORM_INVALIDATION], "doDatabaseInval="+doDatabaseInval);
            }

            if (doDatabaseInval) {
                ps1 = nukerCon.prepareStatement(readLastAccess);
                ps1.setString(1, appName);
                ps1.setString(2, appName);
                ps1.setString(3, appName);
                rs1 = ps1.executeQuery();

                boolean rowExists = false;
                long lastTime = 0L;
                if (rs1.next()) {
                    rowExists = true;
                    lastTime = rs1.getLong(1);
                }
                rs1.close();
                ps1.close();
                ps1Closed = true;

                //check the value of rowExists
                if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE,methodClassName, methodNames[PERFORM_INVALIDATION], "rowExists="+rowExists);
                }

                if (rowExists) {
                    long lastCheck = now - _smc.getInvalidationCheckInterval() * 1000;

                    //check the value of lastCheck,lastTime,now
                    if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE,methodClassName, methodNames[PERFORM_INVALIDATION], "lastCheck="+lastCheck+",lastTime="+lastTime+",now="+now);
                    }

                    //if no other server tried to process invalidation within the interval, this will be true
                    //similar to updateNukerTimeStamp, but we have an extra check here to test the last access time hasn't changed
                    //PK30585 - added future time check
                    if ((lastCheck >= lastTime) || (lastTime > now)) {
                        ps2 = nukerCon.prepareStatement(optUpdate);
                        setPSLong(ps2, 1, now);
                        ps2.setString(2, appName);
                        ps2.setString(3, appName);
                        ps2.setString(4, appName);
                        setPSLong(ps2, 5, lastTime);
                        int res = ps2.executeUpdate();
                        if (res > 0)
                            doInvals = true;
                    }
                } else {
                    //If we are here means, this is the first time this web module is
                    //trying to invalidation of sessions
                    ps2 = nukerCon.prepareStatement(insForInval);
                    ps2.setString(1, appName);
                    ps2.setString(2, appName);
                    ps2.setString(3, appName);
                    setPSLong(ps2, 4, now);
                    ps2.setInt(5, -1);
                    try {
                        ps2.executeUpdate();
                        doInvals = true;
                    } catch (SQLException sqle) {
                        //                        if (isDuplicateKeyException(sqle)) {
                        //                            // ignore duplicate key errror here - can only happen in very small timing window but causes no harm
                        //                            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                        //                                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[PERFORM_INVALIDATION], "Duplicate key inserted");
                        //                            }
                        //                        } else {
                        throw sqle; // to be re-caught and logged below
                        //                        }
                    }
                }

                if (ps2 != null)
                    ps2.close();
                ps2Closed = true;

                //check the value of doInvals
                if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE,methodClassName, methodNames[PERFORM_INVALIDATION], "doInvals="+doInvals);
                }

                if (doInvals) {

                    //Process the non-listener sessions first
                    doInvalidations(nukerCon);

                    //Read in all the sessions with listeners that need to be invalidated
                    Enumeration e = pollForInvalidSessionsWithListeners(nukerCon);
                    processInvalidListeners(e, nukerCon);

                }

            }

        } catch (Throwable t) {
            com.ibm.ws.ffdc.FFDCFilter.processException(t, "com.ibm.ws.session.store.db.DatabaseHashMap.performInvalidation", "2537", this);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[PERFORM_INVALIDATION], "DatabaseHashMap.performInvalidationError");
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[PERFORM_INVALIDATION], "CommonMessage.exception", t);
        } finally {
            if (!ps1Closed && rs1 != null)
                closeResultSet(rs1);
            if (!ps1Closed && ps1 != null)
                closeStatement(ps1);
            if (!ps2Closed && ps2 != null)
                closeStatement(ps2);
            closeConnection(nukerCon);
        }
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
            LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[PERFORM_INVALIDATION]);
        }
    }
646497
protected void performValidation(String path, Object value, List<ValidationResult> results) {
		String name = path != null ? path : "value";

		if (value == null) {
			// Check for required values
			if (_required)
				results.add(new ValidationResult(path, ValidationResultType.Error, "VALUE_IS_NULL",
						name + " cannot be null", "NOT NULL", null));
		} else {
			value = ObjectReader.getValue(value);

			// Check validation rules
			if (_rules != null) {
				for (IValidationRule rule : _rules)
					rule.validate(path, this, value, results);
			}
		}
	}
1082100
private void validateIfRequiredByParent(JDBCStorageConnection conn, ResultSet resultSet) throws RepositoryException,
      SQLException, IllegalNameException
   {
      String parentId = getIdentifier(resultSet, DBConstants.COLUMN_PARENTID);
      InternalQName nodeName = InternalQName.parse(resultSet.getString(DBConstants.COLUMN_NAME));

      NodeData parent = null;
      try
      {
         parent = (NodeData)conn.getItemData(parentId);
      }
      catch (PrimaryTypeNotFoundException e)
      {
         // It is possible, parent also without primaryType property
         return;
      }

      // parent already removed in previous check
      if (parent == null)
      {
         return;
      }

      NodeDefinitionData def =
         nodeTypeManager.getChildNodeDefinition(nodeName, parent.getPrimaryTypeName(), parent.getMixinTypeNames());

      if (!def.isResidualSet())
      {
         throw new SQLException("Node is required by its parent.");
      }
   }
618424
private void validateQuerySql(SQLiteDatabase db, String sql,
                                  CancellationSignal cancellationSignal) {
        db.getThreadSession().prepare(sql,
                db.getThreadDefaultConnectionFlags(true /*readOnly*/), cancellationSignal, null);
    }
1118061
public final void validate() {
    this.accept(new TreeVisitor() {
      @Override
      public boolean preVisit(TreeNode node) {
        node.validateInner();
        return true;
      }
    });
  }
709650
function isValidQuery(definition) {
  var requiredKeys = [
    'event_name',
    'resource_type',
    'tracker_id'
  ];

  return _.all(requiredKeys, function(key) {
    return _.has(definition, key);
  });
}
1198515
public void validate(String path, Schema schema, Object value, List<ValidationResult> results) {
		String name = path != null ? path : "value";
		Object value1 = ObjectReader.getProperty(value, _property1);
		Object value2 = ObjectReader.getProperty(value, _property2);

		if (!ObjectComparator.compare(value1, _operation, value2)) {
			results.add(new ValidationResult(path, ValidationResultType.Error, "PROPERTIES_NOT_MATCH",
					name + " must have " + _property1 + " " + _operation + " " + _property2, value2, value1));
		}
	}
197755
@Override
    public void isValid() throws Exception {
        if (numStmnts() >= 2) {
            if (primaryJoinableHooks.size() > 0) {
                for (String joinField:primaryJoinableHooks) {
                    if (joinField.equals("timestamp")) {// timestamp is implicitly present in the result.
                        continue;
                    }
                    for (QueryMeta query: getAllStmnts()) {
                        boolean isPresent = false;
                        if (query instanceof BaseAggQueryMeta) {// Since BaseAggQueryMeta is also a PlainDimQueryMeta we go with former first.
                            for (AggItem item:((BaseAggQueryMeta)query).aggregations) {
                                if (joinField.equals(item.fieldName) || (item.asName != null && joinField.equals(item.asName))) {
                                    isPresent = true;
                                }
                            }
                        }
                        if (query instanceof PlainDimQueryMeta) {
                            Map<String, String> dims = ((PlainDimQueryMeta)query).fetchDimensions;
                            for (Map.Entry<String, String> entry :dims.entrySet()) {
                                if (joinField.equals(entry.getKey()) || (entry.getValue() != null && joinField.equals(entry.getValue()))) {
                                    isPresent = true;
                                }
                            }
                        }
                        if (!isPresent) {
                            String error = joinField + " mentioned in the composite key should appear in all the data sources being queried and joined.";
                            throw new Exception(error);
                        }
                    }
                }
            } else {
                String error = "Need atleast one field to join on";
                throw new Exception(error);
            }
        }
    }