不要怂,就是干,撸起袖子干!

Commit 8244a34e by Simon Schick Committed by GitHub

docs: asyncify (#12297)

1 parent b2bccb8a
...@@ -30,9 +30,8 @@ const Op = require('../operators'); ...@@ -30,9 +30,8 @@ const Op = require('../operators');
* All methods allow you to pass either a persisted instance, its primary key, or a mixture: * All methods allow you to pass either a persisted instance, its primary key, or a mixture:
* *
* ```js * ```js
* Project.create({ id: 11 }).then(project => { * const project = await Project.create({ id: 11 });
* user.addProjects([project, 12]); * await user.addProjects([project, 12]);
* });
* ``` * ```
* *
* If you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model: * If you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:
...@@ -46,10 +45,10 @@ const Op = require('../operators'); ...@@ -46,10 +45,10 @@ const Op = require('../operators');
* *
* Similarly, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model. * Similarly, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.
* ```js * ```js
* user.getProjects().then(projects => { * const projects = await user.getProjects();
* let p1 = projects[0] * const p1 = projects[0];
* p1.UserProjects.started // Is this project started yet? * p1.UserProjects.started // Is this project started yet?
* }) * })
* ``` * ```
* *
* In the API reference below, add the name of the association to the method, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`. * In the API reference below, add the name of the association to the method, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`.
......
...@@ -2027,13 +2027,11 @@ class Model { ...@@ -2027,13 +2027,11 @@ class Model {
* Find all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very useful for paging * Find all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very useful for paging
* *
* @example * @example
* Model.findAndCountAll({ * const result = await Model.findAndCountAll({
* where: ..., * where: ...,
* limit: 12, * limit: 12,
* offset: 12 * offset: 12
* }).then(result => { * });
* ...
* })
* *
* # In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return the total number of rows that matched your query. * # In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return the total number of rows that matched your query.
* *
......
...@@ -467,13 +467,9 @@ class Sequelize { ...@@ -467,13 +467,9 @@ class Sequelize {
* If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you can pass in a query type to make sequelize format the results: * If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you can pass in a query type to make sequelize format the results:
* *
* ```js * ```js
* sequelize.query('SELECT...').then(([results, metadata]) => { * const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring
* // Raw query - use then plus array spread
* });
* *
* sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(results => { * const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring
* // SELECT query - use then
* })
* ``` * ```
* *
* @param {string} sql * @param {string} sql
...@@ -1024,25 +1020,28 @@ class Sequelize { ...@@ -1024,25 +1020,28 @@ class Sequelize {
* If you have [CLS](https://github.com/Jeff-Lewis/cls-hooked) enabled, the transaction will automatically be passed to any query that runs within the callback * If you have [CLS](https://github.com/Jeff-Lewis/cls-hooked) enabled, the transaction will automatically be passed to any query that runs within the callback
* *
* @example * @example
* sequelize.transaction().then(transaction => { *
* return User.findOne(..., {transaction}) * try {
* .then(user => user.update(..., {transaction})) * const transaction = await sequelize.transaction();
* .then(() => transaction.commit()) * const user = await User.findOne(..., { transaction });
* .catch(() => transaction.rollback()); * await user.update(..., { transaction });
* }) * await transaction.commit();
* } catch {
* await transaction.rollback()
* }
* *
* @example <caption>A syntax for automatically committing or rolling back based on the promise chain resolution is also supported</caption> * @example <caption>A syntax for automatically committing or rolling back based on the promise chain resolution is also supported</caption>
* *
* sequelize.transaction(transaction => { // Note that we use a callback rather than a promise.then() * try {
* return User.findOne(..., {transaction}) * await sequelize.transaction(transaction => { // Note that we pass a callback rather than awaiting the call with no arguments
* .then(user => user.update(..., {transaction})) * const user = await User.findOne(..., {transaction});
* }).then(() => { * await user.update(..., {transaction});
* });
* // Committed * // Committed
* }).catch(err => { * } catch(err) {
* // Rolled back * // Rolled back
* console.error(err); * console.error(err);
* }); * }
*
* @example <caption>To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:</caption> * @example <caption>To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:</caption>
* *
* const cls = require('cls-hooked'); * const cls = require('cls-hooked');
......
...@@ -199,13 +199,14 @@ class Transaction { ...@@ -199,13 +199,14 @@ class Transaction {
* Pass in the desired level as the first argument: * Pass in the desired level as the first argument:
* *
* @example * @example
* return sequelize.transaction({type: Sequelize.Transaction.TYPES.EXCLUSIVE}, transaction => { * try {
* // your transactions * await sequelize.transaction({ type: Sequelize.Transaction.TYPES.EXCLUSIVE }, transaction => {
* }).then(result => { * // your transactions
* });
* // transaction has been committed. Do something after the commit if required. * // transaction has been committed. Do something after the commit if required.
* }).catch(err => { * } catch(err) {
* // do something with the err. * // do something with the err.
* }); * }
* *
* @property DEFERRED * @property DEFERRED
* @property IMMEDIATE * @property IMMEDIATE
...@@ -226,13 +227,14 @@ class Transaction { ...@@ -226,13 +227,14 @@ class Transaction {
* Pass in the desired level as the first argument: * Pass in the desired level as the first argument:
* *
* @example * @example
* return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => { * try {
* // your transactions * const result = await sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
* }).then(result => { * // your transactions
* });
* // transaction has been committed. Do something after the commit if required. * // transaction has been committed. Do something after the commit if required.
* }).catch(err => { * } catch(err) {
* // do something with the err. * // do something with the err.
* }); * }
* *
* @property READ_UNCOMMITTED * @property READ_UNCOMMITTED
* @property READ_COMMITTED * @property READ_COMMITTED
......
...@@ -1830,17 +1830,14 @@ export abstract class Model<T = any, T2 = any> extends Hooks { ...@@ -1830,17 +1830,14 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* rows matching your query. This is very usefull for paging * rows matching your query. This is very usefull for paging
* *
* ```js * ```js
* Model.findAndCountAll({ * const { rows, count } = await Model.findAndCountAll({
* where: ..., * where: ...,
* limit: 12, * limit: 12,
* offset: 12 * offset: 12
* }).then(result => { * });
* ...
* })
* ``` * ```
* In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return * In the above example, `rows` will contain rows 13 through 24, while `count` will return
* the * the total number of rows that matched your query.
* total number of rows that matched your query.
* *
* When you add includes, only those which are required (either because they have a where clause, or * When you add includes, only those which are required (either because they have a where clause, or
* because * because
...@@ -1922,7 +1919,7 @@ export abstract class Model<T = any, T2 = any> extends Hooks { ...@@ -1922,7 +1919,7 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
/** /**
* Find a row that matches the query, or build (but don't save) the row if none is found. * Find a row that matches the query, or build (but don't save) the row if none is found.
* The successfull result of the promise will be (instance, initialized) - Make sure to use `.then(([...]))` * The successful result of the promise will be [instance, initialized] - Make sure to use destructuring such as `const [instance, wasBuilt] = ...`
*/ */
public static findOrBuild<M extends Model>( public static findOrBuild<M extends Model>(
this: { new(): M } & typeof Model, this: { new(): M } & typeof Model,
...@@ -1931,7 +1928,7 @@ export abstract class Model<T = any, T2 = any> extends Hooks { ...@@ -1931,7 +1928,7 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
/** /**
* Find a row that matches the query, or build and save the row if none is found * Find a row that matches the query, or build and save the row if none is found
* The successful result of the promise will be (instance, created) - Make sure to use `.then(([...]))` * The successful result of the promise will be [instance, created] - Make sure to use destructuring such as `const [instance, wasCreated] = ...`
* *
* If no transaction is passed in the `options` object, a new transaction will be created internally, to * If no transaction is passed in the `options` object, a new transaction will be created internally, to
* prevent the race condition where a matching row is created by another connection after the find but * prevent the race condition where a matching row is created by another connection after the find but
...@@ -2446,10 +2443,9 @@ export abstract class Model<T = any, T2 = any> extends Hooks { ...@@ -2446,10 +2443,9 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* Similarily, when fetching through a join table with custom attributes, these attributes will be * Similarily, when fetching through a join table with custom attributes, these attributes will be
* available as an object with the name of the through model. * available as an object with the name of the through model.
* ```js * ```js
* user.getProjects().then(projects => { * const projects = await user.getProjects();
* const p1 = projects[0] * const p1 = projects[0];
* p1.userprojects.started // Is this project started yet? * p1.UserProjects.started // Is this project started yet?
* })
* ``` * ```
* *
* @param target The model that will be associated with hasOne relationship * @param target The model that will be associated with hasOne relationship
...@@ -2498,10 +2494,9 @@ export abstract class Model<T = any, T2 = any> extends Hooks { ...@@ -2498,10 +2494,9 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* Similarily, when fetching through a join table with custom attributes, these attributes will be * Similarily, when fetching through a join table with custom attributes, these attributes will be
* available as an object with the name of the through model. * available as an object with the name of the through model.
* ```js * ```js
* user.getProjects().then(projects => { * const porjects = await user.getProjects();
* const p1 = projects[0] * const p1 = projects[0];
* p1.userprojects.started // Is this project started yet? * p1.userprojects.started // Is this project started yet?
* })
* ``` * ```
* *
* @param target The model that will be associated with hasOne relationship * @param target The model that will be associated with hasOne relationship
......
...@@ -249,6 +249,19 @@ export interface FunctionParam { ...@@ -249,6 +249,19 @@ export interface FunctionParam {
direction?: string; direction?: string;
} }
export interface ColumnDescription {
type: string;
allowNull: boolean;
defaultValue: string;
primaryKey: boolean;
autoIncrement: boolean;
comment: string | null;
}
export interface ColumnsDescription {
[key: string]: ColumnDescription;
}
/** /**
* The interface that Sequelize uses to talk to all databases. * The interface that Sequelize uses to talk to all databases.
* *
...@@ -352,7 +365,7 @@ export class QueryInterface { ...@@ -352,7 +365,7 @@ export class QueryInterface {
public describeTable( public describeTable(
tableName: string | { schema?: string; tableName?: string }, tableName: string | { schema?: string; tableName?: string },
options?: string | { schema?: string; schemaDelimiter?: string } & Logging options?: string | { schema?: string; schemaDelimiter?: string } & Logging
): Promise<object>; ): Promise<ColumnsDescription>;
/** /**
* Adds a new column to a table * Adds a new column to a table
......
...@@ -22,7 +22,7 @@ import { ...@@ -22,7 +22,7 @@ import {
Hookable, Hookable,
} from './model'; } from './model';
import { ModelManager } from './model-manager'; import { ModelManager } from './model-manager';
import { QueryInterface, QueryOptions, QueryOptionsWithModel, QueryOptionsWithType } from './query-interface'; import { QueryInterface, QueryOptions, QueryOptionsWithModel, QueryOptionsWithType, ColumnsDescription } from './query-interface';
import QueryTypes = require('./query-types'); import QueryTypes = require('./query-types');
import { Transaction, TransactionOptions } from './transaction'; import { Transaction, TransactionOptions } from './transaction';
import { Cast, Col, Fn, Json, Literal, Where } from './utils'; import { Cast, Col, Fn, Json, Literal, Where } from './utils';
...@@ -1177,19 +1177,15 @@ export class Sequelize extends Hooks { ...@@ -1177,19 +1177,15 @@ export class Sequelize extends Hooks {
* Execute a query on the DB, optionally bypassing all the Sequelize goodness. * Execute a query on the DB, optionally bypassing all the Sequelize goodness.
* *
* By default, the function will return two arguments: an array of results, and a metadata object, * By default, the function will return two arguments: an array of results, and a metadata object,
* containing number of affected rows etc. Use `.then(([...]))` to access the results. * containing number of affected rows etc. Use `const [results, meta] = await ...` to access the results.
* *
* If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you * If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you
* can pass in a query type to make sequelize format the results: * can pass in a query type to make sequelize format the results:
* *
* ```js * ```js
* sequelize.query('SELECT...').then(([results, metadata]) { * const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring
* // Raw query - use spread
* });
* *
* sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(results => { * const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring
* // SELECT query - use then
* })
* ``` * ```
* *
* @param sql * @param sql
...@@ -1202,16 +1198,7 @@ export class Sequelize extends Hooks { ...@@ -1202,16 +1198,7 @@ export class Sequelize extends Hooks {
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.DELETE>): Promise<void>; public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.DELETE>): Promise<void>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.BULKDELETE>): Promise<number>; public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.BULKDELETE>): Promise<number>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.SHOWTABLES>): Promise<string[]>; public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.SHOWTABLES>): Promise<string[]>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.DESCRIBE>): Promise<{ public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.DESCRIBE>): Promise<ColumnsDescription>;
[key: string]: {
type: string;
allowNull: boolean;
defaultValue: string;
primaryKey: boolean;
autoIncrement: boolean;
comment: string | null;
}
}>;
public query<M extends Model>( public query<M extends Model>(
sql: string | { query: string; values: unknown[] }, sql: string | { query: string; values: unknown[] },
options: QueryOptionsWithModel options: QueryOptionsWithModel
...@@ -1325,12 +1312,14 @@ export class Sequelize extends Hooks { ...@@ -1325,12 +1312,14 @@ export class Sequelize extends Hooks {
* in order for the query to happen under that transaction * in order for the query to happen under that transaction
* *
* ```js * ```js
* sequelize.transaction().then(t => { * try {
* return User.findOne(..., { transaction: t}).then(user => { * const transaction = await sequelize.transaction();
* return user.update(..., { transaction: t}); * const user = await User.findOne(..., { transaction });
* }) * await user.update(..., { transaction });
* .then(t.commit.bind(t)) * await transaction.commit();
* .catch(t.rollback.bind(t)); * } catch(err) {
* await transaction.rollback();
* }
* }) * })
* ``` * ```
* *
...@@ -1338,16 +1327,16 @@ export class Sequelize extends Hooks { ...@@ -1338,16 +1327,16 @@ export class Sequelize extends Hooks {
* supported: * supported:
* *
* ```js * ```js
* sequelize.transaction(t => { // Note that we use a callback rather than a promise.then() * try {
* return User.findOne(..., { transaction: t}).then(user => { * await sequelize.transaction(transaction => { // Note that we pass a callback rather than awaiting the call with no arguments
* return user.update(..., { transaction: t}); * const user = await User.findOne(..., {transaction});
* await user.update(..., {transaction});
* }); * });
* }).then(() => { * // Committed
* // Commited * } catch(err) {
* }).catch(err => {
* // Rolled back * // Rolled back
* console.error(err); * console.error(err);
* }); * }
* ``` * ```
* *
* If you have [CLS](https://github.com/Jeff-Lewis/cls-hooked) enabled, the transaction * If you have [CLS](https://github.com/Jeff-Lewis/cls-hooked) enabled, the transaction
......
...@@ -59,15 +59,14 @@ export namespace Transaction { ...@@ -59,15 +59,14 @@ export namespace Transaction {
* Pass in the desired level as the first argument: * Pass in the desired level as the first argument:
* *
* ```js * ```js
* return sequelize.transaction({isolationLevel: Sequelize.Transaction.SERIALIZABLE}, transaction => { * try {
* * await sequelize.transaction({isolationLevel: Sequelize.Transaction.SERIALIZABLE}, transaction => {
* // your transactions * // your transactions
* * });
* }).then(result => {
* // transaction has been committed. Do something after the commit if required. * // transaction has been committed. Do something after the commit if required.
* }).catch(err => { * } catch(err) {
* // do something with the err. * // do something with the err.
* }); * }
* ``` * ```
*/ */
enum ISOLATION_LEVELS { enum ISOLATION_LEVELS {
......
...@@ -7,23 +7,19 @@ sequelize.afterBulkSync((options: SyncOptions) => { ...@@ -7,23 +7,19 @@ sequelize.afterBulkSync((options: SyncOptions) => {
console.log('synced'); console.log('synced');
}); });
sequelize async function test() {
const rows: unknown[] = await sequelize
.query('SELECT * FROM `test`', { .query('SELECT * FROM `test`', {
type: QueryTypes.SELECT, type: QueryTypes.SELECT,
})
.then(rows => {
rows.forEach(row => {
console.log(row);
});
}); });
const [autoIncrementId, affectedRows] = await sequelize
.query('INSERT into test set test=1', {
type: QueryTypes.INSERT,
});
}
sequelize
.query('INSERT into test set test=1', {
type: QueryTypes.INSERT,
})
.then(([aiId, affected]) => {
console.log(aiId, affected);
});
sequelize.transaction<void>(async transaction => { sequelize.transaction<void>(async transaction => {
const rows = await sequelize const rows = await sequelize
......
...@@ -167,11 +167,9 @@ const MyDefineModel = <MyModelStatic>sequelize.define('MyDefineModel', { ...@@ -167,11 +167,9 @@ const MyDefineModel = <MyModelStatic>sequelize.define('MyDefineModel', {
} }
}); });
function stuffTwo() { async function stuffTwo() {
MyDefineModel.findByPk(1, { const myModel = await MyDefineModel.findByPk(1, {
rejectOnEmpty: true, rejectOnEmpty: true,
})
.then(myModel => {
console.log(myModel.id);
}); });
console.log(myModel.id);
} }
...@@ -4,72 +4,70 @@ import { QueryInterface } from 'sequelize/lib/query-interface'; ...@@ -4,72 +4,70 @@ import { QueryInterface } from 'sequelize/lib/query-interface';
declare let queryInterface: QueryInterface; declare let queryInterface: QueryInterface;
queryInterface.createTable( async function test() {
'nameOfTheNewTable', await queryInterface.createTable(
{ 'nameOfTheNewTable',
attr1: DataTypes.STRING, {
attr2: DataTypes.INTEGER, attr1: DataTypes.STRING,
attr3: { attr2: DataTypes.INTEGER,
allowNull: false, attr3: {
defaultValue: false, allowNull: false,
type: DataTypes.BOOLEAN, defaultValue: false,
}, type: DataTypes.BOOLEAN,
// foreign key usage },
attr4: { // foreign key usage
onDelete: 'cascade', attr4: {
onUpdate: 'cascade', onDelete: 'cascade',
references: { onUpdate: 'cascade',
key: 'id', references: {
model: 'another_table_name', key: 'id',
model: 'another_table_name',
},
type: DataTypes.INTEGER,
},
createdAt: {
type: DataTypes.DATE,
},
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
updatedAt: {
type: DataTypes.DATE,
}, },
type: DataTypes.INTEGER,
},
createdAt: {
type: DataTypes.DATE,
},
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
updatedAt: {
type: DataTypes.DATE,
}, },
}, {
{ charset: 'latin1', // default: null
charset: 'latin1', // default: null collate: 'latin1_general_ci',
collate: 'latin1_general_ci', engine: 'MYISAM', // default: 'InnoDB'
engine: 'MYISAM', // default: 'InnoDB' uniqueKeys: {
uniqueKeys: { test: {
test: { customIndex: true,
customIndex: true, fields: ['attr2', 'attr3'],
fields: ['attr2', 'attr3'], }
} }
} }
} );
);
queryInterface.dropTable('nameOfTheExistingTable'); await queryInterface.dropTable('nameOfTheExistingTable');
queryInterface.bulkDelete({ tableName: 'foo', schema: 'bar' }, {}, {}); await queryInterface.bulkDelete({ tableName: 'foo', schema: 'bar' }, {}, {});
const bulkInsertRes: Promise<number | object> = queryInterface.bulkInsert({ tableName: 'foo', as: 'bar', name: 'as' }, [{}], {}); const bulkInsertRes: Promise<number | object> = queryInterface.bulkInsert({ tableName: 'foo', as: 'bar', name: 'as' }, [{}], {});
queryInterface.bulkUpdate({ tableName: 'foo', delimiter: 'bar', as: 'baz', name: 'quz' }, {}, {}); await queryInterface.bulkUpdate({ tableName: 'foo', delimiter: 'bar', as: 'baz', name: 'quz' }, {}, {});
queryInterface.dropTrigger({ tableName: 'foo', as: 'bar', name: 'baz' }, 'foo', {}); await queryInterface.dropTrigger({ tableName: 'foo', as: 'bar', name: 'baz' }, 'foo', {});
queryInterface.quoteTable({ tableName: 'foo', delimiter: 'bar' }); await queryInterface.quoteTable({ tableName: 'foo', delimiter: 'bar' });
queryInterface.dropAllTables(); await queryInterface.dropAllTables();
queryInterface.renameTable('Person', 'User'); await queryInterface.renameTable('Person', 'User');
queryInterface.showAllTables().then(tableNames => { const tableNames: string[] = await queryInterface.showAllTables();
// do nothing
});
queryInterface.describeTable('Person').then(attributes => {
/* /*
attributes will be something like: attributes will be something like:
...@@ -86,115 +84,116 @@ queryInterface.describeTable('Person').then(attributes => { ...@@ -86,115 +84,116 @@ queryInterface.describeTable('Person').then(attributes => {
} }
} }
*/ */
}); const attributes: object = await queryInterface.describeTable('Person');
queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', DataTypes.STRING);
// or await queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', DataTypes.STRING);
queryInterface.addColumn( // or
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfTheNewAttribute',
DataTypes.STRING
);
// or await queryInterface.addColumn(
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfTheNewAttribute',
DataTypes.STRING
);
queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', { // or
allowNull: false,
type: DataTypes.STRING,
});
queryInterface.removeColumn('Person', 'signature'); await queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', {
allowNull: false,
// or type: DataTypes.STRING,
});
queryInterface.removeColumn({ tableName: 'Person', schema: 'nameOfSchema' }, 'signature'); await queryInterface.removeColumn('Person', 'signature');
queryInterface.changeColumn('nameOfAnExistingTable', 'nameOfAnExistingAttribute', { // or
allowNull: false,
defaultValue: 0.0,
type: DataTypes.FLOAT,
});
// or await queryInterface.removeColumn({ tableName: 'Person', schema: 'nameOfSchema' }, 'signature');
queryInterface.changeColumn( await queryInterface.changeColumn('nameOfAnExistingTable', 'nameOfAnExistingAttribute', {
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfAnExistingAttribute',
{
allowNull: false, allowNull: false,
defaultValue: 0.0, defaultValue: 0.0,
type: DataTypes.FLOAT, type: DataTypes.FLOAT,
} });
);
// or
queryInterface.renameColumn('Person', 'signature', 'sig');
await queryInterface.changeColumn(
// This example will create the index person_firstname_lastname { tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
queryInterface.addIndex('Person', ['firstname', 'lastname']); 'nameOfAnExistingAttribute',
{
// This example will create a unique index with the name SuperDuperIndex using the optional 'options' field. allowNull: false,
// Possible options: defaultValue: 0.0,
// - indexName: The name of the index. Default is __ type: DataTypes.FLOAT,
// - parser: For FULLTEXT columns set your parser }
// - indexType: Set a type for the index, e.g. BTREE. See the documentation of the used dialect );
// - logging: A function that receives the sql query, e.g. console.log
queryInterface.addIndex('Person', ['firstname', 'lastname'], { await queryInterface.renameColumn('Person', 'signature', 'sig');
name: 'SuperDuperIndex',
type: 'UNIQUE', // This example will create the index person_firstname_lastname
}); await queryInterface.addIndex('Person', ['firstname', 'lastname']);
queryInterface.addIndex('Foo', { // This example will create a unique index with the name SuperDuperIndex using the optional 'options' field.
name: 'foo_a', // Possible options:
fields: [ // - indexName: The name of the index. Default is __
{ name: 'foo_b', order: 'DESC' }, // - parser: For FULLTEXT columns set your parser
'foo_c', // - indexType: Set a type for the index, e.g. BTREE. See the documentation of the used dialect
{ name: 'foo_d', order: 'ASC', collate: 'foobar', length: 42 } // - logging: A function that receives the sql query, e.g. console.log
], await queryInterface.addIndex('Person', ['firstname', 'lastname'], {
}); name: 'SuperDuperIndex',
type: 'UNIQUE',
queryInterface.addIndex('Foo', { });
name: 'foo_b_lower',
fields: [ await queryInterface.addIndex('Foo', {
fn('lower', col('foo_b')) name: 'foo_a',
], fields: [
}); { name: 'foo_b', order: 'DESC' },
'foo_c',
queryInterface.addIndex('Foo', { { name: 'foo_d', order: 'ASC', collate: 'foobar', length: 42 }
name: 'foo_c_lower', ],
fields: [ });
literal('LOWER(foo_c)')
] await queryInterface.addIndex('Foo', {
}) name: 'foo_b_lower',
fields: [
queryInterface.removeIndex('Person', 'SuperDuperIndex'); fn('lower', col('foo_b'))
],
// or });
queryInterface.removeIndex('Person', ['firstname', 'lastname']); await queryInterface.addIndex('Foo', {
name: 'foo_c_lower',
queryInterface.sequelize.transaction(trx => queryInterface.addConstraint('Person', { fields: [
name: 'firstnamexlastname', literal('LOWER(foo_c)')
fields: ['firstname', 'lastname'], ]
type: 'unique', })
transaction: trx,
})) await queryInterface.removeIndex('Person', 'SuperDuperIndex');
queryInterface.removeConstraint('Person', 'firstnamexlastname'); // or
queryInterface.select(null, 'Person', { await queryInterface.removeIndex('Person', ['firstname', 'lastname']);
where: {
a: 1, await queryInterface.sequelize.transaction(trx => queryInterface.addConstraint('Person', {
}, name: 'firstnamexlastname',
}); fields: ['firstname', 'lastname'],
type: 'unique',
queryInterface.delete(null, 'Person', { transaction: trx,
where: { }))
a: 1,
}, await queryInterface.removeConstraint('Person', 'firstnamexlastname');
});
await queryInterface.select(null, 'Person', {
queryInterface.upsert("test", {"a": 1}, {"b": 2}, {"c": 3}, Model, {}); where: {
a: 1,
queryInterface.insert(null, 'test', {}); },
});
await queryInterface.delete(null, 'Person', {
where: {
a: 1,
},
});
await queryInterface.upsert("test", {"a": 1}, {"b": 2}, {"c": 3}, Model, {});
await queryInterface.insert(null, 'test', {});
}
...@@ -60,25 +60,17 @@ const myModel: typeof Model1 = sequelize.models.asd; ...@@ -60,25 +60,17 @@ const myModel: typeof Model1 = sequelize.models.asd;
myModel.hasOne(Model2) myModel.hasOne(Model2)
myModel.findAll(); myModel.findAll();
sequelize.query('SELECT * FROM `user`', { type: QueryTypes.RAW }).then(result => { async function test() {
const data = result[0]; const [results, meta]: [unknown[], unknown] = await sequelize.query('SELECT * FROM `user`', { type: QueryTypes.RAW });
const arraysOnly = (a: any[]) => a;
arraysOnly(data);
});
sequelize const res2: { count: number } = await sequelize
.query<{ count: number }>("SELECT COUNT(1) as count FROM `user`", { .query<{ count: number }>("SELECT COUNT(1) as count FROM `user`", {
type: QueryTypes.SELECT, type: QueryTypes.SELECT,
plain: true plain: true
}) });
.then(result => {
result.count.toExponential(); // is a number!
});
sequelize const res3: { [key: string]: unknown; } = await sequelize
.query("SELECT COUNT(1) as count FROM `user`", { .query("SELECT COUNT(1) as count FROM `user`", {
plain: true plain: true
}) })
.then(result => { }
console.log(result.count);
});
...@@ -6,8 +6,8 @@ class TestModel extends Model { ...@@ -6,8 +6,8 @@ class TestModel extends Model {
TestModel.init({}, {sequelize}) TestModel.init({}, {sequelize})
sequelize.transaction(trx => { sequelize.transaction(async trx => {
TestModel.upsert<TestModel>({}, { const res: [TestModel, boolean] = await TestModel.upsert<TestModel>({}, {
benchmark: true, benchmark: true,
fields: ['testField'], fields: ['testField'],
hooks: true, hooks: true,
...@@ -16,9 +16,9 @@ sequelize.transaction(trx => { ...@@ -16,9 +16,9 @@ sequelize.transaction(trx => {
searchPath: 'DEFAULT', searchPath: 'DEFAULT',
transaction: trx, transaction: trx,
validate: true, validate: true,
}).then((res: [ TestModel, boolean ]) => {}); });
TestModel.upsert<TestModel>({}, { let created: boolean = await TestModel.upsert<TestModel>({}, {
benchmark: true, benchmark: true,
fields: ['testField'], fields: ['testField'],
hooks: true, hooks: true,
...@@ -27,9 +27,9 @@ sequelize.transaction(trx => { ...@@ -27,9 +27,9 @@ sequelize.transaction(trx => {
searchPath: 'DEFAULT', searchPath: 'DEFAULT',
transaction: trx, transaction: trx,
validate: true, validate: true,
}).then((created: boolean) => {}); });
return TestModel.upsert<TestModel>({}, { created = await TestModel.upsert<TestModel>({}, {
benchmark: true, benchmark: true,
fields: ['testField'], fields: ['testField'],
hooks: true, hooks: true,
...@@ -37,5 +37,5 @@ sequelize.transaction(trx => { ...@@ -37,5 +37,5 @@ sequelize.transaction(trx => {
searchPath: 'DEFAULT', searchPath: 'DEFAULT',
transaction: trx, transaction: trx,
validate: true, validate: true,
}).then((created: boolean) => {}); });
}) })
...@@ -164,31 +164,22 @@ MyModel.update({ hi: 1 }, { where }); ...@@ -164,31 +164,22 @@ MyModel.update({ hi: 1 }, { where });
// From https://sequelize.org/master/en/v4/docs/models-usage/ // From https://sequelize.org/master/en/v4/docs/models-usage/
// find multiple entries async function test() {
MyModel.findAll().then(projects => { // find multiple entries
// projects will be an array of all MyModel instances let projects: MyModel[] = await MyModel.findAll();
});
// search for specific attributes - hash usage // search for specific attributes - hash usage
MyModel.findAll({ where: { name: 'A MyModel', enabled: true } }).then(projects => { projects = await MyModel.findAll({ where: { name: 'A MyModel', enabled: true } })
// projects will be an array of MyModel instances with the specified name
});
// search within a specific range // search within a specific range
MyModel.findAll({ where: { id: [1, 2, 3] } }).then(projects => { projects = await MyModel.findAll({ where: { id: [1, 2, 3] } });
// projects will be an array of MyModels having the id 1, 2 or 3
// this is actually doing an IN query
});
// locks // locks
MyModel.findAll({ lock: Transaction.LOCK.KEY_SHARE }).then(projects => { projects = await MyModel.findAll({ lock: Transaction.LOCK.KEY_SHARE });
// noop
});
// locks on model // locks on model
MyModel.findAll({ lock: { level: Transaction.LOCK.KEY_SHARE, of: MyModel} }).then(projects => { projects = await MyModel.findAll({ lock: { level: Transaction.LOCK.KEY_SHARE, of: MyModel} });
// noop }
});
MyModel.findAll({ MyModel.findAll({
where: { where: {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!