Example #1
0
QueryInterface.prototype.showIndex = function(tableName, options) {
  var sql = this.QueryGenerator.showIndexesQuery(tableName, options);
  return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
};
 before(function () {
   optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions);
   promptCase = _.assign(_.cloneDeep(defaultPrompts), {
     router: prompts.router.values.none
   });
 });
 before(function () {
   optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions);
   promptCase = _.assign(_.cloneDeep(defaultPrompts), {
     ui: prompts.ui.values['angular-material']
   });
 });
 before(function () {
   optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions);
   promptCase = _.assign(_.cloneDeep(defaultPrompts), {
     'angularVersion': prompts.angularVersion.values['1.2']
   });
 });
 before(function () {
   optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions);
   promptCase = _.assign(_.cloneDeep(defaultPrompts), {
     jQuery: prompts.jQuery.values['zeptojs 1.1']
   });
 });
			.tap(packetHeader => {
				//	Convert password from NULL padded array to string
				//packetHeader.password = ftn.stringFromFTN(packetHeader.password);
				packetHeader.password = strUtil.stringFromNullTermBuffer(packetHeader.password, 'CP437');

				if(FTN_PACKET_HEADER_TYPE !== packetHeader.packetType) {
					cb(new Error('Unsupported header type: ' + packetHeader.packetType));
					return;
				}

				//
				//	What kind of packet do we really have here?
				//
				//	:TODO: adjust values based on version discovered
				if(FTN_PACKET_BAUD_TYPE_2_2 === packetHeader.baud) {
					packetHeader.version = '2.2';

					//	See FSC-0045
					packetHeader.origPoint	= packetHeader.year;
					packetHeader.destPoint	= packetHeader.month;

					packetHeader.destDomain = packetHeader.origZone2;
					packetHeader.origDomain	= packetHeader.auxNet;
				} else {
					//
					//	See heuristics described in FSC-0048, "Receiving Type-2+ bundles"
					//
					const capWordValidateSwapped = 
						((packetHeader.capWordValidate & 0xff) << 8) |
						((packetHeader.capWordValidate >> 8) & 0xff);

					if(capWordValidateSwapped === packetHeader.capWord && 
						0 != packetHeader.capWord &&
						packetHeader.capWord & 0x0001)
					{
						packetHeader.version = '2+';

						//	See FSC-0048
						if(-1 === packetHeader.origNet) {
							packetHeader.origNet = packetHeader.auxNet;
						}
					} else {
						packetHeader.version = '2';

						//	:TODO: should fill bytes be 0?
					}
				}
						
				packetHeader.created = moment({
					year 	: packetHeader.year,
					month	: packetHeader.month - 1,	//	moment uses 0 indexed months
					date	: packetHeader.day,
					hour	: packetHeader.hour,
					minute	: packetHeader.minute,
					second	: packetHeader.second
				});
				
				let ph = new PacketHeader();
				_.assign(ph, packetHeader);

				cb(null, ph);
			});
Example #7
0
 return getTransferId(fulfillment.transfer_id, options).then((transferId) => {
   return _.assign({}, fulfillment, {transfer_id: transferId})
 })
Example #8
0
 [UPDATE_PAGE_STATE]: (state, pageState) => {
   state.page.state = _.assign({}, state.page.state, pageState);
   return state;
 },
Example #9
0
gulp.task('tests', ['validate_tests'], function(done) {
  karma.start(_.assign({}, karmaCommonConf, {singleRun: true}), done);
});
    const fetchJsonApi = function (opts, isCollection = true, type) {

        opts = opts || {};

        const internals = {};
        const { include, fields, sort, page = {}, filter } = opts;

        // Get a reference to the field being used as the id
        internals.idAttribute = this.constructor.prototype.idAttribute ?
            this.constructor.prototype.idAttribute : 'id';

        // Get a reference to the current model name. Note that if no type is
        // explcitly passed, the tableName will be used
        internals.modelName = type ? type : this.constructor.prototype.tableName;

        // Initialize an instance of the current model and clone the initial query
        internals.model =
            this.constructor.forge().query((qb) => _assign(qb, this.query().clone()));

        /**
         * Build a query based on the `fields` parameter.
         * @param  fieldNames {object}
         */
        internals.buildFields = (fieldNames = {}) => {

            if (_isObject(fieldNames) && !_isEmpty(fieldNames)) {

                // Format column names
                fieldNames = internals.formatColumnNames(fieldNames);

                // Process fields for each type/relation
                _forEach(fieldNames, (fieldValue, fieldKey) => {

                    // Add qualifying table name to avoid ambiguous columns
                    fieldNames[fieldKey] = _map(fieldNames[fieldKey], (value) => {

                        return `${fieldKey}.${value}`;
                    });

                    // Only process the field if it's not a relation. Fields
                    // for relations are processed in `buildIncludes()`
                    if (!_includes(include, fieldKey)) {

                        // Add column to query
                        internals.model.query((qb) => {

                            qb.column.apply(qb, [fieldValue]);

                            // JSON API considers relationships as fields, so we
                            // need to make sure the id of the relation is selected
                            _forEach(include, (relation) => {

                                const relationId = `${relation}_id`;

                                if (!internals.isManyRelation(relation) &&
                                    !_includes(fieldNames[relation], relationId)) {

                                    qb.column.apply(qb, [relationId]);
                                }
                            });
                        });
                    }
                });
            }
        };

        /**
         * Build a query based on the `filters` parameter.
         * @param  filterValues {object|array}
         */
        internals.buildFilters = (filterValues) => {

            if (_isObjectLike(filterValues) && !_isEmpty(filterValues)) {

                // format the column names of the filters
                filterValues = this.format(filterValues);

                // build the filter query
                internals.model.query((qb) => {

                    _forEach(filterValues, (value, key) => {

                        // Determine if there are multiple filters to be applied
                        value = value.toString().indexOf(',') !== -1 ? value.split(',') : value;

                        qb.whereIn.apply(qb, [key, value]);
                    });
                });
            }
        };

        /**
         * Build a query based on the `include` parameter.
         * @param  includeValues {array}
         */
        internals.buildIncludes = (includeValues) => {

            if (_isArray(includeValues) && !_isEmpty(includeValues)) {

                const relations = [];

                _forEach(includeValues, (relation) => {

                    if (_has(fields, relation)) {

                        const fieldNames = internals.formatColumnNames(fields);

                        relations.push({
                            [relation]: (qb) => {

                                const relationId = `${internals.modelName}_id`;

                                if (!internals.isBelongsToRelation(relation) &&
                                    !_includes(fieldNames[relation], relationId)) {

                                    qb.column.apply(qb, [relationId]);
                                }

                                qb.column.apply(qb, [fieldNames[relation]]);
                            }
                        });
                    }
                    else {
                        relations.push(relation);
                    }
                });

                // Assign the relations to the options passed to fetch/All
                _assign(opts, { withRelated: relations });
            }
        };

        /**
         * Build a query based on the `sort` parameter.
         * @param  sortValues {array}
         */
        internals.buildSort = (sortValues = []) => {


            if (_isArray(sortValues) && !_isEmpty(sortValues)) {

                let sortDesc = [];

                for (let i = 0; i < sortValues.length; ++i) {

                    // Determine if the sort should be descending
                    if (typeof sortValues[i] === 'string' && sortValues[i][0] === '-') {
                        sortDesc.push(sortValues[i].substring(1, sortValues[i].length));
                    }
                }

                // Format column names according to Model settings
                sortDesc = internals.formatColumnNames(sortDesc);
                sortValues = internals.formatColumnNames(sortValues);

                _forEach(sortValues, (sortBy) => {

                    internals.model.orderBy(sortBy, sortDesc.indexOf(sortBy) === -1 ? 'asc' : 'desc');
                });
            }
        };

        /**
         * Processes incoming parameters that represent columns names and
         * formats them using the internal {@link Model#format} function.
         * @param  columnNames {array}
         * @return {array{}
         */
        internals.formatColumnNames = (columnNames = []) => {

            _forEach(columnNames, (value, key) => {

                let columns;

                // Convert column names to an object so it can
                // be passed to Model#format
                if (_isArray(columnNames[key])) {
                    columns = _zipObject(columnNames[key], null);
                }
                else {
                    columns = _zipObject(columnNames, null);
                }

                // Format column names using Model#format
                if (_isArray(columnNames[key])) {
                    columnNames[key] = _keys(this.format(columns));
                }
                else {
                    columnNames = _keys(this.format(columns));
                }
            });

            return columnNames;
        };

        /**
         * Determines if the specified relation is a `belongsTo` type.
         * @param  relationName {string}
         * @return {boolean}
         */
        internals.isBelongsToRelation = (relationName) => {

            const relationType = this.related(relationName).relatedData.type.toLowerCase();

            if (relationType !== undefined &&
                relationType === 'belongsto') {

                return true;
            }

            return false;
        };

        /**
         * Determines if the specified relation is a `many` type.
         * @param  relationName {string}
         * @return {boolean}
         */
        internals.isManyRelation = (relationName) => {

            const relationType = this.related(relationName).relatedData.type.toLowerCase();

            if (relationType !== undefined &&
                relationType.indexOf('many') > 0) {

                return true;
            }

            return false;
        };

        ////////////////////////////////
        /// Process parameters
        ////////////////////////////////

        // Apply filters
        internals.buildFilters(filter);

        // Apply sorting
        internals.buildSort(sort);

        // Apply relations
        internals.buildIncludes(include);


        // Apply sparse fieldsets
        internals.buildFields(fields);

        // Assign default paging options if they were passed to the plugin
        // and no pagination parameters were passed directly to the method.
        if (isCollection &&
            _isEmpty(page) &&
            _has(options, 'pagination')) {

            _assign(page, options.pagination);
        }

        // Apply paging
        if (isCollection &&
            _isObject(page) &&
            !_isEmpty(page)) {

            const pageOptions = _assign(opts, page);

            return internals.model.fetchPage(pageOptions);
        }

        // Determine whether to return a Collection or Model

        // Call `fetchAll` to return Collection
        if (isCollection) {
            return internals.model.fetchAll(opts);
        }

        // Otherwise, call `fetch` to return Model
        return internals.model.fetch(opts);
    };
this.constructor.forge().query((qb) => _assign(qb, this.query().clone()));
Example #12
0
 {_.map(props.items, item => types[item.type] ? types[item.type](_.assign(
   {className: getInnerClassName(item, props.changes[item.key])},
     item,
     _.mapValues(fns, fn => _.partial(fn, item))
   )) : null)}
Example #13
0
QueryInterface.prototype.createTable = function(tableName, attributes, options, model) {
  var keys = Object.keys(attributes)
    , keyLen = keys.length
    , self = this
    , sql = ''
    , i = 0;

  options = _.clone(options) || {};

  attributes = Utils._.mapValues(attributes, function(attribute) {
    if (!Utils._.isPlainObject(attribute)) {
      attribute = { type: attribute, allowNull: true };
    }

    attribute = self.sequelize.normalizeAttribute(attribute);

    return attribute;
  });

  // Postgres requires a special SQL command for enums
  if (self.sequelize.options.dialect === 'postgres') {
    var promises = [];

    for (i = 0; i < keyLen; i++) {
      if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
        sql = self.QueryGenerator.pgListEnums(tableName, attributes[keys[i]].field || keys[i], options);
        promises.push(self.sequelize.query(
          sql,
          _.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT })
        ));
      }
    }

    return Promise.all(promises).then(function(results) {
      var promises = []
        , enumIdx = 0;

      for (i = 0; i < keyLen; i++) {
        if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
          // If the enum type doesn't exist then create it
          if (!results[enumIdx]) {
            sql = self.QueryGenerator.pgEnum(tableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options);
            promises.push(self.sequelize.query(
              sql,
              _.assign({}, options, { raw: true })
            ));
          } else if (!!results[enumIdx] && !!model) {
            var enumVals = self.QueryGenerator.fromArray(results[enumIdx].enum_value)
              , vals = model.rawAttributes[keys[i]].values;

            vals.forEach(function(value, idx) {
              // reset out after/before options since it's for every enum value
              var valueOptions = _.clone(options);
              valueOptions.before = null;
              valueOptions.after = null;

              if (enumVals.indexOf(value) === -1) {
                if (!!vals[idx + 1]) {
                  valueOptions.before = vals[idx + 1];
                }
                else if (!!vals[idx - 1]) {
                  valueOptions.after = vals[idx - 1];
                }
                valueOptions.supportsSearchPath = false;
                promises.push(self.sequelize.query(self.QueryGenerator.pgEnumAdd(tableName, keys[i], value, valueOptions), valueOptions));
              }
            });
            enumIdx++;
          }
        }
      }

      if (!tableName.schema &&
        (options.schema || (!!model && model.$schema))) {
        tableName = self.QueryGenerator.addSchema({
          tableName: tableName,
          $schema: (!!model && model.$schema) || options.schema
        });
      }

      attributes = self.QueryGenerator.attributesToSQL(attributes, {
        context: 'createTable'
      });
      sql = self.QueryGenerator.createTableQuery(tableName, attributes, options);

      return Promise.all(promises).then(function() {
        return self.sequelize.query(sql, options);
      });
    });
  } else {
    if (!tableName.schema &&
      (options.schema || (!!model && model.$schema))) {
      tableName = self.QueryGenerator.addSchema({
        tableName: tableName,
        $schema: (!!model && model.$schema) || options.schema
      });
    }

    attributes = self.QueryGenerator.attributesToSQL(attributes, {
      context: 'createTable'
    });
    sql = self.QueryGenerator.createTableQuery(tableName, attributes, options);

    return self.sequelize.query(sql, options);
  }
};
Example #14
0
QueryInterface.prototype.databaseVersion = function(options) {
  return this.sequelize.query(
    this.QueryGenerator.versionQuery(),
    _.assign({}, options, { type: QueryTypes.VERSION })
  );
};
  var getOutputOptions = function(options, dest) {
    var outputOptions = {
      beautify: false,
      source_map: null
    };

    if (options.preserveComments) {
      if (options.preserveComments === 'all' || options.preserveComments === true) {

        // preserve all the comments we can
        outputOptions.comments = true;
      } else if (options.preserveComments === 'some') {
        // preserve comments with directives or that start with a bang (!)
        outputOptions.comments = /^!|@preserve|@license|@cc_on/i;
      } else if (_.isFunction(options.preserveComments)) {

        // support custom functions passed in
        outputOptions.comments = options.preserveComments;
      }
    }

    if (options.banner && options.sourceMap) {
      outputOptions.preamble = options.banner;
    }

    if (options.beautify) {
      if (_.isObject(options.beautify)) {
        // beautify options sent as an object are merged
        // with outputOptions and passed to the OutputStream
        _.assign(outputOptions, options.beautify);
      } else {
        outputOptions.beautify = true;
      }
    }

    if (options.screwIE8) {
      outputOptions.screw_ie8 = true;
    }

    if (options.sourceMap) {

      var destBasename = path.basename(dest);
      var sourceMapIn;
      if (options.sourceMapIn) {
        sourceMapIn = grunt.file.readJSON(options.sourceMapIn);
      }
      outputOptions.source_map = UglifyJS.SourceMap({
        file: destBasename,
        root: options.sourceMapRoot,
        orig: sourceMapIn
      });
      if (options.sourceMapIncludeSources && sourceMapIn && sourceMapIn.sourcesContent) {
        sourceMapIn.sourcesContent.forEach(function(content, idx) {
          outputOptions.source_map.get().setSourceContent(sourceMapIn.sources[idx], content);
        });
      }

      if (options.sourceMapIn) {
        outputOptions.source_map.get()._file = destBasename;
      }
    }

    if (!_.isUndefined(options.indentLevel)) {
      outputOptions.indent_level = options.indentLevel;
    }

    if (!_.isUndefined(options.maxLineLen)) {
      outputOptions.max_line_len = options.maxLineLen;
    }

    if (!_.isUndefined(options.ASCIIOnly)) {
      outputOptions.ascii_only = options.ASCIIOnly;
    }

    if (!_.isUndefined(options.quoteStyle)) {
      outputOptions.quote_style = options.quoteStyle;
    }

    return outputOptions;
  };
function updateEntityFromRemote(usergridResponse) {
    helpers.setWritable(this, ['uuid', 'name', 'type', 'created'])
    _.assign(this, usergridResponse.entity)
    helpers.setReadOnly(this, ['uuid', 'name', 'type', 'created'])
}
Example #17
0
assign(ColumnCompiler_Oracle.prototype, {

  // helper function for pushAdditional in increments() and bigincrements()
  _createAutoIncrementTriggerAndSequence: function () {
    // TODO Add warning that sequence etc is created
    this.pushAdditional(function () {
      var sequenceName = this.tableCompiler._indexCommand('seq', this.tableCompiler.tableNameRaw);
      var triggerName  = this.tableCompiler._indexCommand('trg', this.tableCompiler.tableNameRaw, this.getColumnName());
      var tableName    = this.tableCompiler.tableName();
      var columnName   = this.formatter.wrap(this.getColumnName());
      var createTriggerSQL = 'create or replace trigger ' + triggerName + ' before insert on ' + tableName +
        ' for each row' +
        ' when (new.' + columnName + ' is null) ' +
        ' begin' +
        ' select ' + sequenceName + '.nextval into :new.' + columnName + ' from dual;' +
        ' end;';
      this.pushQuery(utils.wrapSqlWithCatch('create sequence ' + sequenceName, -955));
      this.pushQuery(createTriggerSQL);
    });
  },

  increments: function () {
    this._createAutoIncrementTriggerAndSequence();
    return 'integer not null primary key';
  },

  bigincrements: function () {
    this._createAutoIncrementTriggerAndSequence();
    return 'number(20, 0) not null primary key';
  },

  floating: function(precision) {
    var parsedPrecision = this._num(precision, 0);
    return 'float' + (parsedPrecision ? '(' + parsedPrecision + ')' : '');
  },

  double: function(precision, scale) {
    // if (!precision) return 'number'; // TODO: Check If default is ok
    return 'number(' + this._num(precision, 8) + ', ' + this._num(scale, 2) + ')';
  },

  integer: function(length) {
      return length ? 'number(' + this._num(length, 11) + ')' : 'integer';
  },

  tinyint: 'smallint',

  smallint: 'smallint',

  mediumint: 'integer',

  biginteger: 'number(20, 0)',

  text: 'clob',

  enu: function (allowed) {
    allowed = uniq(allowed);
    var maxLength = (allowed || []).reduce(function (maxLength, name) {
      return Math.max(maxLength, String(name).length);
    }, 1);

    // implicitly add the enum values as checked values
    this.columnBuilder._modifiers.checkIn = [allowed];

    return "varchar2(" + maxLength + ")";
  },

  time: 'timestamp with time zone',

  datetime: function(without) {
    return without ? 'timestamp' : 'timestamp with time zone';
  },

  timestamp: function(without) {
    return without ? 'timestamp' : 'timestamp with time zone';
  },

  bit: 'clob',

  json: 'clob',

  bool: function () {
    // implicitly add the check for 0 and 1
    this.columnBuilder._modifiers.checkIn = [[0, 1]];
    return 'number(1, 0)';
  },

  varchar: function(length) {
    return 'varchar2(' + this._num(length, 255) + ')';
  },

  // Modifiers
  // ------

  comment: function(comment) {
    this.pushAdditional(function() {
      this.pushQuery('comment on column ' + this.tableCompiler.tableName() + '.' +
        this.formatter.wrap(this.args[0]) + " is '" + (comment || '')+ "'");
    }, comment);
  },

  checkIn: function (value) {
    // TODO: Maybe accept arguments also as array
    // TODO: value(s) should be escaped properly
    if (value === undefined) {
      return '';
    } else if (value instanceof Raw) {
      value = value.toQuery();
    } else if (Array.isArray(value)) {
      value = map(value, function (v) {
        return "'" + v + "'";
      }).join(', ');
    } else {
      value = "'" + value + "'";
    }
    return 'check (' + this.formatter.wrap(this.args[0]) + ' in (' + value + '))';
  }

});
 putProperties: function(obj) {
     _.assign(this, obj)
 },
Example #19
0
assign(TableCompiler_MySQL.prototype, {

  createQuery(columns, ifNot) {
    const createStatement = ifNot ? 'create table if not exists ' : 'create table ';
    const { client } = this;
    let conn = {};
    let sql = createStatement + this.tableName() + ' (' + columns.sql.join(', ') + ')';

    // Check if the connection settings are set.
    if (client.connectionSettings) {
      conn = client.connectionSettings;
    }

    const charset = this.single.charset || conn.charset || '';
    const collation = this.single.collate || conn.collate || '';
    const engine = this.single.engine  || '';

    // var conn = builder.client.connectionSettings;
    if (charset)   sql += ` default character set ${charset}`;
    if (collation) sql += ` collate ${collation}`;
    if (engine)    sql += ` engine = ${engine}`;

    if (this.single.comment) {
      const comment = (this.single.comment || '');
      if (comment.length > 60) helpers.warn('The max length for a table comment is 60 characters');
      sql += ` comment = '${comment}'`;
    }

    this.pushQuery(sql);
  },

  addColumnsPrefix: 'add ',

  dropColumnPrefix: 'drop ',

  // Compiles the comment on the table.
  comment(comment) {
    this.pushQuery(`alter table ${this.tableName()} comment = '${comment}'`);
  },

  changeType() {
    // alter table + table + ' modify ' + wrapped + '// type';
  },

  // Renames a column on the table.
  renameColumn(from, to) {
    const compiler = this;
    const table = this.tableName();
    const wrapped = this.formatter.wrap(from) + ' ' + this.formatter.wrap(to);

    this.pushQuery({
      sql: `show fields from ${table} where field = ` +
        this.formatter.parameter(from),
      output(resp) {
        const column = resp[0];
        const runner = this;
        return compiler.getFKRefs(runner).get(0)
          .then(refs =>
            Promise.try(function () {
              if (!refs.length) { return; }
              return compiler.dropFKRefs(runner, refs);
            }).then(function () {
              let sql = `alter table ${table} change ${wrapped} ${column.Type}`;

              if(String(column.Null).toUpperCase() !== 'YES') {
                sql += ` NOT NULL`
              }
              if(column.Default !== void 0 && column.Default !== null) {
                sql += ` DEFAULT '${column.Default}'`
              }

              return runner.query({
                sql
              });
            }).then(function () {
              if (!refs.length) { return; }
              return compiler.createFKRefs(runner, refs.map(function (ref) {
                if (ref.REFERENCED_COLUMN_NAME === from) {
                  ref.REFERENCED_COLUMN_NAME = to;
                }
                if (ref.COLUMN_NAME === from) {
                  ref.COLUMN_NAME = to;
                }
                return ref;
              }));
            })
          );
      }
    });
  },

  getFKRefs (runner) {
    const formatter = this.client.formatter();
    const sql = 'SELECT KCU.CONSTRAINT_NAME, KCU.TABLE_NAME, KCU.COLUMN_NAME, '+
              '       KCU.REFERENCED_TABLE_NAME, KCU.REFERENCED_COLUMN_NAME, '+
              '       RC.UPDATE_RULE, RC.DELETE_RULE '+
              'FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU '+
              'JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC '+
              '       USING(CONSTRAINT_NAME)' +
              'WHERE KCU.REFERENCED_TABLE_NAME = ' + formatter.parameter(this.tableNameRaw) + ' '+
              '  AND KCU.CONSTRAINT_SCHEMA = ' + formatter.parameter(this.client.database()) + ' '+
              '  AND RC.CONSTRAINT_SCHEMA = ' + formatter.parameter(this.client.database());

    return runner.query({
      sql,
      bindings: formatter.bindings
    });
  },

  dropFKRefs (runner, refs) {
    const formatter = this.client.formatter();

    return Promise.all(refs.map(function (ref) {
      const constraintName = formatter.wrap(ref.CONSTRAINT_NAME);
      const tableName = formatter.wrap(ref.TABLE_NAME);
      return runner.query({
        sql: `alter table ${tableName} drop foreign key ${constraintName}`
      });
    }));
  },
  createFKRefs (runner, refs) {
    const formatter = this.client.formatter();

    return Promise.all(refs.map(function (ref) {
      const tableName = formatter.wrap(ref.TABLE_NAME);
      const keyName = formatter.wrap(ref.CONSTRAINT_NAME);
      const column = formatter.columnize(ref.COLUMN_NAME);
      const references = formatter.columnize(ref.REFERENCED_COLUMN_NAME);
      const inTable = formatter.wrap(ref.REFERENCED_TABLE_NAME);
      const onUpdate = ` ON UPDATE ${ref.UPDATE_RULE}`;
      const onDelete = ` ON DELETE ${ref.DELETE_RULE}`;

      return runner.query({
        sql: `alter table ${tableName} add constraint ${keyName} ` +
          'foreign key (' + column + ') references ' + inTable + ' (' + references + ')' + onUpdate + onDelete
      });
    }));
  },
  index(columns, indexName) {
    indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns);
    this.pushQuery(`alter table ${this.tableName()} add index ${indexName}(${this.formatter.columnize(columns)})`);
  },

  primary(columns, indexName) {
    indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('primary', this.tableNameRaw, columns);
    this.pushQuery(`alter table ${this.tableName()} add primary key ${indexName}(${this.formatter.columnize(columns)})`);
  },

  unique(columns, indexName) {
    indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns);
    this.pushQuery(`alter table ${this.tableName()} add unique ${indexName}(${this.formatter.columnize(columns)})`);
  },

  // Compile a drop index command.
  dropIndex(columns, indexName) {
    indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns);
    this.pushQuery(`alter table ${this.tableName()} drop index ${indexName}`);
  },

  // Compile a drop foreign key command.
  dropForeign(columns, indexName) {
    indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('foreign', this.tableNameRaw, columns);
    this.pushQuery(`alter table ${this.tableName()} drop foreign key ${indexName}`);
  },

  // Compile a drop primary key command.
  dropPrimary() {
    this.pushQuery(`alter table ${this.tableName()} drop primary key`);
  },

  // Compile a drop unique key command.
  dropUnique(column, indexName) {
    indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, column);
    this.pushQuery(`alter table ${this.tableName()} drop index ${indexName}`);
  }

})
Example #20
0
/**
 * The function that provides the data that needs to be
 * evaluated by conditional logic.
 *
 * @param  {Object} props
 * @param  {Object} fields
 * @return {Object}
 */
function output( props, fields ) {
	const isTopLevelField = has( fields, props.field.base_name );
	let siblingFields = {};

	if ( isTopLevelField ) {
		siblingFields = mapParentPrefix( omit( fields, [ props.field.base_name ] ) );
	} else {
		// Get the hierarchy.
		const path = props.id.split( '__' );

		// Remove the chunk with identifier of block since
		// we already have it.
		path.shift();

		// Remove the chunk with name of root field.
		const rootFieldName = path.shift();

		// Remove the chunk with name of field since
		// we already have it.
		path.pop();

		// Keep reference to the depth
		// so we can add the `parent.` prefix.
		let depth = path.reduce( ( accumulator, chunk ) => {
			return isComplexGroupIdentifier( chunk )
				? accumulator
				: accumulator + 1;
		}, 0 );

		// Collect fields that are siblings of root field.
		siblingFields = omit( fields, [ rootFieldName ] );
		siblingFields = mapParentPrefix( siblingFields, depth + 1 );

		// Keep reference to the full path of the field.
		let pathPrefix = rootFieldName;

		while ( path.length > 0 ) {
			const chunk = path.shift();
			const isGroup = isComplexGroupIdentifier( chunk );
			const isNestedComplex = ! isGroup;

			if ( isGroup ) {
				const groupIndex = findIndex( get( fields, pathPrefix ), [ '_id', chunk ] );

				pathPrefix = `${ pathPrefix }.${ groupIndex }`;

				let groupFields = get( fields, pathPrefix );
				groupFields = omit( groupFields, [ '_id', '_type', props.field.base_name ] );
				groupFields = mapParentPrefix( groupFields, depth );

				assign( siblingFields, groupFields );
			}

			if ( isNestedComplex ) {
				pathPrefix = `${ pathPrefix }.${ chunk }`;

				depth--;
			}
		}
	}

	return siblingFields;
}
 before(function () {
   optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions);
   promptCase = _.assign(_.cloneDeep(defaultPrompts), {
     htmlPreprocessor: prompts.htmlPreprocessor.values.jade
   });
 });
Example #22
0
settings.appcache_media = settings.frontend_dir + '/appcache_media.json';

settings.db_transformer = function (data) {
  return dbTransformer(settings, data);
};

if ('DEBUG' in process.env) {
  settings.debug = !!+process.env.DEBUG;
}

// Load local- or prod-specific settings to override the ones above.

// Hopefully this is the only command-line argument we need ;)
var settings_name = process.argv.slice(2).join('')
  .replace('--settings', '').replace('=','').trim()
  .replace(/^\.\//, '').replace(/\.js$/, '') || 'settings_local';

var settings_local = {};

try {
  console.log(pkg.name + ' v' + pkg.version +
              ", using settings '" + settings_name + "'");
  settings_local = require('./' + settings_name);
} catch (err) {
  if (err.code !== 'MODULE_NOT_FOUND') {
    throw err;
  }
}

module.exports = settings = _.assign(settings, settings_local || {});
 before(function () {
   optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions);
   promptCase = _.assign(_.cloneDeep(defaultPrompts), {
     angularModules: []
   });
 });
router.get('/:filename', function(req, res, next) {
    _.assign(res.locals, filenames(res.locals));

    if (req.params.filename == res.locals.scoreStatsCsvFilename) {
        var params = {assessment_id: res.locals.assessment.id};
        sqldb.queryOneRow(sql.assessment_stats, params, function(err, result) {
            if (ERR(err, next)) return;
            var assessmentStat = result.rows[0];
            var csvHeaders = ['Course', 'Instance', 'Set', 'Number', 'Assessment', 'Title', 'TID', 'NStudents', 'Mean',
                              'Std', 'Min', 'Max', 'Median', 'NZero', 'NHundred', 'NZeroPerc', 'NHundredPerc'];
            var csvData = [
                res.locals.course.short_name,
                res.locals.course_instance.short_name,
                res.locals.assessment_set.name,
                res.locals.assessment.number,
                res.locals.assessment_set.abbreviation + res.locals.assessment.number,
                res.locals.assessment.title,
                res.locals.assessment.tid,
                assessmentStat.number,
                assessmentStat.mean,
                assessmentStat.std,
                assessmentStat.min,
                assessmentStat.max,
                assessmentStat.median,
                assessmentStat.n_zero,
                assessmentStat.n_hundred,
                assessmentStat.n_zero_perc,
                assessmentStat.n_hundred_perc,
            ];
            _(assessmentStat.score_hist).each(function(count, i) {
                csvHeaders.push("Hist " + (i + 1));
                csvData.push(count);
            });
            csvData = [csvHeaders, csvData];
            csvStringify(csvData, function(err, csv) {
                if (ERR(err, next)) return;
                res.attachment(req.params.filename);
                res.send(csv);
            });
        });
    } else if (req.params.filename == res.locals.durationStatsCsvFilename) {
        var params = {assessment_id: res.locals.assessment.id};
        sqldb.queryOneRow(sql.assessment_duration_stats, params, function(err, result) {
            if (ERR(err, next)) return;
            var durationStat = result.rows[0];
            var csvHeaders = ['Course', 'Instance', 'Set', 'Number', 'Assessment', 'Title', 'TID',
                              'Mean duration (min)', 'Median duration (min)', 'Min duration (min)', 'Max duration (min)'];
            var csvData = [
                res.locals.course.short_name,
                res.locals.course_instance.short_name,
                res.locals.assessment_set.name,
                res.locals.assessment.number,
                res.locals.assessment_set.abbreviation + res.locals.assessment.number,
                res.locals.assessment.title,
                res.locals.assessment.tid,
                durationStat.mean_mins,
                durationStat.median_mins,
                durationStat.min_mins,
                durationStat.max_mins,
            ];
            _(durationStat.threshold_seconds).each(function(count, i) {
                csvHeaders.push("Hist boundary " + (i + 1) + " (s)");
                csvData.push(count);
            });
            _(durationStat.hist).each(function(count, i) {
                csvHeaders.push("Hist" + (i + 1));
                csvData.push(count);
            });
            csvData = [csvHeaders, csvData];
            csvStringify(csvData, function(err, csv) {
                if (ERR(err, next)) return;
                res.attachment(req.params.filename);
                res.send(csv);
            });
        });
    } else if (req.params.filename == res.locals.instancesCsvFilename) {
        var params = {assessment_id: res.locals.assessment.id};
        sqldb.query(sql.assessment_instance_data, params, function(err, result) {
            if (ERR(err, next)) return;
            var columns = [
                ['UID', 'uid'],
                ['Name', 'name'],
                ['Role', 'role'],
                ['Assessment', 'assessment_label'],
                ['Instance', 'number'],
                ['Started', 'date_formatted'],
                ['Remaining', 'time_remaining'],
                ['Score (%)', 'score_perc'],
                ['Points', 'points'],
                ['Max points', 'max_points'],
                ['Duration (min)', 'duration_mins'],
            ];
            csvMaker.rowsToCsv(result.rows, columns, function(err, csv) {
                if (ERR(err, next)) return;
                res.attachment(req.params.filename);
                res.send(csv);
            });
        });
    } else if (req.params.filename == res.locals.scoresCsvFilename) {
        var params = {assessment_id: res.locals.assessment.id};
        sqldb.query(sql.assessment_instance_scores, params, function(err, result) {
            if (ERR(err, next)) return;
            var assessmentName = res.locals.assessment_set.name + ' ' + res.locals.assessment.number;
            var columns = [
                ['UID', 'uid'],
                [assessmentName, 'score_perc'],
            ];
            csvMaker.rowsToCsv(result.rows, columns, function(err, csv) {
                if (ERR(err, next)) return;
                res.attachment(req.params.filename);
                res.send(csv);
            });
        });
    } else if (req.params.filename == res.locals.scoresByUsernameCsvFilename) {
        var params = {assessment_id: res.locals.assessment.id};
        sqldb.query(sql.assessment_instance_scores_by_username, params, function(err, result) {
            if (ERR(err, next)) return;
            var assessmentName = res.locals.assessment_set.name + ' ' + res.locals.assessment.number;
            var columns = [
                ['Username', 'username'],
                [assessmentName, 'score_perc'],
            ];
            csvMaker.rowsToCsv(result.rows, columns, function(err, csv) {
                if (ERR(err, next)) return;
                res.attachment(req.params.filename);
                res.send(csv);
            });
        });
    } else if (req.params.filename == res.locals.allInstanceScoresCsvFilename) {
        var params = {assessment_id: res.locals.assessment.id};
        sqldb.query(sql.assessment_instance_scores_all, params, function(err, result) {
            if (ERR(err, next)) return;
            var assessmentName = res.locals.assessment_set.name + ' ' + res.locals.assessment.number;
            var columns = [
                ['UID', 'uid'],
                ['Instance', 'number'],
                [assessmentName, 'score_perc'],
            ];
            csvMaker.rowsToCsv(result.rows, columns, function(err, csv) {
                if (ERR(err, next)) return;
                res.attachment(req.params.filename);
                res.send(csv);
            });
        });
    } else if (req.params.filename == res.locals.allSubmissionsCsvFilename
               || req.params.filename == res.locals.finalSubmissionsCsvFilename) {
        var include_all = (req.params.filename == res.locals.allSubmissionsCsvFilename);
        var params = {
            assessment_id: res.locals.assessment.id,
            include_all: include_all,
        };
        sqldb.query(sql.assessment_instance_submissions, params, function(err, result) {
            if (ERR(err, next)) return;
            var columns = [
                ['UID', 'uid'],
                ['Name', 'name'],
                ['Role', 'role'],
                ['Assessment', 'assessment_label'],
                ['Assessment instance', 'assessment_instance_number'],
                ['Question', 'qid'],
                ['Question instance', 'instance_question_number'],
                ['Variant', 'variant_number'],
                ['Seed', 'variant_seed'],
                ['Params', 'params'],
                ['True answer', 'true_answer'],
                ['Options', 'options'],
                ['Submission date', 'submission_date_formatted'],
                ['Submitted answer', 'submitted_answer'],
                ['Override score', 'override_score'],
                ['Credit', 'credit'],
                ['Mode', 'mode'],
                ['Grading requested date', 'grading_requested_at_formatted'],
                ['Grading date', 'graded_at_formatted'],
                ['Score', 'score'],
                ['Correct', 'correct'],
                ['Feedback', 'feedback'],
            ];
            if (!include_all) {
                columns = columns.concat([
                    ['Question points', 'points'],
                    ['Max points', 'max_points'],
                    ['Question % score', 'score_perc'],
                ]);
            }
            csvMaker.rowsToCsv(result.rows, columns, function(err, csv) {
                if (ERR(err, next)) return;
                res.attachment(req.params.filename);
                res.send(csv);
            });
        });
    } else if (req.params.filename == res.locals.allFilesZipFilename
               || req.params.filename == res.locals.finalFilesZipFilename) {
        var include_all = (req.params.filename == res.locals.allFilesZipFilename);
        var params = {
            assessment_id: res.locals.assessment.id,
            include_all: include_all,
        };
        sqldb.query(sql.assessment_instance_files, params, function(err, result) {
            if (ERR(err, next)) return;
            var dirname = (res.locals.assessment_set.name + res.locals.assessment.number).replace(' ', '');
            dataFiles.filesToZipBuffer(result.rows, dirname, function(err, zipBuffer) {
                if (ERR(err, next)) return;
                res.attachment(req.params.filename);
                res.send(zipBuffer);
            });
        });
    } else if (req.params.filename == res.locals.questionStatsCsvFilename) {
        var params = {assessment_id: res.locals.assessment.id};
        sqldb.query(sql.question_stats, params, function(err, result) {
            if (ERR(err, next)) return;
            var questionStatsList = result.rows;
            var csvData = [];
            var csvHeaders = ['Question number', 'Question title', 'Mean score', 'Discrimination', 'Attempts'];
            for (var i = 0; i < 5; i++) {
                csvHeaders.push("Hist " + (i + 1));
            }

            csvData.push(csvHeaders);

            _(questionStatsList).each(function(questionStats) {
                questionStatsData = [];
                questionStatsData.push(questionStats.number);
                questionStatsData.push(questionStats.title);
                questionStatsData.push(questionStats.mean_score_per_question);
                questionStatsData.push(questionStats.discrimination);
                questionStatsData.push(questionStats.average_number_attempts);

                _(questionStats.quintile_scores).each(function(perc) {
                    questionStatsData.push(perc);
                });

                csvData.push(questionStatsData);
            });

            csvStringify(csvData, function(err, csv) {
                if (ERR(err, next)) return;
                res.attachment(req.params.filename);
                res.send(csv);
            });
        });
    } else if (req.params.filename == res.locals.statsByDateCsvFilename) {
        var params = {assessment_id: res.locals.assessment.id};
        sqldb.query(sql.assessment_score_histogram_by_date, params, function(err, result) {
            if (ERR(err, next)) return;
            var scoresByDay = result.rows;

            var csvHeaders = ["Date"];
            _(scoresByDay).each(function(day) {
                csvHeaders.push(day.date_formatted);
            });

            var numDays = scoresByDay.length;
            var numGroups = scoresByDay[0].histogram.length;

            var csvData = [];

            var groupData = ['Number'];
            for (var day = 0; day < numDays; day++) {
                groupData.push(scoresByDay[day].number);
            }
            csvData.push(groupData);
            
            var groupData = ['Mean score perc'];
            for (var day = 0; day < numDays; day++) {
                groupData.push(scoresByDay[day].mean_score_perc);
            }
            csvData.push(groupData);
            
            for (var group = 0; group < numGroups; group++) {
                var groupData = [(group * 10) + "% to " + ((group + 1) * 10) + "%"];
                for (var day = 0; day < numDays; day++) {
                    groupData.push(scoresByDay[day].histogram[group]);
                }
                csvData.push(groupData);
            }
            csvData.splice(0, 0, csvHeaders);
            csvStringify(csvData, function(err, csv) {
                if (ERR(err, next)) return;
                res.attachment(req.params.filename);
                res.send(csv);
            });
        });
    } else {
        next(new Error("Unknown filename: " + req.params.filename));
    }
});
 before(function () {
   optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions);
   promptCase = _.assign(_.cloneDeep(defaultPrompts), {
     resource: prompts.resource.values.restangular
   });
 });
 function(callback) {
     debug('set filenames');
     _.assign(res.locals, filenames(res.locals));
     callback(null);
 },
 before(function () {
   optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions);
   promptCase = _.assign(_.cloneDeep(defaultPrompts), {
     bootstrapComponents: prompts.bootstrapComponents.values.official
   });
 });
Example #28
0
  const corpusTree = corpus.reduce(function(map, node) {
    map[node.uid] = discardChildReferences(assign({}, node));

    return map;
  }, {});
 before(function () {
   optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions);
   promptCase = _.assign(_.cloneDeep(defaultPrompts), {
     jsPreprocessor: prompts.jsPreprocessor.values.traceur
   });
 });
Example #30
0
QueryInterface.prototype.pgListEnums = function (tableName, options) {
  options = options || {};
  var sql = this.QueryGenerator.pgListEnums(tableName);
  return this.sequelize.query(sql, _.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT }));
};