@function validateDeleted

if delete/unDelete tables exist set correct value for d column

@param {object} args

@returns {Promise}
513697
async function validateDeleted (args) {
    try {
        var deletedTable = await this.mysql().query(
            sql.showCreateTable({name: `${this.name}Delete`}), {}, {}, args.session
        )
    }
    // exception will be thrown if table does not exist
    catch (err) {
        return
    }
    // get deleted records
    const [ results ] = await this.mysql().query(sql.selectDeleted(this))
    debug(`checking ${results.length} deleted records`)
    // check each record and delete if needed
    for (const result of results) {
        // load current record
        var record = await this.query({
            allow: true,
            cache: false,
            current: true,
            one: true,
            session: args.session,
            where: { id: result.id }
        })
        // skip if record not found
        if (!defined(record)) {
            continue
        }
        // skip if id does not match
        if (record.id !== result.id) {
            continue
        }
        // skip if record already deleted
        if (record.isDeleted) {
            continue
        }
        debug(`deleting ${record.id}`)
        // delete record
        await record.delete({allow: true, cache: false})
    }
}
507796
async function alterTable (args) {
    // get args object
    args = requireValidOptionalObject(args)
    // get existing schema
    var schema = requireValidSchema(args.schema)
    // modify existing columns
    await Promise.each(this.columnNames, async name => {
        // skip unless column exists
        if (!schema.columns[name]) {
            return
        }
        // attempt to alter existing column if model does not match schema
        await this.alterColumn({
            column: name,
            schema: schema,
            session: args.session,
        })
    })
    // create new columns
    await Promise.each(this.columnNames, async name => {
        // skip if column exists
        if (schema.columns[name]) {
            return
        }
        // get spec
        var spec = this.columns[name]
        // attempt to add column to table
        await this.createColumn({
            column: {
                name: name,
                spec: spec,
            },
            session: args.session,
        })
    })
}
866341
function init (args) {
    // get values from args
    this.model = args.model
    this.promise = args.promise
    this.raw = args.raw
    this.session = args.session
    // list of instance properties
    this.properties = []
    // add default properties to instance
    _.each(this.model.defaultColumns, (defaultName, columnName) => {
        // skip row (n)um column
        if (columnName === 'c' || columnName === 'n') {
            return
        }
        // use d column to set deleted flag
        if (columnName === 'd') {
            this.isDeleted = this.raw[columnName] === 1 ? true : false
        }
        // and column to instance
        else {
            // add property using default name (e.g. id, createTime) to object
            this[defaultName] = this.raw[columnName]
            // add to properties
            this.properties.push(defaultName)
        }
    })
    // if model has data then make sure extra columns are set in data
    if (defined(this.model.columnName('data'))) {
        // check that extra properties defined in data
        _.each(this.model.extraColumns, (spec, columnName) => {
            // if extra property is in column but not data then set in data
            if (defined(this.raw[columnName]) && !defined(_.get(this.data, spec.path))) {
                // convert boolean
                if (spec.type === 'boolean') {
                    _.set(this.data, spec.path, this.raw[columnName] === 1 ? true : false)
                }
                // convert int
                else if (spec.type === 'int' || spec.type === 'smallint') {
                    var val = parseInt(this.raw[columnName])
                    // set value only if valid integer
                    if (!Number.isNaN(val)) {
                        _.set(this.data, spec.path, val)
                    }
                }
                // set all other values directly
                else {
                    _.set(this.data, spec.path, this.raw[columnName])
                }
            }
        })
    }
    // if model does not have data then any extra columns go on instance
    else {
        // add extra properties to instance
        _.each(this.model.extraColumns, (spec, columnName) => {
            this[columnName] = this.raw[columnName]
            // add to properties
            this.properties.push(columnName)
        })
    }
    // list of states record is in for checking access
    var states = []
    // add deleted to states if set
    if (this.isDeleted) {
        states.push('deleted')
    }
    // if there are reladed records loaded copy them to instance
    if (this.raw._related) {
        this.related = this.raw._related
        delete this.raw._related
    }
    // if child id was selected use to determin if record is current
    if (this.raw.hasOwnProperty('childId')) {
        // if record has child it is not current
        this.isCurrent = defined(this.raw.childId) ? false : true
        // add isCurrent to properties
        this.properties.push('isCurrent')
    }
    // default scope for access control
    this.scope = 'any'
    // id that grants ownership access to record
    this.accessId = undefined
    // set access id for raw if defined
    if (defined(this.raw[this.model.accessIdName])) {
        this.accessId = this.raw[this.model.accessIdName]
    }
    // otherwise set from data - may be undefined
    else if (defined(this.data) && defined(this.data[this.model.accessIdName])) {
        this.accessId = this.data[this.model.accessIdName]
    }
    // if session has accessId set and it is used for model then use it
    if (defined(this.session.accessId) && this.session.accessIdName === this.model.accessIdName) {
        // if access id is in data and matches session then change scope to own
        if (this.session.accessId = this.accessId) {
            this.scope = 'own'
        }
    }
    // otherwise try account id
    else if (defined(this.session.accountId) && this.model.defaultColumnsInverse.accountId) {
        // if account id matches session then change scope to own
        if (this.session.accountId === this.accountId) {
            this.scope = 'own'
        }
    }
    // check access unless allow override set - only check access on primary model
    // records and not on action records
    if (!args.allow && !this.model.isAction) {
        // get global access control instance
        var accessControl = ImmutableAccessControl.getGlobal()
        // build args for access check - default to any scope
        var allowArgs = {
            action: 'read',
            model: this.model.name,
            scope: this.scope,
            session: this.session,
            states: states,
        }
        // check access
        var allow = accessControl.allowModel(allowArgs)
        // throw access denied error if not allowed
        if (!allow) {
            httpError(403, null, accessControl.audit)
        }
    }
}
1206761
async function validateData (args) {
    debug('validate '+this.name)
    // query all records and iterate over response
    var res = await this.query({
        // skip access control checks
        allow: true,
        // do not cache
        cache: false,
        // make sure session is object
        session: args.session,
    })
    // get response
    debug('checking '+res.length+' records')
    // iterate over records waiting for promise to be resolved
    await res.each(async (rec, num) => {
        // set to true if column needs to be updated
        var needsUpdate = false
        // check if any columns do not match
        _.each(this.extraColumns, (spec, name) => {
            // skip if no data
            if (!rec.data) {
                return
            }
            // if already updating or column value does not match data
            // value then set the update flag to true
            if (needsUpdate || rec.raw[name] !== rec.data[spec.path]) {
                needsUpdate = true
            }
        })
        // go to next record if update not needed
        if (!needsUpdate) {
            return
        }
        // debug
        debug('updating record num '+num)
        // get update sql
        var update = sql.updateExtraColumns(this, rec)
        // do update
        await this.mysql().query(update.sql, update.params, {}, args.session)
        // increment update count
        this.updated++
    })
    // validate complete
    this.validated = true
}
147607
def delete(sql_params = "", *bindvars)
      delete_sql = "DELETE FROM \"#{@schema_name}\".\"#{@table_name}\" "
      case sql_params
      when String
        delete_sql << sql_params
      when Hash
        raise ArgumentError, "Cannot specify bind variables when passing WHERE conditions as Hash" unless bindvars.empty?
        where_sqls = []
        sql_params.each do |k, v|
          where_sqls << "#{k} = :#{k}"
          bindvars << v
        end
        delete_sql << "WHERE " << where_sqls.join(" AND ") unless where_sqls.empty?
      else
        raise ArgumentError, "Only String or Hash can be provided as SQL condition argument"
      end
      @schema.execute(delete_sql, *bindvars)
    end
57010
function validateData(data, schema, fn) {
        debug('Schema:', schema);
        debug('Data:', data);

        if (!tv4.validate(data, schema)) {
            return fn(tv4.error);
        }

        return fn(null, true);
    }
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
        }
    })
}
1141863
function doDelete(filter) {
    console.log('folder delete called', filter);
    return new Promise(function(resolve, reject) {
      var keysPromise;
      var deletes = [], deletedKeys = [];

      if (common.keyTypes.indexOf(typeof filter) !== -1) {
        filter = [filter];
      } else if (filter instanceof Array) {
      } else if (filter === true || typeof filter === 'object') {
        console.log('object/true delete handler');
        // Get the existing keys
        readKeys().then(function(existingKeys) {
          console.log('existing keys are', existingKeys);
          if (filter === true) {
            deletedKeys = existingKeys;
            existingKeys.forEach(function(key) {
              deletes.push(saveData(key));
            });
          } else {
            if (options.cacheValues) {
              console.log('processing filter', filter);
              common.processFilter(cachedData, filter, function(key) {
                console.log('deleting matching item', key);
                deletes.push(saveData(key).then(function() {
                  delete cachedData[key];
                  deletedKeys.push(key);
                }));
              });
            } else {
              console.log('processing filter on non-cached data');
              existingKeys.forEach(function(key) {
                deletes.push(readData(key).then(function(data) {
                  console.log('loaded data for', key);
                  if (common.runFilter(data, filter)) {
                    return saveData(key).then(function() {
                      if (options.cacheKeys) {
                        cachedKeys.splice(cachedKeys.indexOf(key), 1);
                      }
                      deletedKeys.push(key);
                    });
                  } else {
                    return Promise.resolve();
                  }
                }));
              });
            }
          }

          return Promise.all(deletes).then(function() {
            if (filter === true && options.cacheValues) {
              cachedData = {};
            }
            if (options.cacheValues && options.cacheKeys) {
              cachedKeys = Object.keys(cachedData);
            } else if (filter === true && options.cacheKeys) {
              cachedKeys = [];
            }
            resolve(deletedKeys);
          });
        }).catch(function(error) {
          reject(error);
        });

        return;
      } else {
        reject({
          message: 'filter needs to be an object containing a filter'
        });
        return;
      }

      /* Get the list of keys */
      if (options.cacheKeys) {
        keysPromise = Promise.resolve(cachedKeys);
      } else {
        keysPromise = readKeys();
      }

      keysPromise.then(function(keys) {
        console.log('got current keys', keys);
        filter.forEach(function(id) {
          if (keys.indexOf(id) !== -1) {
            // TODO XXX Remove once file watch implemented
            deletes.push(saveData(id).then(function() {
              if (options.cacheValues) {
                delete cachedData[id];
              } else if (options.cacheKeys) {
                // Delete remove key from cached keys if caching keys but not values
                cachedKeys.splice(cachedKeys.indexOf(id), 1);
              }

              deletedKeys.push(id);
            }));
          }
        });

        Promise.all(deletes).then(function() {
          // Redo cached keys if caching keys and values (otherwise done above)
          if (options.cacheKeys && options.cacheValues) {
            cachedKeys = Object.keys(cachedData);
          }
          resolve(deletedKeys);
        });
      }).catch(function(error) {
        reject(error);
      });
    });
  }
380566
function checkForReservedFieldName(args) {
  if (!args) {
    return;
  }
  if (args.databaseTypeName) {
    checkFieldName(args.name, args.databaseTypeName, args.shouldThrow);
  } else {
    for (let i = 0, types = Object.keys(DatabaseTypes); i < types.length; i++) {
      checkFieldName(args.name, DatabaseTypes[types[i]], args.shouldThrow);
    }
  }
}
221057
public int delete(String query, Object... args) throws DAOException{
        if(query==null)
            query = "";
        return jdbc.executeUpdate("DELETE FROM "+table.name+" "+query, args);
    }
1287206
function checkSelectById () {
    // default to false
    this.isSelectById = false
    // id column must be in where clause
    if (!defined(this.args.where.id)) {
        return
    }
    // id must be string or array being selected with all results
    if (typeof this.args.where.id !== 'string' && !(Array.isArray(this.args.where.id) && (this.args.all || this.args.one))) {
        return
    }
    // query with order and join not supported
    if (defined(this.args.order) || defined(this.args.join)) {
        return
    }
    // false if there are custom revision flags
    if (this.args.allRevisions || this.args.current || this.args.isCurrent) {
        return
    }
    // get number of properties for where
    var whereProps = _.keys(this.args.where).length
    // false if there are more than 2 (id, isDeleted) where props
    if (whereProps > 2) {
        return
    }
    // if there are 2 where props other must be isDeleted
    else if (whereProps === 2 && !defined(this.args.where.isDeleted)) {
        return
    }
    // query is select by id
    this.isSelectById = true
}
829018
def sqldelete(table, where):
    
    validate_name(table)
    (whereclause, wherevalues) = sqlwhere(where)
    sql = "delete from {}".format(table)
    if whereclause:
        sql += " where " + whereclause
    return (sql, wherevalues)
948204
function (args) {
                args.HasError = false;
                args.ErrorMessage = "";

                //no dates - > nothing to validate
                if (!_.isDate(this.From) || !_.isDate(this.To))
                    return;

                if (self.FromDatePart.isAfter(self.ToDatePart)) {
                    args.HasError = true;
                    args.ErrorMessage = customErrorMessage({ Msg: "Date from '{From}' must be before date to '{To}'.", Format: 'MM/DD/YYYY' }, this);
                    args.TranslateArgs = { TranslateId: 'BeforeDate', MessageArgs: this, CustomMessage: customErrorMessage };
                    return;
                }

                var minDays = 1;
                var maxDays = 25;

                //maximal duration
                if (self.IsOverLimitRange || (self.VacationDaysCount > maxDays || self.VacationDaysCount < minDays)) {
                    args.HasError = true;
                    var messageArgs = { MaxDays: maxDays, MinDays: minDays };
                    args.ErrorMessage = Utils.StringFce.format("Vacation duration value must be between {MinDays] and {MaxDays} days.", messageArgs);
                    args.TranslateArgs = { TranslateId: 'RangeDuration', MessageArgs: messageArgs };
                    return;
                }

                var diff = _.difference(self.ExcludedDaysDatePart, self.RangeDays);
                if (diff.length != 0) {
                    args.HasError = true;
                    var messageArgs2 = { ExcludedDates: _.reduce(diff, function (memo, item) {
                            return memo + item.format("MM/DD/YYYY");
                        }) };
                    args.ErrorMessage = Utils.StringFce.format("Excluded days are not in range. '{ExcludedDates}'.", messageArgs2);
                    args.TranslateArgs = { TranslateId: 'ExcludedDaysMsg', MessageArgs: messageArgs2 };
                    return;
                }
            }
1174579
@CheckResult protected Observable<Integer> delete(@NonNull final String table,
      @Nullable final String whereClause, @Nullable final String... whereArgs) {
    return Observable.defer(new Func0<Observable<Integer>>() {
      @Override
      public Observable<Integer> call() {
        return Observable.just(db.delete(table, whereClause, whereArgs));
      }
    });
  }
863872
function(ev,args) {
      var target = Event.getTarget(ev);
      var column = this.datatable.getColumn(target);      
      var rowIndex = this.datatable.getTrIndex(target);
      if (column.key == 'delete') {
         if (confirm(msgs.confirmDeletion)) {
            var record = this.datatable.getRecord(target);
            if(this.editingNewRecord) {
               this.editingNewRecord = false;
            }
            else {
               this.itemRemovedEvt.fire( record );
            }
            this.datatable.deleteRow(target);
            this.hideSubform();
         }
      }
      else if(column.key == 'modify') {
         this.onClickModify(rowIndex);
      } 
      else {				
      	this.onCellClick(ev,rowIndex);
      }
   }
852655
function (args, onDone, extra) {
		// if args are not provided then we shift the parameters
		if (typeof args === 'function') {
			extra = onDone;
			onDone = args;
			args = {};
		}

		// TODO: perform argument type check (currently there's none, so internal API calls won't do type checks)
		// TODO: move checker to here

		var onError = function(err) {
			LOG.error('onError '+ err, l_name);
			UTIL.safeCall(onDone, err);
		}

		function onExec() {
			// make actual call to user-defined function
			// NOTE: we also return values for direct function calls
			return UTIL.safeCall(l_list[name], args, function (err, result, unsupported_return) {
				if (err) {
					LOG.error('[' + name + '] error:', l_name);
					LOG.error(err, l_name);
				}

				if (unsupported_return) {
					var errmsg = 'onDone() in SR.API does not support more than one return variable, please return everything inside a result object';
					LOG.error(errmsg, l_name);
					LOG.stack();
					return UTIL.safeCall(onDone, errmsg);
				}

				// perform post-event actions, if any
				if (l_afterActions.hasOwnProperty(name) === false) {
					return UTIL.safeCall(onDone, err, result);
				}

				var posts = l_afterActions[name];
				var promise = undefined;
				for (var i=0; i < posts.length; i++) {
					if (!promise) {
						promise = post_action(args, { err: err, result: result }, posts[i], extra);
					} else {
						promise = promise.then(post_action(args, { err: err, result: result }, posts[i], extra));
					}
				}

				// last action
				promise.then(new SR.promise(function (resolve, reject) {
					//LOG.warn('everything is done... call original onDone...', l_name);
					UTIL.safeCall(onDone, err, result);
					resolve();
				}));

			}, extra);
		}

		// perform pre-event actions, if any
		if (l_beforeActions.hasOwnProperty(name) === false) {
			return onExec();
		}

		const pres = l_beforeActions[name].map((callback) => pre_action(args, callback, extra));
		pres.reduce((p, callback) => p.then(() => callback), Promise.resolve())
			.then(onExec)
			.catch((err) => {
				LOG.error(err);
				onDone(err);
			});
	}
334397
function validateArgs (args, methodMeta) {
    // do not validate if no schema
    if (!defined(methodMeta.schema.args)) {
        return args
    }
    // do not validate if disabled
    if (!methodMeta.validateArgs) {
        return args
    }
    // get validator
    var ajv = methodMeta.ajv
    // throw error if validation fails
    if (!ajv.validate(methodMeta.schema.args.id, args)) {
        // create error
        var error = new Error(`${methodMeta.signature}: invalid args - ${ajv.errorsText()}`)
        // add ajv errors to error data
        error.data = ajv.errors
        // throw error
        throw error
    }
    // return possibly modified args
    return args
}