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

Commit 8244a34e by Simon Schick Committed by GitHub

docs: asyncify (#12297)

1 parent b2bccb8a
......@@ -30,9 +30,8 @@ const Op = require('../operators');
* All methods allow you to pass either a persisted instance, its primary key, or a mixture:
*
* ```js
* Project.create({ id: 11 }).then(project => {
* user.addProjects([project, 12]);
* });
* const project = await Project.create({ id: 11 });
* 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:
......@@ -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.
* ```js
* user.getProjects().then(projects => {
* let p1 = projects[0]
* p1.UserProjects.started // Is this project started yet?
* })
* const projects = await user.getProjects();
* const p1 = projects[0];
* 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()`.
......
......@@ -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
*
* @example
* Model.findAndCountAll({
* const result = await Model.findAndCountAll({
* where: ...,
* limit: 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.
*
......
......@@ -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:
*
* ```js
* sequelize.query('SELECT...').then(([results, metadata]) => {
* // Raw query - use then plus array spread
* });
* const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring
*
* sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(results => {
* // SELECT query - use then
* })
* const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring
* ```
*
* @param {string} sql
......@@ -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
*
* @example
* sequelize.transaction().then(transaction => {
* return User.findOne(..., {transaction})
* .then(user => user.update(..., {transaction}))
* .then(() => transaction.commit())
* .catch(() => transaction.rollback());
* })
*
* try {
* const transaction = await sequelize.transaction();
* const user = await User.findOne(..., { transaction });
* 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>
*
* sequelize.transaction(transaction => { // Note that we use a callback rather than a promise.then()
* return User.findOne(..., {transaction})
* .then(user => user.update(..., {transaction}))
* }).then(() => {
* try {
* await sequelize.transaction(transaction => { // Note that we pass a callback rather than awaiting the call with no arguments
* const user = await User.findOne(..., {transaction});
* await user.update(..., {transaction});
* });
* // Committed
* }).catch(err => {
* } catch(err) {
* // Rolled back
* console.error(err);
* });
*
* }
* @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');
......
......@@ -199,13 +199,14 @@ class Transaction {
* Pass in the desired level as the first argument:
*
* @example
* return sequelize.transaction({type: Sequelize.Transaction.TYPES.EXCLUSIVE}, transaction => {
* // your transactions
* }).then(result => {
* try {
* await sequelize.transaction({ type: Sequelize.Transaction.TYPES.EXCLUSIVE }, transaction => {
* // your transactions
* });
* // transaction has been committed. Do something after the commit if required.
* }).catch(err => {
* } catch(err) {
* // do something with the err.
* });
* }
*
* @property DEFERRED
* @property IMMEDIATE
......@@ -226,13 +227,14 @@ class Transaction {
* Pass in the desired level as the first argument:
*
* @example
* return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
* // your transactions
* }).then(result => {
* try {
* const result = await sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
* // your transactions
* });
* // transaction has been committed. Do something after the commit if required.
* }).catch(err => {
* } catch(err) {
* // do something with the err.
* });
* }
*
* @property READ_UNCOMMITTED
* @property READ_COMMITTED
......
......@@ -1830,17 +1830,14 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
* rows matching your query. This is very usefull for paging
*
* ```js
* Model.findAndCountAll({
* const { rows, count } = await Model.findAndCountAll({
* where: ...,
* limit: 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, `rows` will contain rows 13 through 24, while `count` will return
* the 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
* because
......@@ -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.
* 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>(
this: { new(): M } & typeof Model,
......@@ -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
* 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
* 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 {
* 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.
* ```js
* user.getProjects().then(projects => {
* const p1 = projects[0]
* p1.userprojects.started // Is this project started yet?
* })
* const projects = await user.getProjects();
* const p1 = projects[0];
* p1.UserProjects.started // Is this project started yet?
* ```
*
* @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 {
* 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.
* ```js
* user.getProjects().then(projects => {
* const p1 = projects[0]
* p1.userprojects.started // Is this project started yet?
* })
* const porjects = await user.getProjects();
* const p1 = projects[0];
* p1.userprojects.started // Is this project started yet?
* ```
*
* @param target The model that will be associated with hasOne relationship
......
......@@ -249,6 +249,19 @@ export interface FunctionParam {
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.
*
......@@ -352,7 +365,7 @@ export class QueryInterface {
public describeTable(
tableName: string | { schema?: string; tableName?: string },
options?: string | { schema?: string; schemaDelimiter?: string } & Logging
): Promise<object>;
): Promise<ColumnsDescription>;
/**
* Adds a new column to a table
......
......@@ -22,7 +22,7 @@ import {
Hookable,
} from './model';
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 { Transaction, TransactionOptions } from './transaction';
import { Cast, Col, Fn, Json, Literal, Where } from './utils';
......@@ -1177,19 +1177,15 @@ export class Sequelize extends Hooks {
* 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,
* 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
* can pass in a query type to make sequelize format the results:
*
* ```js
* sequelize.query('SELECT...').then(([results, metadata]) {
* // Raw query - use spread
* });
* const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring
*
* sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(results => {
* // SELECT query - use then
* })
* const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring
* ```
*
* @param sql
......@@ -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.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.DESCRIBE>): Promise<{
[key: string]: {
type: string;
allowNull: boolean;
defaultValue: string;
primaryKey: boolean;
autoIncrement: boolean;
comment: string | null;
}
}>;
public query(sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.DESCRIBE>): Promise<ColumnsDescription>;
public query<M extends Model>(
sql: string | { query: string; values: unknown[] },
options: QueryOptionsWithModel
......@@ -1325,12 +1312,14 @@ export class Sequelize extends Hooks {
* in order for the query to happen under that transaction
*
* ```js
* sequelize.transaction().then(t => {
* return User.findOne(..., { transaction: t}).then(user => {
* return user.update(..., { transaction: t});
* })
* .then(t.commit.bind(t))
* .catch(t.rollback.bind(t));
* try {
* const transaction = await sequelize.transaction();
* const user = await User.findOne(..., { transaction });
* await user.update(..., { transaction });
* await transaction.commit();
* } catch(err) {
* await transaction.rollback();
* }
* })
* ```
*
......@@ -1338,16 +1327,16 @@ export class Sequelize extends Hooks {
* supported:
*
* ```js
* sequelize.transaction(t => { // Note that we use a callback rather than a promise.then()
* return User.findOne(..., { transaction: t}).then(user => {
* return user.update(..., { transaction: t});
* try {
* await sequelize.transaction(transaction => { // Note that we pass a callback rather than awaiting the call with no arguments
* const user = await User.findOne(..., {transaction});
* await user.update(..., {transaction});
* });
* }).then(() => {
* // Commited
* }).catch(err => {
* // Committed
* } catch(err) {
* // Rolled back
* console.error(err);
* });
* }
* ```
*
* If you have [CLS](https://github.com/Jeff-Lewis/cls-hooked) enabled, the transaction
......
......@@ -59,15 +59,14 @@ export namespace Transaction {
* Pass in the desired level as the first argument:
*
* ```js
* return sequelize.transaction({isolationLevel: Sequelize.Transaction.SERIALIZABLE}, transaction => {
*
* // your transactions
*
* }).then(result => {
* try {
* await sequelize.transaction({isolationLevel: Sequelize.Transaction.SERIALIZABLE}, transaction => {
* // your transactions
* });
* // transaction has been committed. Do something after the commit if required.
* }).catch(err => {
* } catch(err) {
* // do something with the err.
* });
* }
* ```
*/
enum ISOLATION_LEVELS {
......
......@@ -7,23 +7,19 @@ sequelize.afterBulkSync((options: SyncOptions) => {
console.log('synced');
});
sequelize
async function test() {
const rows: unknown[] = await sequelize
.query('SELECT * FROM `test`', {
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 => {
const rows = await sequelize
......
......@@ -167,11 +167,9 @@ const MyDefineModel = <MyModelStatic>sequelize.define('MyDefineModel', {
}
});
function stuffTwo() {
MyDefineModel.findByPk(1, {
async function stuffTwo() {
const myModel = await MyDefineModel.findByPk(1, {
rejectOnEmpty: true,
})
.then(myModel => {
console.log(myModel.id);
});
console.log(myModel.id);
}
......@@ -4,72 +4,70 @@ import { QueryInterface } from 'sequelize/lib/query-interface';
declare let queryInterface: QueryInterface;
queryInterface.createTable(
'nameOfTheNewTable',
{
attr1: DataTypes.STRING,
attr2: DataTypes.INTEGER,
attr3: {
allowNull: false,
defaultValue: false,
type: DataTypes.BOOLEAN,
},
// foreign key usage
attr4: {
onDelete: 'cascade',
onUpdate: 'cascade',
references: {
key: 'id',
model: 'another_table_name',
async function test() {
await queryInterface.createTable(
'nameOfTheNewTable',
{
attr1: DataTypes.STRING,
attr2: DataTypes.INTEGER,
attr3: {
allowNull: false,
defaultValue: false,
type: DataTypes.BOOLEAN,
},
// foreign key usage
attr4: {
onDelete: 'cascade',
onUpdate: 'cascade',
references: {
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
collate: 'latin1_general_ci',
engine: 'MYISAM', // default: 'InnoDB'
uniqueKeys: {
test: {
customIndex: true,
fields: ['attr2', 'attr3'],
{
charset: 'latin1', // default: null
collate: 'latin1_general_ci',
engine: 'MYISAM', // default: 'InnoDB'
uniqueKeys: {
test: {
customIndex: true,
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 => {
// do nothing
});
const tableNames: string[] = await queryInterface.showAllTables();
queryInterface.describeTable('Person').then(attributes => {
/*
attributes will be something like:
......@@ -86,115 +84,116 @@ queryInterface.describeTable('Person').then(attributes => {
}
}
*/
});
queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', DataTypes.STRING);
const attributes: object = await queryInterface.describeTable('Person');
// or
await queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', DataTypes.STRING);
queryInterface.addColumn(
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfTheNewAttribute',
DataTypes.STRING
);
// or
// or
await queryInterface.addColumn(
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfTheNewAttribute',
DataTypes.STRING
);
queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', {
allowNull: false,
type: DataTypes.STRING,
});
// or
queryInterface.removeColumn('Person', 'signature');
// or
await queryInterface.addColumn('nameOfAnExistingTable', 'nameOfTheNewAttribute', {
allowNull: false,
type: DataTypes.STRING,
});
queryInterface.removeColumn({ tableName: 'Person', schema: 'nameOfSchema' }, 'signature');
await queryInterface.removeColumn('Person', 'signature');
queryInterface.changeColumn('nameOfAnExistingTable', 'nameOfAnExistingAttribute', {
allowNull: false,
defaultValue: 0.0,
type: DataTypes.FLOAT,
});
// or
// or
await queryInterface.removeColumn({ tableName: 'Person', schema: 'nameOfSchema' }, 'signature');
queryInterface.changeColumn(
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfAnExistingAttribute',
{
await queryInterface.changeColumn('nameOfAnExistingTable', 'nameOfAnExistingAttribute', {
allowNull: false,
defaultValue: 0.0,
type: DataTypes.FLOAT,
}
);
queryInterface.renameColumn('Person', 'signature', 'sig');
// This example will create the index person_firstname_lastname
queryInterface.addIndex('Person', ['firstname', 'lastname']);
// This example will create a unique index with the name SuperDuperIndex using the optional 'options' field.
// Possible options:
// - indexName: The name of the index. Default is __
// - 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'], {
name: 'SuperDuperIndex',
type: 'UNIQUE',
});
queryInterface.addIndex('Foo', {
name: 'foo_a',
fields: [
{ name: 'foo_b', order: 'DESC' },
'foo_c',
{ name: 'foo_d', order: 'ASC', collate: 'foobar', length: 42 }
],
});
queryInterface.addIndex('Foo', {
name: 'foo_b_lower',
fields: [
fn('lower', col('foo_b'))
],
});
queryInterface.addIndex('Foo', {
name: 'foo_c_lower',
fields: [
literal('LOWER(foo_c)')
]
})
queryInterface.removeIndex('Person', 'SuperDuperIndex');
// or
queryInterface.removeIndex('Person', ['firstname', 'lastname']);
queryInterface.sequelize.transaction(trx => queryInterface.addConstraint('Person', {
name: 'firstnamexlastname',
fields: ['firstname', 'lastname'],
type: 'unique',
transaction: trx,
}))
queryInterface.removeConstraint('Person', 'firstnamexlastname');
queryInterface.select(null, 'Person', {
where: {
a: 1,
},
});
queryInterface.delete(null, 'Person', {
where: {
a: 1,
},
});
queryInterface.upsert("test", {"a": 1}, {"b": 2}, {"c": 3}, Model, {});
queryInterface.insert(null, 'test', {});
});
// or
await queryInterface.changeColumn(
{ tableName: 'nameOfAnExistingTable', schema: 'nameOfSchema' },
'nameOfAnExistingAttribute',
{
allowNull: false,
defaultValue: 0.0,
type: DataTypes.FLOAT,
}
);
await queryInterface.renameColumn('Person', 'signature', 'sig');
// This example will create the index person_firstname_lastname
await queryInterface.addIndex('Person', ['firstname', 'lastname']);
// This example will create a unique index with the name SuperDuperIndex using the optional 'options' field.
// Possible options:
// - indexName: The name of the index. Default is __
// - 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
await queryInterface.addIndex('Person', ['firstname', 'lastname'], {
name: 'SuperDuperIndex',
type: 'UNIQUE',
});
await queryInterface.addIndex('Foo', {
name: 'foo_a',
fields: [
{ name: 'foo_b', order: 'DESC' },
'foo_c',
{ name: 'foo_d', order: 'ASC', collate: 'foobar', length: 42 }
],
});
await queryInterface.addIndex('Foo', {
name: 'foo_b_lower',
fields: [
fn('lower', col('foo_b'))
],
});
await queryInterface.addIndex('Foo', {
name: 'foo_c_lower',
fields: [
literal('LOWER(foo_c)')
]
})
await queryInterface.removeIndex('Person', 'SuperDuperIndex');
// or
await queryInterface.removeIndex('Person', ['firstname', 'lastname']);
await queryInterface.sequelize.transaction(trx => queryInterface.addConstraint('Person', {
name: 'firstnamexlastname',
fields: ['firstname', 'lastname'],
type: 'unique',
transaction: trx,
}))
await queryInterface.removeConstraint('Person', 'firstnamexlastname');
await queryInterface.select(null, 'Person', {
where: {
a: 1,
},
});
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;
myModel.hasOne(Model2)
myModel.findAll();
sequelize.query('SELECT * FROM `user`', { type: QueryTypes.RAW }).then(result => {
const data = result[0];
const arraysOnly = (a: any[]) => a;
arraysOnly(data);
});
async function test() {
const [results, meta]: [unknown[], unknown] = await sequelize.query('SELECT * FROM `user`', { type: QueryTypes.RAW });
sequelize
.query<{ count: number }>("SELECT COUNT(1) as count FROM `user`", {
type: QueryTypes.SELECT,
plain: true
})
.then(result => {
result.count.toExponential(); // is a number!
});
const res2: { count: number } = await sequelize
.query<{ count: number }>("SELECT COUNT(1) as count FROM `user`", {
type: QueryTypes.SELECT,
plain: true
});
sequelize
.query("SELECT COUNT(1) as count FROM `user`", {
plain: true
})
.then(result => {
console.log(result.count);
});
const res3: { [key: string]: unknown; } = await sequelize
.query("SELECT COUNT(1) as count FROM `user`", {
plain: true
})
}
......@@ -6,8 +6,8 @@ class TestModel extends Model {
TestModel.init({}, {sequelize})
sequelize.transaction(trx => {
TestModel.upsert<TestModel>({}, {
sequelize.transaction(async trx => {
const res: [TestModel, boolean] = await TestModel.upsert<TestModel>({}, {
benchmark: true,
fields: ['testField'],
hooks: true,
......@@ -16,9 +16,9 @@ sequelize.transaction(trx => {
searchPath: 'DEFAULT',
transaction: trx,
validate: true,
}).then((res: [ TestModel, boolean ]) => {});
});
TestModel.upsert<TestModel>({}, {
let created: boolean = await TestModel.upsert<TestModel>({}, {
benchmark: true,
fields: ['testField'],
hooks: true,
......@@ -27,9 +27,9 @@ sequelize.transaction(trx => {
searchPath: 'DEFAULT',
transaction: trx,
validate: true,
}).then((created: boolean) => {});
});
return TestModel.upsert<TestModel>({}, {
created = await TestModel.upsert<TestModel>({}, {
benchmark: true,
fields: ['testField'],
hooks: true,
......@@ -37,5 +37,5 @@ sequelize.transaction(trx => {
searchPath: 'DEFAULT',
transaction: trx,
validate: true,
}).then((created: boolean) => {});
});
})
......@@ -164,31 +164,22 @@ MyModel.update({ hi: 1 }, { where });
// From https://sequelize.org/master/en/v4/docs/models-usage/
// find multiple entries
MyModel.findAll().then(projects => {
// projects will be an array of all MyModel instances
});
async function test() {
// find multiple entries
let projects: MyModel[] = await MyModel.findAll();
// search for specific attributes - hash usage
MyModel.findAll({ where: { name: 'A MyModel', enabled: true } }).then(projects => {
// projects will be an array of MyModel instances with the specified name
});
// search for specific attributes - hash usage
projects = await MyModel.findAll({ where: { name: 'A MyModel', enabled: true } })
// search within a specific range
MyModel.findAll({ where: { id: [1, 2, 3] } }).then(projects => {
// projects will be an array of MyModels having the id 1, 2 or 3
// this is actually doing an IN query
});
// search within a specific range
projects = await MyModel.findAll({ where: { id: [1, 2, 3] } });
// locks
MyModel.findAll({ lock: Transaction.LOCK.KEY_SHARE }).then(projects => {
// noop
});
// locks
projects = await MyModel.findAll({ lock: Transaction.LOCK.KEY_SHARE });
// locks on model
MyModel.findAll({ lock: { level: Transaction.LOCK.KEY_SHARE, of: MyModel} }).then(projects => {
// noop
});
// locks on model
projects = await MyModel.findAll({ lock: { level: Transaction.LOCK.KEY_SHARE, of: MyModel} });
}
MyModel.findAll({
where: {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!