Подтвердить что ты не робот

Что происходит в файле конфигурации Sequelize?

Я только начинаю с Sequelize в Node.js и обнаруживаю, что документация действительно отсутствует. У меня есть модуль "db", в котором я подключаюсь к базе данных через Sequelize, и это читается в конфигурации из файла конфигурации приложения в ./config.json по отношению к корню моего проекта. Это вложенная конфигурация и вряд ли будет структурирована таким образом, что Sequelize хочет создать файл конфигурации для CLI.

Теперь я пытаюсь использовать миграции, и в документации делается ссылка на "файл конфигурации". Я знаю, что могу установить путь к этому файлу конфигурации, но что, черт возьми, я в него вставляю? Он не документирован нигде (что я видел).

4b9b3361

Ответ 1

Я прочитал код, чтобы понять это. Это плоская структура. Я просто перестраиваю конфигурацию в другом формате из моей собственной конфигурации.

var config = require('./config');

module.exports = {
  database: config.database.name,
  username: config.database.user,
  password: config.database.pass,
  dialect: 'postgres',
  dialectModulePath: 'pg.js',
  host: config.database.host,
  port: config.database.port,
  pool: config.database.pool
};

Ответ 2

В конфигурационный файл можно добавить больше вещей:

var sequelize = new Sequelize(config.database.dbName, config.database.master.user,     config.database.master.password, {
    dialect: config.database.protocol,
    port: config.database.port,
    host: config.database.master.host,
    /* You could setup replication as well
    replication: {
     read: [
     {
       host: config.database.master.host,
       username: config.database.master.host,
       password: config.database.master.password
     },
     {
       host: config.database.master.host,
       username: config.database.master.host,
       password: config.database.master.password
     }
     ],
     write: {
       host: config.database.master.host,
       username: config.database.master.host,
       password: config.database.master.password
     }
     */
    },
    pool: {
        maxConnections: config.database.pool.maxConnections,
        maxIdleTime: config.database.pool.maxIdleTime
    },

    logging: false,
    define: {
        underscored: false,
        freezeTableName: false,
        syncOnAssociation: true,
        charset: 'utf8',
        collate: 'utf8_general_ci',
        classMethods: {method1: function() {}},
        instanceMethods: {method2: function() {}},
        timestamps: true
        schema: "prefix"
    }
}),

Ответ 3

Я думаю, что документация для конструктора описывает все опции, доступные в конфиге. По состоянию на 12/1/2018 (Sequelize v4, текущий выпуск). *

options.host    String   optional default: 'localhost' The host of the relational database.

options.port    Integer  optional default: The port of the relational database.

options.username    String   optional default: null The username which is used to authenticate against the database.

options.password    String   optional default: null The password which is used to authenticate against the database.

options.database    String   optional default: null The name of the database

options.dialect String   optional The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql.

options.dialectModulePath   String   optional default: null If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'pg.js' here

options.dialectOptions  Object   optional An object of additional options, which are passed directly to the connection library

options.storage String   optional Only used by sqlite. Defaults to ':memory:'

options.protocol    String   optional default: 'tcp' The protocol of the relational database.

options.define  Object   optional default: {} Default options for model definitions. See sequelize.define for options

options.query   Object   optional default: {} Default options for sequelize.query

options.set Object   optional default: {} Default options for sequelize.set

options.sync    Object   optional default: {} Default options for sequelize.sync

options.timezone    String   optional default: '+00:00' The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.

options.logging Function     optional default: console.log A function that gets executed every time Sequelize would log something.

options.benchmark   Boolean  optional default: false Pass query execution time in milliseconds as second argument to logging function (options.logging).

options.omitNull    Boolean  optional default: false A flag that defines if null values should be passed to SQL queries or not.

options.native  Boolean  optional default: false A flag that defines if native library shall be used or not. Currently only has an effect for postgres

options.replication Boolean  optional default: false Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: host, port, username, password, database

options.pool    Object   optional sequelize connection pool configuration

options.pool.max    Integer  optional default: 5 Maximum number of connection in pool

options.pool.min    Integer  optional default: 0 Minimum number of connection in pool

options.pool.idle   Integer  optional default: 10000 The maximum time, in milliseconds, that a connection can be idle before being released. Use with combination of evict for proper working, for more details read https://github.com/coopernurse/node-pool/issues/178#issuecomment-327110870

options.pool.acquire    Integer  optional default: 10000 The maximum time, in milliseconds, that pool will try to get connection before throwing error

options.pool.evict  Integer  optional default: 10000 The time interval, in milliseconds, for evicting stale connections. Set it to 0 to disable this feature.

options.pool.handleDisconnects  Boolean  optional default: true Controls if pool should handle connection disconnect automatically without throwing errors

options.pool.validate   Function     optional A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected

options.quoteIdentifiers    Boolean  optional default: true Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them. WARNING: Setting this to false may expose vulnerabilities and is not recommended!

options.transactionType String   optional default: 'DEFERRED' Set the default transaction type. See Sequelize.Transaction.TYPES for possible options. Sqlite only.

options.isolationLevel  String   optional Set the default transaction isolation level. See Sequelize.Transaction.ISOLATION_LEVELS for possible options.

options.retry   Object   optional Set of flags that control when a query is automatically retried.

options.retry.match Array    optional Only retry a query if the error matches one of these strings.

options.retry.max   Integer  optional How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.

options.typeValidation  Boolean  optional default: false Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like.

options.operatorsAliases    Object | Boolean     optional default: true String based operator alias, default value is true which will enable all operators alias. Pass object to limit set of aliased operators or false to disable completely.

* Обратите внимание, что многие из этих свойств, таких как pool и logging, упоминаются в других ответах. Ответ @siyang описывает свойство define напрямую, но документация также охватывает это (см. свойство options)

Кстати, я пытался решить проблему "Время ожидания ресурса" при использовании Sequelize для создания некоторых обновлений PostgreSQL, поэтому я поделился этими ссылками с документацией; настройка свойства pool может помочь вам, если у вас есть эта проблема.