self.sequelize.query(showTablesSql, null, options).success(function(tableNames) {
   self.emit('showAllTables', null)
   emitter.emit('success', Utils._.flatten(tableNames))
 }).error(function(err) {
 tableNames.forEach(function(tableName, i) {
   result[tableName] = Utils._.compact(results[i]).map(function(r) { return r.constraint_name })
 })
Example #3
0
 it('doesn\'t camelize if second param is false', function() {
   expect(Utils._.underscoredIf('fooBar', true)).to.equal('foo_bar');
 });
Example #4
0
  var queryAndEmit = QueryInterface.prototype.queryAndEmit = function(sqlOrQueryParams, methodName, options, emitter) {
    options = Utils._.extend({
      success:     function(){},
      error:       function(){},
      transaction: null,
      logging:     this.sequelize.options.logging
    }, options || {})

    var execQuery = function(emitter) {
      var query;
      if (Array.isArray(sqlOrQueryParams)) {
        if (sqlOrQueryParams.length === 1) {
          sqlOrQueryParams.push(null)
        }

        if (sqlOrQueryParams.length === 2) {
          sqlOrQueryParams.push(typeof options === "object" ? options : {})
        }

        query = this.sequelize.query.apply(this.sequelize, sqlOrQueryParams)
      } else {
        query = this.sequelize.query(sqlOrQueryParams, null, options)
      }

      if (!emitter) {
        return query.then(function (result) {
          if (options.success) options.success(result);
          return result;
        }/*, function (err) {
          if (options.error) options.error(err);
        }*/);
      }

      emitter.query = query;

      emitter
        .query
        .success(function(obj) {
          if (options.success) {
            options.success(obj)
          }
          this.emit(methodName, null)
          emitter.emit('success', obj)
        }.bind(this))
        .error(function(err) {
          if (options.error) {
            options.error(err)
          }
          this.emit(methodName, err)
          emitter.emit('error', err)
        }.bind(this))
        .proxy(emitter, { events: ['sql'] })

      return emitter;
    }.bind(this)

    if (!!emitter) {
      execQuery(emitter)
    } else {
      return execQuery();
    }
  }
Example #5
0
 QueryInterface.prototype.bulkDelete = function(tableName, identifier, options, model) {
   var sql = this.QueryGenerator.deleteQuery(tableName, identifier, Utils._.defaults(options || {}, {limit: null}), model);
   return this.sequelize.query(sql, null, options);
 };
Example #6
0
  QueryInterface.prototype.createTable = function(tableName, attributes, options) {
    var keys = Object.keys(attributes)
      , keyLen = keys.length
      , self = this
      , sql = ''
      , i = 0;

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

      attribute.type = self.sequelize.normalizeDataType(attribute.type);

      if (attribute.hasOwnProperty('defaultValue')) {
        if (typeof attribute.defaultValue === 'function' && (
            attribute.defaultValue === DataTypes.NOW ||
            attribute.defaultValue === DataTypes.UUIDV4 ||
            attribute.defaultValue === DataTypes.UUIDV4
        )) {
          attribute.defaultValue = new attribute.defaultValue();
        }
      }

      if (attribute.type instanceof DataTypes.ENUM) {
        // The ENUM is a special case where the type is an object containing the values
        attribute.values = attribute.values || attribute.type.values || [];

        if (!attribute.values.length) {
          throw new Error('Values for ENUM haven\'t been defined.');
        }
      }

      return attribute;
    });

    options = Utils._.extend({
      logging: this.sequelize.options.logging,
    }, options || {});

    // Postgres requires a special SQL command for enums
    if (self.sequelize.options.dialect === 'postgres') {
      var promises = []
        // For backwards-compatibility, public schemas don't need to
        // explicitly state their schema when creating a new enum type
        , getTableName = (!options || !options.schema || options.schema === 'public' ? '' : options.schema + '_') + tableName;

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

      return Promise.all(promises).then(function(results) {
        var promises = []
          // Find the table that we're trying to create throgh DAOFactoryManager
          , daoTable = self.sequelize.daoFactoryManager.daos.filter(function(dao) { return dao.tableName === tableName; })
          , enumIdx = 0;

        daoTable = daoTable.length > 0 ? daoTable[0] : null;

        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(getTableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options);
              promises.push(self.sequelize.query(sql, null, { raw: true, logging: options.logging }));
            } else if (!!results[enumIdx] && !!daoTable) {
              var enumVals = self.QueryGenerator.fromArray(results[enumIdx].enum_value)
                , vals = daoTable.rawAttributes[keys[i]].values;

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

                if (enumVals.indexOf(value) === -1) {
                  if (!!vals[idx + 1]) {
                    options.before = vals[idx + 1];
                  }
                  else if (!!vals[idx - 1]) {
                    options.after = vals[idx - 1];
                  }

                  promises.push(self.sequelize.query(self.QueryGenerator.pgEnumAdd(getTableName, keys[i], value, options)));
                }
              });
              enumIdx++;
            }
          }
        }

        if (!tableName.schema && options.schema) {
          tableName = self.QueryGenerator.addSchema({
            tableName: tableName,
            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, null, options);
        });
      });
    } else {
      if (!tableName.schema && options.schema) {
        tableName = self.QueryGenerator.addSchema({
          tableName: tableName,
          schema: options.schema
        });
      }

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

      return self.sequelize.query(sql, null, options);
    }
  };
Example #7
0
 success: function(migration, callback) {
   if (options && Utils._.isFunction(options.success)) {
     options.success.call(self, migration);
   }
   callback();
 }
Example #8
0
  QueryInterface.prototype.upsert = function(tableName, values, model, options) {
    var wheres = []
      , where
      , indexFields
      , indexes = []
      , updateValues
      , attributes = Object.keys(values);

    where = {};
    for (var i = 0; i < model.primaryKeyAttributes.length; i++) {
      var key = model.primaryKeyAttributes[i];
      if(key in values){
        where[key] = values[key];
      }
    }

    if (!Utils._.isEmpty(where)) {
      wheres.push(where);
    }

    // Lets combine uniquekeys and indexes into one
    indexes = Utils._.map(model.options.uniqueKeys, function (value) {
      return value.fields;
    });

    Utils._.each(model.options.indexes, function (value) {
      if (value.unique === true) {
        // fields in the index may both the strings or objects with an attribute property - lets sanitize that
        indexFields = Utils._.map(value.fields, function (field) {
          if (Utils._.isPlainObject(field)) {
            return field.attribute;
          }
          return field;
        });
        indexes.push(indexFields);
      }
    });

    indexes.forEach(function (index) {
      if (Utils._.intersection(attributes, index).length === index.length) {
        where = {};
        index.forEach(function (field) {
          where[field] = values[field];
        });
        wheres.push(where);
      }
    });

    where = this.sequelize.or.apply(this.sequelize, wheres);

    options.type = QueryTypes.UPSERT;
    options.raw = true;


    if (model._timestampAttributes.createdAt) {
      // If we are updating an existing row, we shouldn't set createdAt
      updateValues = Utils.cloneDeep(values);

      delete updateValues[model._timestampAttributes.createdAt];
    } else {
      updateValues = values;
    }

    var sql = this.QueryGenerator.upsertQuery(tableName, values, updateValues, where, model.rawAttributes, options);
    return this.sequelize.query(sql, null, options).then(function (rowCount) {
      if (rowCount === undefined) {
        return rowCount;
      }

      // MySQL returns 1 for inserted, 2 for updated http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html. Postgres has been modded to do the same

      return rowCount === 1;
    });
  };
Example #9
0
 before: function(migration) {
   if (options && Utils._.isFunction(options.before)) {
     options.before.call(self, migration);
   }
 },
Example #10
0
 after: function(migration) {
   if (options && Utils._.isFunction(options.after)) {
     options.after.call(self, migration);
   }
 },
Example #11
0
 self.sequelize.query(showTablesSql, null, options).success(function(tableNames) {
   emitter.emit('success', Utils._.flatten(tableNames))
 }).proxy(emitter, { events: ['error', 'sql']})
Example #12
0
function validate(value, options) {
    options = _.defaults(options || {}, {
        trim : true,
        required : true,
        label : 'Value',
        compare : true
    });
    if (_.isObject(value)) {

        if ( typeof value.value === 'string') {

            if (value.hintText) {
                options.label = value.hintText;
            }

            value = value.value;

        } else if (options['compare'] !== true) {
            var values = {};

            _.each(_.keys(value), function(key) {
                var keyOptions, keyValue;

                if (_.isArray(value[key])) {
                    keyValue = value[key][0];
                    keyOptions = _.defaults(value[key][1] || {}, options);

                } else {
                    keyValue = value[key];
                    keyOptions = _.clone(options);
                }

                values[key] = validate(keyValue, keyOptions);

                return;
            });

            return values;
        }
    }

    if ( typeof value === 'string' && options.trim) {
        value = value.trim();
    }
    delete options.trim;

    if (options.required && _.isEmpty(value)) {
        throw String.format(L('validate_required', '%s is required.'), options.label);
    }
    delete options.required;

    var error;

    _.each(options, function(setting, key) {

        if (setting === false) {
            return;
        }

        switch (key) {

            case 'email':
                var email = /^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$/;
                if (!email.test(value))
                    throw String.format(L('validate_required', '%s is no email address.'), options.label);
                break;

            case 'regexp':
                if (!setting.test(value))
                    throw String.format(L('validate_regexp', '%s is not valid.'), options.label);
                break;

            case 'numeric':
                if (!_.isFinite(value))
                    throw String.format(L('validate_numeric', '%s is not a number.'), options.label);
                break;

            case "compare":
                for (var i = 1, j = value.compare.length; j > i; i++) {
                    if (value.compare[i - 1] !== value.compare[i])
                        throw L("validate_compare", "The values are not equal");
                }
                break;
        }

        return;
    });

    return value;
}
Example #13
0
  QueryInterface.prototype.createTable = function(tableName, attributes, options) {
    var attributeHashes   = {}
      , dataTypeValues    = Utils._.values(DataTypes)
      , keys              = Object.keys(attributes)
      , keyLen            = keys.length
      , self              = this
      , sql               = ''
      , i                 = 0

    for (i = 0; i < keyLen; i++) {
      if (dataTypeValues.indexOf(attributes[keys[i]]) > -1) {
        attributeHashes[keys[i]] = { type: attributes[keys[i]], allowNull: true }
      } else {
        attributeHashes[keys[i]] = attributes[keys[i]]
      }
    }

    options = Utils._.extend({
      logging: this.sequelize.options.logging
    }, options || {})

    // Postgres requires a special SQL command for enums
    if (self.sequelize.options.dialect === "postgres") {
      var promises = []
        // For backwards-compatibility, public schemas don't need to
        // explicitly state their schema when creating a new enum type
        , getTableName = (!options || !options.schema || options.schema === "public" ? '' : options.schema + '_') + tableName

      for (i = 0; i < keyLen; i++) {
        if (attributes[keys[i]].toString().match(/^ENUM\(/) || attributes[keys[i]].toString() === "ENUM" || (attributes[keys[i]].type && attributes[keys[i]].type.toString() === "ENUM")) {
          sql = self.QueryGenerator.pgListEnums(getTableName, keys[i], options)
          promises.push(self.sequelize.query(sql, null, { plain: true, raw: true, type: QueryTypes.SELECT, logging: options.logging }))
        }
      }

      return Promise.all(promises).then(function(results) {
        var promises = []
          // Find the table that we're trying to create throgh DAOFactoryManager
          , daoTable = self.sequelize.daoFactoryManager.daos.filter(function(dao) { return dao.tableName === tableName })
          , enumIdx  = 0

        daoTable = daoTable.length > 0 ? daoTable[0] : null

        for (i = 0; i < keyLen; i++) {
          if (attributes[keys[i]].toString().match(/^ENUM\(/) || attributes[keys[i]].toString() === "ENUM" || (attributes[keys[i]].type && attributes[keys[i]].type.toString() === "ENUM")) {
            // If the enum type doesn't exist then create it
            if (!results[enumIdx]) {
              sql = self.QueryGenerator.pgEnum(getTableName, keys[i], attributes[keys[i]], options)
              promises.push(self.sequelize.query(sql, null, { raw: true, logging: options.logging }))
            } else if (!!results[enumIdx] && !!daoTable) {
              var enumVals = self.QueryGenerator.fromArray(results[enumIdx].enum_value)
                , vals = daoTable.rawAttributes[keys[i]].values

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

                if (enumVals.indexOf(value) === -1) {
                  if (!!vals[idx+1]) {
                    options.before = vals[idx+1]
                  }
                  else if (!!vals[idx-1]) {
                    options.after = vals[idx-1]
                  }

                  promises.push(self.sequelize.query(self.QueryGenerator.pgEnumAdd(getTableName, keys[i], value, options)))
                }
              })
              enumIdx++
            }
          }
        }

        attributes = self.QueryGenerator.attributesToSQL(attributeHashes)
        sql = self.QueryGenerator.createTableQuery(tableName, attributes, options)

        return Promise.all(promises).then(function() {
          return self.sequelize.query(sql, null, options)
        })
      })
    } else {
      attributes = self.QueryGenerator.attributesToSQL(attributeHashes)
      sql = self.QueryGenerator.createTableQuery(tableName, attributes, options)

      return self.sequelize.query(sql, null, options)
    }
  }
Example #14
0
 self.sequelize.query(showSchemasSql, null, options).success(function(schemaNames) {
   self.emit('showAllSchemas', null)
   emitter.emit('success', Utils._.flatten(Utils._.map(schemaNames, function(value){ return (!!value.schema_name ? value.schema_name : value) })))
 }).error(function(err) {
Example #15
0
 it('camelizes if second param is true', function(done) {
   expect(Utils._.camelizeIf('foo_bar', true)).to.equal('fooBar')
   done()
 })
Example #16
0
  QueryInterface.prototype.createTable = function(tableName, attributes, options) {
    var attributeHashes   = {}
      , dataTypeValues    = Utils._.values(DataTypes)
      , keys              = Object.keys(attributes)
      , keyLen            = keys.length
      , self              = this
      , sql               = ''
      , i                 = 0

    for (i = 0; i < keyLen; i++) {
      if (dataTypeValues.indexOf(attributes[keys[i]]) > -1) {
        attributeHashes[keys[i]] = { type: attributes[keys[i]], allowNull: true }
      } else {
        attributeHashes[keys[i]] = attributes[keys[i]]
      }
    }

    options = Utils._.extend({
      logging: this.sequelize.options.logging
    }, options || {})

    return new Utils.CustomEventEmitter(function(emitter) {
      // Postgres requires a special SQL command for enums
      if (self.sequelize.options.dialect === "postgres") {
        var chainer = new Utils.QueryChainer()
          // For backwards-compatibility, public schemas don't need to
          // explicitly state their schema when creating a new enum type
          , getTableName = (!options || !options.schema || options.schema === "public" ? '' : options.schema + '_') + tableName

        for (i = 0; i < keyLen; i++) {
          if (attributes[keys[i]].toString().match(/^ENUM\(/)) {
            sql = self.QueryGenerator.pgListEnums(getTableName, keys[i], options)
            chainer.add(self.sequelize.query(sql, null, { plain: true, raw: true, type: 'SELECT', logging: options.logging }))
          }
        }

        chainer.runSerially().success(function(results) {
          var chainer2 = new Utils.QueryChainer()
            // Find the table that we're trying to create throgh DAOFactoryManager
            , daoTable = self.sequelize.daoFactoryManager.daos.filter(function(dao) { return dao.tableName === tableName })
            , enumIdx  = 0

          daoTable = daoTable.length > 0 ? daoTable[0] : null

          for (i = 0; i < keyLen; i++) {
            if (attributes[keys[i]].toString().match(/^ENUM\(/)) {
              // If the enum type doesn't exist then create it
              if (!results[enumIdx]) {
                sql = self.QueryGenerator.pgEnum(getTableName, keys[i], attributes[keys[i]], options)
                chainer2.add(self.sequelize.query(sql, null, { raw: true, logging: options.logging }))
              } else if (!!results[enumIdx] && !!daoTable) {
                var enumVals = self.QueryGenerator.fromArray(results[enumIdx].enum_value)
                  , vals = daoTable.rawAttributes[keys[i]].values

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

                  if (enumVals.indexOf(value) === -1) {
                    if (!!vals[idx+1]) {
                      options.before = vals[idx+1]
                    }
                    else if (!!vals[idx-1]) {
                      options.after = vals[idx-1]
                    }

                    chainer2.add(self.sequelize.query(self.QueryGenerator.pgEnumAdd(getTableName, keys[i], value, options)))
                  }
                })
              }
            }
          }

          attributes = self.QueryGenerator.attributesToSQL(attributeHashes)
          sql = self.QueryGenerator.createTableQuery(tableName, attributes, options)

          chainer2.run().success(function() {
            queryAndEmit
              .call(self, sql, 'createTable', options)
              .success(function(res) {
                self.emit('createTable', null)
                emitter.emit('success', res)
              })
              .error(function(err) {
                self.emit('createTable', err)
                emitter.emit('error', err)
              })
              .on('sql', function(sql)  {
                emitter.emit('sql', sql)
              })
          }).error(function(err) {
            emitter.emit('error', err)
          }).on('sql', function(sql) {
            emitter.emit('sql', sql)
          })
        })
      } else {
        attributes = self.QueryGenerator.attributesToSQL(attributeHashes)
        sql = self.QueryGenerator.createTableQuery(tableName, attributes, options)

        queryAndEmit.call(self, sql, 'createTable', options).success(function(results) {
          self.emit('createTable', null)
          emitter.emit('success', results)
        }).error(function(err) {
          self.emit('createTable', err)
          emitter.emit('error', err)
        }).on('sql', function(sql) {
          emitter.emit('sql', sql)
        })
      }
    }).run()
  }
Example #17
0
 it('underscores if second param is true', function(done) {
   expect(Utils._.underscoredIf('fooBar', true)).to.equal('foo_bar')
   done()
 })
Example #18
0
 indexFields = Utils._.map(value.fields, function (field) {
   if (Utils._.isPlainObject(field)) {
     return field.attribute;
   }
   return field;
 });
Example #19
0
 it("doesn't underscore if second param is false", function(done) {
   expect(Utils._.underscoredIf('fooBar', false)).to.equal('fooBar')
   done()
 })
Example #20
0
 Object.keys(scopeObj).forEach(function(method) {
   if (typeof scopeObj[method] === 'number' || !Utils._.isEmpty(scopeObj[method])) {
     options[method] = scopeObj[method];
   }
 });
Example #21
0
  QueryInterface.prototype.bulkDelete = function(tableName, identifier, options) {
    var sql = this.QueryGenerator.deleteQuery(tableName, identifier, Utils._.defaults(options || {}, {limit: null}))

    return this.queryAndEmit([sql, null, options], 'bulkDelete', options)
  }
Example #22
0
 return self.sequelize.query(showTablesSql, null, options).then(function(tableNames) {
   return Utils._.flatten(tableNames);
 });
Example #23
0
  Migrator.prototype.migrate = function(options) {
    var self = this

    options = Utils._.extend({
      method: 'up'
    }, options || {})

    return new Utils.CustomEventEmitter(function(emitter) {
      self.getUndoneMigrations(function(err, migrations) {
        if (err) {
          emitter.emit('error', err)
        } else {
          var chainer = new Utils.QueryChainer()
            , from    = migrations[0]

          if (options.method === 'down') {
            migrations.reverse()
          }

          if (migrations.length === 0) {
            self.options.logging("There are no pending migrations.")
          } else {
            self.options.logging("Running migrations...")
          }

          migrations.forEach(function(migration) {
            var migrationTime

            chainer.add(migration, 'execute', [options], {
              before: function(migration) {
                if (self.options.logging !== false) {
                  self.options.logging(migration.filename)
                }
                migrationTime = process.hrtime()
              },

              after: function(migration) {
                migrationTime = process.hrtime(migrationTime)
                migrationTime = Math.round( (migrationTime[0] * 1000) + (migrationTime[1] / 1000000));

                if (self.options.logging !== false) {
                  self.options.logging('Completed in ' + migrationTime + 'ms')
                }
              },

              success: function(migration, callback) {
                if (options.method === 'down') {
                  deleteUndoneMigration.call(self, from, migration, callback)
                } else {
                  saveSuccessfulMigration.call(self, from, migration, callback)
                }
              }
            })
          })

          chainer
            .runSerially({ skipOnError: true })
            .success(function() { emitter.emit('success', null) })
            .error(function(err) { emitter.emit('error', err) })
        }
      })
    }).run()
  }