Giter Club home page Giter Club logo

sails-hook-sequelize's Introduction

sails-hook-sequelize

Sails.js hook to use sequelize ORM

NPM version Build Status Code coverage MIT License Known Vulnerabilities

Installation

Install this hook with:

$ npm install sails-hook-sequelize --save

Configuration

.sailsrc

{
  "hooks": {
    "orm": false,
    "pubsub": false
  }
}

Also you can set some parameters in config/sequelize.js to override defaults.

module.exports.sequelize = {
    "clsNamespace": "myAppCLSNamespace",
    "exposeToGlobal": true
};

Connections

Sequelize connection.

Important note: dialect keyword MUST be present in connection or connection.options.

somePostgresqlServer: {
  user: 'postgres',
  password: '',
  database: 'sequelize',
  dialect: 'postgres',
  options: {
    dialect: 'postgres',
    host   : 'localhost',
    port   : 5432,
    logging: console.log        // or specify sails log level to use ('info', 'warn', 'verbose', etc)
  }
}

Models

Sequelize model definition models/user.js

module.exports = {
  attributes: {
    name: {
      type: Sequelize.STRING,
      allowNull: false
    },
    age: {
      type: Sequelize.INTEGER
    }
  },
  associations: function() {
    user.hasMany(image, {
      foreignKey: {
        name: 'owner',
        allowNull: false
      }
    });
  },
  defaultScope: function() {
    return {
      include: [
        {model: image, as: 'images'}
      ]
    }
  },
  options: {                                  // Options must exists (even if empty) in order to consider this model a Sequelize model
    tableName: 'user',
    classMethods: {},
    instanceMethods: {},
    hooks: {},
    scopes: {},
  },
  connection: 'NotDefaultModelsConnection'    // Can be omitted, so default sails.config.models.connection will be used
};

Contributors

This project was originally created by Gergely Munkácsy (@festo). Now is maintained by Konstantin Burkalev (@KSDaemon).

License

MIT

Thanks JetBrains for support! Best IDEs for every language!

JetBrains

sails-hook-sequelize's People

Contributors

abelosorio avatar damienmarble avatar dependabot[bot] avatar dnizovtsev avatar festo avatar josearaujodev avatar ksdaemon avatar loulin avatar mrded avatar pretender avatar tmandry avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

sails-hook-sequelize's Issues

Sequelize should be a peerDependency

Hello,

First of all, thanks for all the great work on the plugin.

I have been facing an issue with the plugin and sequelize, in specific when using functions or literals with custom names.

The issue that I'm having is that I'm currently using Typescript / ES6 signature.

So to create my queries or apply a Sequelize function I use something like:

import { fn as seqFn, literal as seqLiteral } from 'sequelize';
...
const count = seqFn('json_array_length', seqCast(seqCol('mycol'), 'json'));

So first of all, in order to be able to implement that notation I need to install a version of sequelize in my package.json.

Now in general, pretty much everything works good, until I reached this blocker when using custom named attributes.

const query = {
    attributes: [
             "attr1", "attr2", "attr3"
             [count, 'myCountResult'],
    ] 
}

This creates a custom query attribute mapping for the function result.

Steps to reproduce the behavior:

  1. Im currently using Sails 0.12
  2. When and where error is happening

Now when that executes generates an exception specifically in the file.

node_modules/sails-hook-sequelize/node_module/sequelize/lib/dialects/abstract/query-generator.js

Specifically in line 1426 } else if (!attr[0].includes('(') && !attr[0].includes(')')) {

The issue in specific occurs before reaching to that line the following validation should have occured:

if (attr[0] instanceof Utils.SequelizeMethod) {

But as I have 2 instances of sequelize node_modules/sequelize and node_modules/sails-hook-sequelize/node_modules/sequelize then the reference to the class is not the same.

I have fixed this temporarily by modifying the Sails-hook-sequelize package.json and moving the sequelize dependency as a peerDependency.

In this way both sails-hook-sequelize and my app can share the same sequelize instance and version.

A clear and concise description of what the bug is.

  1. Error description

Expected behavior

I should be able to use ES6 syntax and not rely on globals.
Also I should be able to use custom function named attributes.

Desktop (please complete the following information):

  • OS: Mac
  • Node.js 10.15
  • Sequelize version 5.21

Document clsNamespace

Your docs/README.md mention clsNamespace, but there's nothing that indicated what it means, nor why it should be set. The default (looking at code) seems to be sails-sequelize but the docs say myAppCLSNamespace

Bad documentation on the README.md file

Working with the relations between models, find out that the example that is given on the README file is not correct, it has associate as the key when it should be associations.

module.exports = {
  attributes: { ... },
  associations: function() {
      //   Model.reletionType(Model, opts );
       User.hasOne(Profile);
    });
  },
  ...
};

Log query

Tried to pass

options: { logging: true } 

to the connection, but I still don't get the executed query. How to show / log executed query?

The hook initializes only the default models connection, even if there are multiple connections defined in config.

I've defined 2 connections in the /config/connections.js file:

      monolithMysql: {
        user: 'store_app',
        database: 'store',
        dialect: 'mysql',
        options: {
          dialect: 'mysql',
          host: 'dockerhost',
          port: 3306,
          logging: console.log
        }
      },

      postgres: {
        user: 'user_app',
        database: 'user_authentication',
        dialect: 'postgres',
        options: {
          dialect: 'postgres',
          host: 'dockerhost',
          port: 8201,
          logging: console.log
        }
      }

and in the different models I've put the property connection, so that they're distinguished, as follows:

/**
  * model User
  */
    module.exports = {

      options: {
        connection: 'monolithMysql',
        ...
/**
  * model Token
  */
    module.exports = {

      options: {
        connection: 'postgres',
        ...

In /config/models.js I set as default connection the monolithMysql one. If I comment out or do not specify the connection property in /config/models.js then Sequelize hook fails to load.
But that should be overridden by the connection property, if specified in the models.

Nevertheless, when trying to query models that have, eg. postgres as connection it still queries them in the MySQL DB, and obviously fails... If I set postgres as default connection, then it will always query in the Postgres DB connection, no matter what the local connection property of the different models says.

After some debugging in the module code, I found out that it initializes only 1 instance of Sequelize - an instance with the default connection, specified in /config/models.js

Dialect: mysql and postgres
Sequelize version: ^3.21.0

Sequelize Hooks Support

It would be nice to add Sequelize Hooks to models:

module.exports = {
  attributes: {
    username: DataTypes.STRING,
    mood: {
      type: DataTypes.ENUM,
      values: ['happy', 'sad', 'neutral']
    }
  },
  hooks: function() {
    beforeValidate: (user, options) => {
      user.mood = 'happy';
    },
    afterValidate: (user, options) => {
      user.username = 'Toni';
    }
  },
};

Allow sharing of model definitions among datasources

Is your feature request related to a problem? Please describe.
My organization is creating a multitenant application using Sails, with Sequelize as our ORM to connect to existing database(s). Our goal is for new tenants with separate datasources to be able to be added purely through configuration changes. However, currently each model can be associated with only a single Sequelize instance.

Describe the solution you'd like
A way to namespace Models so that model multiple instances which function identically but point to different datasources can be created.

Describe alternatives you've considered
We could create separate model definitions for each tenant and explicitly name which datasource to associate with, but this violates our configuration-only requirement and will caused an ever-increasing maintenance burden as the number of models, tenants and places where they are used grow. (x models times y tenants times z places where a model is used and which one to use must be determined)

SailsJS v1 - Using custom datastore

I am having some issues with Sails v1 getting any datastore other than 'default' to function.

I have configured config\datastores.js as follows:

module.exports.datastores = {

  default: {

    user: 'user',
    password: 'pass',
    database: 'db',
    dialect: 'mssql',
    options: {
      dialect: 'mssql',
      host   : 'host.domain.com',
      port   : 1433,
      logging: console.log        // or specify sails log level to use ('info', 'warn', 'verbose', etc)
    }
  },


  test: {
    user: 'user',
    password: 'pass',
    database: 'db2',
    dialect: 'mssql',
    options: {
      dialect: 'mssql',
      host   : 'host2.domain.com',
      port   : 1433,
      logging: console.log        // or specify sails log level to use ('info', 'warn', 'verbose', etc)
    }
  }

};

I have configured my model as follows:

module.exports = {
  attributes: {
    id: {
      type: Sequelize.STRING,
      allowNull: false,
      primaryKey: true,
      field: 'proid'
    },
    name: {
      type: Sequelize.STRING,
      field: 'name'
    }
  },
  options: {
    tableName: 'inwork',
    classMethods: {},
    instanceMethods: {},
    hooks: {},
    scopes: {},
    connection: 'test',    // Can be omitted, so default sails.config.models.connection will be used
    timestamps: false
  }
};

A custom controller action and route is in place, which is working as expected, however the query fails since the default datastore is the only one being used. Due to the 'connection' option within models, it would appear that we should be able to use custom datastores, I'm just not sure what to change so that I stop reading the default store only, or if this is a bug with the current version.

Error: Callback was already called

When you set multiple database connections throw Error: Callback was already called. I think that the problem is in line 203 Promise.all(syncTasks).then(() => next()).catch(e => next(e));, it must be out of for (connectionName in datastores) statament scope.
Regards

Blueprint APIs are not working after installing sails-hook-sequelize

I am getting below warning after installing this package, '/user' is not working

warn: Ignored attempt to bind route (/offices/find) to unknown action :: offices/find
 warn: Ignored attempt to bind route (/offices/find/:id) to unknown action :: offices/findOne
 warn: Ignored attempt to bind route (/offices/create) to unknown action :: offices/create
 warn: Ignored attempt to bind route (/offices/update/:id) to unknown action :: offices/update
 warn: Ignored attempt to bind route (/offices/destroy/:id) to unknown action :: offices/destroy
 warn: Ignored attempt to bind route (/user/find) to unknown action :: user/find
 warn: Ignored attempt to bind route (/user/find/:id) to unknown action :: user/findOne
 warn: Ignored attempt to bind route (/user/create) to unknown action :: user/create
 warn: Ignored attempt to bind route (/user/update/:id) to unknown action :: user/update
 warn: Ignored attempt to bind route (/user/destroy/:id) to unknown action :: user/destroy

Sails lift hook load fail

Sails version: 1.0.0-42
sails-hook-sequelize: 1.1.1

Sails fails on lift.

log:
Using default connection named default
verbo: Thu, 14 Dec 2017 17:48:42 GMT sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators at node_modules\sequelize\lib\sequelize.js:236:13
Exposing Sequelize and Sequelize connections globally
error: A hook (sequelize) failed to load!
verbo: Loading model 'Titles'
verbo: sockets hook loaded successfully. (34ms)
verbo: Lowering sails...
error: Failed to lift app: TypeError: Cannot read property 'connection' of undefined
at Hook.defineModels (E:\c2c-apiProject\node_modules\sails-hook-sequelize\index.js:112:51)
at Hook.wrapper [as defineModels] (E:\c2c-apiProject\node_modules@sailshq\lodash\lib\index.js:3250:19)
at sails.modules.loadModels (E:\c2c-apiProject\node_modules\sails-hook-sequelize\index.js:42:22)
at E:\c2c-apiProject\node_modules\sails\lib\hooks\moduleloader\index.js:326:18
at E:\c2c-apiProject\node_modules\sails\lib\hooks\moduleloader\index.js:622:14
at helpBuildDictionary (E:\c2c-apiProject\node_modules\include-all\lib\help-build-dictionary.js:135:10)
at Function.module.exports.optional (E:\c2c-apiProject\node_modules\include-all\index.js:67:10)
at E:\c2c-apiProject\node_modules\sails\lib\hooks\moduleloader\index.js:314:20
at helpBuildDictionary (E:\c2c-apiProject\node_modules\include-all\lib\help-build-dictionary.js:135:10)
at Function.module.exports.optional (E:\c2c-apiProject\node_modules\include-all\index.js:67:10)
at Hook.loadModels (E:\c2c-apiProject\node_modules\sails\lib\hooks\moduleloader\index.js:304:18)
at Hook.wrapper [as loadModels] (E:\c2c-apiProject\node_modules@sailshq\lodash\lib\index.js:3250:19)
at Hook.reload (E:\c2c-apiProject\node_modules\sails-hook-sequelize\index.js:36:34)
at Hook.wrapper [as reload] (E:\c2c-apiProject\node_modules@sailshq\lodash\lib\index.js:3250:19)
at Hook.initialize (E:\c2c-apiProject\node_modules\sails-hook-sequelize\index.js:21:18)
at Hook.wrapper [as initialize] (E:\c2c-apiProject\node_modules@sailshq\lodash\lib\index.js:3250:19)
at E:\c2c-apiProject\node_modules\sails\lib\hooks\index.js:106:18
at E:\c2c-apiProject\node_modules\sails\node_modules\async\dist\async.js:421:16
at processQueue (E:\c2c-apiProject\node_modules\sails\node_modules\async\dist\async.js:1565:20)
at taskComplete (E:\c2c-apiProject\node_modules\sails\node_modules\async\dist\async.js:1588:9)
at E:\c2c-apiProject\node_modules\sails\node_modules\async\dist\async.js:1612:17
at E:\c2c-apiProject\node_modules\sails\node_modules\async\dist\async.js:906:16
at Hook.loadModules (E:\c2c-apiProject\node_modules\sails\lib\hooks\index.js:156:14)
at Hook.wrapper [as loadModules] (E:\c2c-apiProject\node_modules@sailshq\lodash\lib\index.js:3250:19)
at modules (E:\c2c-apiProject\node_modules\sails\lib\hooks\index.js:83:25)
at runTask (E:\c2c-apiProject\node_modules\sails\node_modules\async\dist\async.js:1621:13)
at E:\c2c-apiProject\node_modules\sails\node_modules\async\dist\async.js:1559:13
at processQueue (E:\c2c-apiProject\node_modules\sails\node_modules\async\dist\async.js:1569:13)
at Object.auto (E:\c2c-apiProject\node_modules\sails\node_modules\async\dist\async.js:1555:5)
at Hook.load (E:\c2c-apiProject\node_modules\sails\lib\hooks\index.js:77:13)
at Hook.wrapper [as load] (E:\c2c-apiProject\node_modules@sailshq\lodash\lib\index.js:3250:19)
at loadHook (E:\c2c-apiProject\node_modules\sails\lib\app\private\loadHooks.js:208:17)
at E:\c2c-apiProject\node_modules\sails\lib\app\private\loadHooks.js:330:13
at E:\c2c-apiProject\node_modules\sails\node_modules\async\dist\async.js:3083:16

Postgres Schema migration throws unique constraint violation errors when multiple datasources are defined

Describe the bug
After adding a second datasource to the test configuration, I discovered that the schema migration was being run multiple times agains the same database.

To Reproduce
Steps to reproduce the behavior:

  1. Sails configuration samples

datasources.js

somePostgresqlServer: {
        user: 'postgres',
        password: '',
        database: 'sequelize',
        dialect: 'postgres',
        options: {
            dialect: 'postgres',
            host   : 'localhost',
            port   : 5432,
            logging: 'verbose'
        }
    },
    anotherPostgresqlServer: {
        user: 'postgres',
        password: '',
        database: 'sequelize2',
        dialect: 'postgres',
        options: {
            dialect: 'postgres',
            host   : 'localhost',
            port   : 5432,
            logging: 'verbose'
        }
    },

The issue is caused by this section in the migrateSchemas method:

                for (connectionName in datastores) {
                    connectionDescription = datastores[connectionName];

                    // Skip waterline connections
                    if (connectionDescription.adapter) {
                        continue;
                    }

                    sails.log.verbose('Migrating schema in \'' + connectionName + '\' connection');

                    if (connectionDescription.dialect === 'postgres') {

                        syncTasks.push(connections[connectionName].showAllSchemas().then(schemas => {
                            let modelName, modelDef, tableSchema;

                            for (modelName in models) {
                                modelDef = models[modelName];
                                tableSchema = modelDef.options.schema || '';

                                if (tableSchema !== '' && schemas.indexOf(tableSchema) < 0) { // there is no schema in db for model
                                    connections[connectionName].createSchema(tableSchema);
                                    schemas.push(tableSchema);
                                }
                            }

                            return connections[*connectionName*].sync({ force: forceSyncFlag, alter: alterFlag });
                        }));

                    } else {
                        syncTasks.push(connections[connectionName].sync({ force: forceSyncFlag, alter: alterFlag }));
                    }
                }

By the time the then handler on showAllSchemas() is called, iteration over datastores has completed, meaning that inside the handler connectionName will always be whatever the last iterated value was.

Sync is causing an error when I start sails for a second time

Describe the bug
When I start the server for a second time I get:
SequelizeDatabaseError: relation "email_unique_idx" already exists

To Reproduce
Just start the app two times

Expected behavior
To have a clean start without errors

Screenshots
image

Desktop (please complete the following information):

  • OS: Mac Os High Sierra
  • Node.js version 10.1.0
  • Sequelize version 4.38.0

Additional context
Seems to be related with: sequelize/sequelize#7606
But I'n not sure if for any reason sync is being called twice as by some config of sails v1 (sequelize/sequelize#7606 (comment))

How to do raw SQL queries to database?

I'm looking for a way to access sequelize.query to make a native sql query.

As I understand sails-hook-sequelize initialises a pool connection with database, and it should be possible to reuse it for own needs.

Can you please point me how to do that?

Thank you.

how to use pubSub

In your sailsrc pubSub hooks are disabled (as they can't be run without the orm hook). Is there a possibility to still use pubSub together with sequelize?

SequelizeUniqueConstraintError: Validation error

Sails throws this when running my mocha tests (using npm start):

Error: Callback was already called.
    at node_modules/sails/node_modules/async/dist/async.js:903:32
    at node_modules/sails/lib/app/private/loadHooks.js:218:46
    at node_modules/async-listener/glue.js:188:31
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
SequelizeUniqueConstraintError: Validation error
    at Query.formatError (node_modules/sequelize/lib/dialects/postgres/query.js:325:18)
    at Result.query.on.err (node_modules/sequelize/lib/dialects/postgres/query.js:93:21)
    at Result.Query.handleError (node_modules/pg/lib/query.js:163:8)
    at Client.<anonymous> (node_modules/pg/lib/client.js:188:26)
    at Socket.<anonymous> (node_modules/pg/lib/connection.js:133:12)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at Socket.Readable.push (_stream_readable.js:208:10)
    at TCP.onread [as _originalOnread] (net.js:594:20)
    at TCP.onread (node_modules/async-listener/glue.js:188:31)

These tests are pretty much empty since it's a brand new project. The only test is this:

require('../../bootstrap.test');

describe('RootService', function () {
  it('Basic test',
    function (done) {
      assert.equal(0, 0);
      done();
    });
});

Though running the app itself, using npm start works, but I've not yet tried to do anything once lifted, so I don't know if something won't work.

The only model so far is Root.js, which as you can tell is unused:

module.exports = {

  attributes: {
    description: {
      type: Sequelize.STRING,
      allowNull: false
    }
  },

  associations: function () {
  },

  options: {
    tableName: 'Root',
    classMethods: {},
    instanceMethods: {},
    hooks: {}
  }
};

Thanks in advance

Dialect needs to be explicitly supplied as of v4.0.0

shows error below,

error: A hook (`sequelize`) failed to load!
verbose: Lowering sails...
verbose: Shutting down HTTP server...
verbose: HTTP server shut down successfully.
error: Error: Dialect needs to be explicitly supplied as of v4.0.0
    at new Sequelize

But when i downgrade to npm i [email protected], it works fine.

Can I set raw: true by default on all queries?

I'm running sails console and some CRUD operations to test if sequelize is working with sails, e.g. User.findOne({where: {id: myId}}).then(function(result) { console.log(result); }). I expect the result to contain only data retrieved from the db, instead of all data from the promise. I know I can do it by adding raw: true to the query but is there anyway to set it by default?

Use sqlite for tests

Just noticed that you use Postgres to run tests. Are there any reasons to use it over SQLite?

Using SQLite will simplify test environment. It will allow you to run tests without having a "real" database.

sequelize not found in controller

When I create a POST request (adding user information from a form), I route that to the corresponding controller, which does the following:

sequelize.transaction(t => { ... }

at which point fails, sending back a 500 error saying
error: Sending 500 ("Server Error") response: ReferenceError: sequelize is not defined

Support Sequelize 5

Is your feature request related to a problem? Please describe.
Hello Guys,

First of all, thanks a lot for all the work put into the library. I have been using it for a while, and has been working really great.

Describe the solution you'd like
As you may know recently Sequelize 5 was release and I was looking to upgrade, but I would like to confirm if the library will be able to handle it.
Im not completely aware of the code changes in sequelize regarding at least the model definitions, I was quickly looking at least some changes on the TS typings, and saw some usage of Classes which should be great to implement, but at least basic support will be welcome.

Thanks.

Table schema changes are not updating

I was trying to update the model, but after re-lifting the sails server, it is not getting updated in the database. Because it was trying to execute the create query instead of update schema even if the table exists also. Please try to suggest an immediate fix.

Other fields not accessible for custom validations

I'm trying to create a custom validation like so.

module.exports = {
    attributes : {
        startDate : {
            field     : 'start_date',
            type      : 'DATETIME',
            allowNull : false,
            validate  : {
                isValid : async (value) => {
                    sails.log.info(this.endDate);
                },
            },
        },
        endDate : {
            field     : 'end_date',
            type      : 'DATETIME',
            allowNull : false,
            validate  : {
                isValid : async (value) => {
                    // Do something
                },
            },
        },
    },
    associations : function() {},
    defaultScope : function() {},
    options      : {
        tableName       : 'campaigns',
        classMethods    : {},
        instanceMethods : {},
        validate : {
            isStartDateValid : () => {
                console.log(this.startDate); // prints undefined
            },
        },
        scopes : {},
    },
};

Is there a way to access other fields inside custom validations like the samples here: https://sequelize.org/docs/v6/core-concepts/validations-and-constraints/#per-attribute-validations

Expected behavior
Should be able to access other fields for custom validations

Desktop (please complete the following information):

  • OS: Mac
  • Node.js version: 18.12.1
  • Sails version: 1.5.3
  • Sails-hook-sequelize version: 2.0.0

No way to config sequelize logging

Hi all, I wonder why logging configuration is hard code to sails.log.verbose (file index.js)

if (connection.options == null) {
  connection.options = {};
}
connection.options.logging = sails.log.verbose;

It means there is no way to config logging for sequelize

Sequelize CLI support

I'm trying to use Sequelize CLI with sails, and then I run sequelize db:drop - it gives me an error:

Sequelize CLI [Node: 8.7.0, CLI: 3.0.0, ORM: 4.13.6]

WARNING: This version of Sequelize CLI is not fully compatible with Sequelize v4. https://github.com/sequelize/cli#sequelize-support

Loaded configuration file "config/sequelize.js".

ERROR: Dialect undefined does not support db:create / db:drop commands

It happens because it doesn't understand that my database settings are defended in config/datastores.js and config/env/*.js files, under sails.config.connections || sails.config.datastores variables.

Sails itself does understand it, thanks to sails-hook-sequelize, but sequelize-cli doesn't.

I can solve that problem with following hack in config/sequelize.js:

var path = require('path');

var config = require(path.resolve('config/env', process.env.NODE_ENV || 'development')); 

var datastore = config.datastores.default;

module.exports = Object.assign(datastore, { charset: 'utf8' }); 

However I believe, it would be nice if sails-hook-sequelize supports sequelize-cli as well.

Model is not defined.

why can't it see the Role model? been looking everywhere for the solution. do i need to import the model everytime? on the other project i inherited, i can't seem to find any require('path/to/model')

  User.belongsTo(
    Role,
    {
      foreignKey: {
        allowNull: false,
        field: 'role_id'
      }
    }
};```

error: Must contain an `adapter` key referencing the adapter to use.

If I leave out the keyword "adapter" from connection configuration, I get the error as described in the title when using the "npm test" command. To clarify the situation, "sails lift" works correctly. This error occurs only when I try to run my tests.

I'm using sails version 0.12.0-rc4

Working along with waterline

I have a big project built on top of Sails/Waterline. Now I need to move from waterline to sequelize. I want to refactor my models one by one, but I can`t use Sequelize hook with default Sails orm enabled, because orm try to initialize Sequelize models too. Need some method for initialization of sequelize models after it was initialized in waterline.

Warning on Model.save

When I use Model.save() I receive this warning message:

Warning: a promise was created in a  handler but was not returned from it
    at Instance.save (/projectpath/node_modules/sails-hook-sequelize/node_modules/sequelize/lib/instance.js:554:18)
    at Model.create (/projectpath/node_modules/sails-hook-sequelize/node_modules/sequelize/lib/model.js:1798:6)
    at /projectpath/api/models/Session.js:27:29
    at module.exports.options.classMethods.generate (/projectpath/api/models/Session.js:25:24)
    at null.<anonymous> (/projectpath/api/controllers/AuthController.js:15:33)
    at null.<anonymous> (/projectpath/node_modules/sails-hook-sequelize/node_modules/continuation-local-storage/context.js:74:17)
    at Immediate._onImmediate (/projectpath/node_modules/sails-hook-sequelize/node_modules/continuation-local-storage/node_modules/async-listener/glue.js:188:31)
    at processImmediate [as _immediateCallback] (timers.js:367:17)
From previous event:
    at Promise.then (/projectpath/node_modules/sails-hook-sequelize/node_modules/sequelize/lib/promise.js:21:17)
    at Object.module.exports.login (/projectpath/api/controllers/AuthController.js:10:62)
    at bound (/usr/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at routeTargetFnWrapper (/usr/lib/node_modules/sails/lib/router/bind.js:179:5)
    at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
    at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
    at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:135:11)
    at pass (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
    at nextRoute (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
    at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:167:11)
    at /usr/lib/node_modules/sails/lib/router/bind.js:187:7
    at alwaysAllow (/usr/lib/node_modules/sails/lib/hooks/policies/index.js:207:11)
    at routeTargetFnWrapper (/usr/lib/node_modules/sails/lib/router/bind.js:179:5)
    at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
    at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
    at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:135:11)
    at pass (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
    at nextRoute (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
    at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:167:11)
    at /usr/lib/node_modules/sails/lib/router/bind.js:187:7
    at _sendHeaders (/usr/lib/node_modules/sails/lib/hooks/cors/index.js:195:7)
    at routeTargetFnWrapper (/usr/lib/node_modules/sails/lib/router/bind.js:179:5)
    at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
    at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
    at pass (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
    at nextRoute (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
    at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:167:11)
    at /usr/lib/node_modules/sails/lib/router/bind.js:187:7
    at sails.router.bind._middlewareType (/usr/lib/node_modules/sails/lib/hooks/csrf/index.js:114:11)
    at routeTargetFnWrapper (/usr/lib/node_modules/sails/lib/router/bind.js:179:5)
    at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:164:37)

Is possible to suppress this warning?

Sails.js v1 support

Hello,

It looks like this module support 0.12 version of sails only.
When will it support v1?

Thanks.

Problem if datastores > 1

Hi,

You have a problem of synchronization on the name connection, in index.js (line 256):

if (connectionDescription.dialect === 'postgres') {

    syncTasks.push(connections[connectionName].showAllSchemas().then(schemas => {
        let modelName, modelDef, tableSchema;

        for (modelName in models) {
            modelDef = models[modelName];
            tableSchema = modelDef.options.schema || '';

            if (tableSchema !== '' && schemas.indexOf(tableSchema) < 0) { // there is no schema in db for model
                connections[connectionName].createSchema(tableSchema);
                schemas.push(tableSchema);
            }
        }

        return connections[connectionName].sync({ force: forceSyncFlag, alter: alterFlag });
    }));

} else {}

Since "syncTasks" can take some time, connectionName can contain a wrong value, in my case it contains the last item of the data array.
Your must replace by this :

if (connectionDescription.dialect === 'postgres') {
    let cn = connectionName
    syncTasks.push(connections[cn].showAllSchemas().then(schemas => {
        let modelName, modelDef, tableSchema;

        for (modelName in models) {
            modelDef = models[modelName];
            tableSchema = modelDef.options.schema || '';

            if (tableSchema !== '' && schemas.indexOf(tableSchema) < 0) { // there is no schema in db for model
                connections[cn].createSchema(tableSchema);
                schemas.push(tableSchema);
            }
        }

        return connections[cn].sync({ force: forceSyncFlag, alter: alterFlag });
    }));
} else {

For reproduction, you must have several datastore in file : config/datastores.js

module.exports.datastores = {

  sequelizeHost: {
    user: '',
    password: '',
    database: '',
    dialect: 'postgres',
    options: {
        dialect: 'postgres',
        host   : '',
        port   : x,
        logging: false,
        operatorsAliases: false,
        dialectOptions: {
          ssl: true
        }    
    }        
  },

  sequelizeDev: {
    adapter: {}, // force to skip
    user: '',
    password: '',
    database: '',
    options: {
        dialect: 'postgres',
        host   : 'localhost',
        port   : 5432,
        logging: false,
        operatorsAliases: false
    }
  },

  sequelizeTests: {
    adapter: {}, // force to skip
    user: '',
    password: '',
    database: '',
    options: {
        dialect: 'postgres',
        host   : 'localhost',
        port   : 5432,
        logging: false,
        operatorsAliases: false
    }
  }
};

and in the config/models .js :

connection: 'sequelizeHost'

So, it would be nice to have an option that would inhibit a connection (in order for it to work, I had to add -> adapter : {})

Model is not defined.

I followed all instructions.
And I created Post model and tried to retrieve all post records from the db table.

            .populate("responses")
            .exec(function(err, posts){
                if(err){
                    return res.send(err);
                }
                return res.send(JSON.stringify(posts));
            })```
Cannot read property 'define' of undefined

option bug fix

I found a options bug, following.

sails-hook-sequelize\index.js

image

Worked logging, after added line 126,127.
I could set options other than string type option.

Transactions

I couldn't create a transaction with this sequelize instance. How can i use sequelize transactions with sails-hook-sequelize?

TypeError: User.hasMany is not a function

TypeError: User.hasMany is not a function
at Object.User.associations (/srv/http/myapp/api/models/User.js:82:8)
at Hook.setAssociation (/srv/http/myapp/node_modules/sails-hook-sequelize/index.js:72:20)
at Hook.bound as setAssociation
at /srv/http/myapp/node_modules/sails-hook-sequelize/index.js:41:16
at /srv/http/myapp/node_modules/sails/lib/hooks/moduleloader/index.js:294:18
at /srv/http/myapp/node_modules/sails/lib/hooks/moduleloader/index.js:499:14
at buildDictionary (/srv/http/myapp/node_modules/sails-build-dictionary/index.js:134:9)
at Function.module.exports.optional (/srv/http/myapp/node_modules/sails-build-dictionary/index.js:160:9)
at /srv/http/myapp/node_modules/sails/lib/hooks/moduleloader/index.js:287:25
at buildDictionary (/srv/http/myapp/node_modules/sails-build-dictionary/index.js:134:9)
at Function.module.exports.optional (/srv/http/myapp/node_modules/sails-build-dictionary/index.js:160:9)
at Hook.loadModels (/srv/http/myapp/node_modules/sails/lib/hooks/moduleloader/index.js:279:23)
at Hook.bound as loadModels
at Hook.initialize (/srv/http/myapp/node_modules/sails-hook-sequelize/index.js:26:28)
at Hook.bound as initialize
at /srv/http/myapp/node_modules/sails/lib/hooks/index.js:75:14
at /srv/http/myapp/node_modules/sails/node_modules/async/lib/async.js:451:17
at /srv/http/myapp/node_modules/sails/node_modules/async/lib/async.js:441:17
at _each (/srv/http/myapp/node_modules/sails/node_modules/async/lib/async.js:46:13)
at Immediate.taskComplete (/srv/http/myapp/node_modules/sails/node_modules/async/lib/async.js:440:13)
at Immediate._onImmediate (/srv/http/myapp/node_modules/async-listener/glue.js:188:31)
at processImmediate as _immediateCallback

Error during lifting

Got the following error while lifted the app:

Executing (default): SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'information_schema' AND schema_name != 'public' AND schema_name !~ E'^pg_';
Executing (default): SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'information_schema' AND schema_name != 'public' AND schema_name !~ E'^pg_';
Executing (default): SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'information_schema' AND schema_name != 'public' AND schema_name !~ E'^pg_';
/Users/shepeliev/projects/rentloop-api/node_modules/sails/node_modules/async/lib/async.js:43
            if (fn === null) throw new Error("Callback was already called.");
                             ^

Error: Callback was already called.
  at /Users/shepeliev/projects/rentloop-api/node_modules/sails/node_modules/async/lib/async.js:43:36
  at /Users/shepeliev/projects/rentloop-api/node_modules/async-listener/glue.js:188:31
  at _combinedTickCallback (internal/process/next_tick.js:131:7)
  at process._tickDomainCallback [as _tickCallback] (internal/process/next_tick.js:218:9)

Please, need help ASAP 🙏

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.