title: MySQL

MySQL is one of the most common and best RDBMS in terms of web applications. It is used in many large-scale websites such as Google and Facebook.

egg-mysql

egg-mysql is provided to access both the MySQL databases and MySQL-based online database service.

Installation and Configuration

Install egg-mysql

  1. $ npm i --save egg-mysql

Enable Plugin:

  1. // config/plugin.js
  2. exports.mysql = {
  3. enable: true,
  4. package: 'egg-mysql',
  5. };

Configure database information in config/config.${env}.js

Single Data Source

Configuration to accesss single MySQL instance as shown below:

  1. // config/config.${env}.js
  2. exports.mysql = {
  3. // database configuration
  4. client: {
  5. host: 'mysql.com',
  6. port: '3306',
  7. user: 'test_user',
  8. password: 'test_password',
  9. database: 'test',
  10. },
  11. // load into app, default true
  12. app: true,
  13. // load into agent, default false
  14. agent: false,
  15. };

Use:

  1. await app.mysql.query(sql, values); // single instance can be accessed through app.mysql

Multiple Data Sources

Configuration to accesss multiple MySQL instances as below:

  1. exports.mysql = {
  2. clients: {
  3. // clientId, obtain the client instances using the app.mysql.get('clientId')
  4. db1: {
  5. host: 'mysql.com',
  6. port: '3306',
  7. user: 'test_user',
  8. password: 'test_password',
  9. database: 'test',
  10. },
  11. db2: {
  12. host: 'mysql2.com',
  13. port: '3307',
  14. user: 'test_user',
  15. password: 'test_password',
  16. database: 'test',
  17. },
  18. // ...
  19. },
  20. //default configuration of all databases
  21. default: {
  22. },
  23. // load into app, default true
  24. app: true,
  25. // load into agent, default false
  26. agent: false,
  27. };

Use:

  1. const client1 = app.mysql.get('db1');
  2. await client1.query(sql, values);
  3. const client2 = app.mysql.get('db2');
  4. await client2.query(sql, values);

Dynamic Creation

Pre-declaration of configuration might not needed in the configuration file. Obtaining the actual parameters dynamically from the configuration center then initialize an instance instead.

  1. // {app_root}/app.js
  2. module.exports = app => {
  3. app.beforeStart(async () => {
  4. // obtain the MySQL configuration from the configuration center
  5. // { host: 'mysql.com', port: '3306', user: 'test_user', password: 'test_password', database: 'test' }
  6. const mysqlConfig = await app.configCenter.fetch('mysql');
  7. app.database = app.mysql.createInstance(mysqlConfig);
  8. });
  9. };

Service layer

Connecting to MySQL is a data processing layer in the Web layer. So it is strongly recommended that keeping the code in the Service layer.

An example of connecting to MySQL as follows.

Details of Service layer, refer to service

  1. // app/service/user.js
  2. class UserService extends Service {
  3. async find(uid) {
  4. // assume we have the user id then trying to get the user details from database
  5. const user = await this.app.mysql.get('users', { id: 11 });
  6. return { user };
  7. }
  8. }

After that, obtaining the data from service layer using the controller

  1. // app/controller/user.js
  2. class UserController extends Controller {
  3. async info() {
  4. const ctx = this.ctx;
  5. const userId = ctx.params.id;
  6. const user = await ctx.service.user.find(userId);
  7. ctx.body = user;
  8. }
  9. }

Writing CRUD

Following statments default under app/service if not specifed

Create

INSERT method to perform the INSERT INTO query

  1. // INSERT
  2. const result = await this.app.mysql.insert('posts', { title: 'Hello World' }); //insert a record title 'Hello World' to 'posts' table
  3. => INSERT INTO `posts`(`title`) VALUES('Hello World');
  4. console.log(result);
  5. =>
  6. {
  7. fieldCount: 0,
  8. affectedRows: 1,
  9. insertId: 3710,
  10. serverStatus: 2,
  11. warningCount: 2,
  12. message: '',
  13. protocol41: true,
  14. changedRows: 0
  15. }
  16. // check if insertion is success or failure
  17. const insertSuccess = result.affectedRows === 1;

Read

Use get or select to select one or multiple records. select method support query criteria and result customization

  • get one record
  1. const post = await this.app.mysql.get('posts', { id: 12 });
  2. => SELECT * FROM `posts` WHERE `id` = 12 LIMIT 0, 1;
  • query all from the table
  1. const results = await this.app.mysql.select('posts');
  2. => SELECT * FROM `posts`;
  • query criteria and result customization
  1. const results = await this.app.mysql.select('posts', { // search posts table
  2. where: { status: 'draft', author: ['author1', 'author2'] }, // WHERE criteria
  3. columns: ['author', 'title'], // get the value of certain columns
  4. orders: [['created_at','desc'], ['id','desc']], // sort order
  5. limit: 10, // limit the return rows
  6. offset: 0, // data offset
  7. });
  8. => SELECT `author`, `title` FROM `posts`
  9. WHERE `status` = 'draft' AND `author` IN('author1','author2')
  10. ORDER BY `created_at` DESC, `id` DESC LIMIT 0, 10;

Update

UPDATE operation to update the records of databases

  1. // modify data and search by primary key ID, and refresh
  2. const row = {
  3. id: 123,
  4. name: 'fengmk2',
  5. otherField: 'other field value', // any other fields u want to update
  6. modifiedAt: this.app.mysql.literals.now, // `now()` on db server
  7. };
  8. const result = await this.app.mysql.update('posts', row); // update records in 'posts'
  9. => UPDATE `posts` SET `name` = 'fengmk2', `modifiedAt` = NOW() WHERE id = 123 ;
  10. // check if update is success or failure
  11. const updateSuccess = result.affectedRows === 1;
  12. // if primary key is your custom id,such as custom_id,you should config it in `where`
  13. const row = {
  14. name: 'fengmk2',
  15. otherField: 'other field value', // any other fields u want to update
  16. modifiedAt: this.app.mysql.literals.now, // `now()` on db server
  17. };
  18. const options = {
  19. where: {
  20. custom_id: 456
  21. }
  22. };
  23. const result = await this.app.mysql.update('posts', row, options); // update records in 'posts'
  24. => UPDATE `posts` SET `name` = 'fengmk2', `modifiedAt` = NOW() WHERE custom_id = 456 ;
  25. // check if update is success or failure
  26. const updateSuccess = result.affectedRows === 1;

Delete

DELETE operation to delete the records of databases

  1. const result = await this.app.mysql.delete('posts', {
  2. author: 'fengmk2',
  3. });
  4. => DELETE FROM `posts` WHERE `author` = 'fengmk2';

Implementation of SQL statement

Plugin supports splicing and execute SQL statment directly. It can use query to execute a valid SQL statement

Note!! Strongly do not recommend developers splicing SQL statement, it is easier to cause SQL injection!!

Use the mysql.escape method if you have to splice SQL statement

Refer to preventing-sql-injection-in-node-js

  1. const postId = 1;
  2. const results = await this.app.mysql.query('update posts set hits = (hits + ?) where id = ?', [1, postId]);
  3. => update posts set hits = (hits + 1) where id = 1;

Transaction

Transaction is mainly used to deal with large data of high complexity. For example, in a personnel management system, deleting a person which need to delete the basic information of the staff, but also need to delete the related information of staff, such as mailboxes, articles and so on. It is easier to use transaction to run a set of operations.
A transaction is a set of continuous database operations which performed as a single unit of work. Each individual operation within the group is successful and the transaction succeeds. If one part of the transaction fails, then the entire transaction fails.
In gerenal, transaction must be atomic, consistent, isolated and durable.

  • Atomicity requires that each transaction be “all or nothing”: if one part of the transaction fails, then the entire transaction fails, and the database state is left unchanged.
  • The consistency property ensures that any transaction will bring the database from one valid state to another.
  • The isolation property ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed sequentially
  • The durability property ensures that once a transaction has been committed, it will remain so.

Therefore, for a transaction, must be accompanied by beginTransaction, commit or rollback, respectively, beginning of the transaction, success and failure to roll back.

egg-mysql proviodes two types of transactions

Manual Control

  • adventage: beginTransaction, commit or rollback can be completely under control by developer
  • disadventage: more handwritten code, Forgot catching error or cleanup will lead to serious bug.
  1. const conn = await app.mysql.beginTransaction(); // initialize the transaction
  2. try {
  3. await conn.insert(table, row1); // first step
  4. await conn.update(table, row2); // second step
  5. await conn.commit(); // commit the transaction
  6. } catch (err) {
  7. // error, rollback
  8. await conn.rollback(); // rollback after catching the exception!!
  9. throw err;
  10. }

Automatic control: Transaction with scope

  • API:beginTransactionScope(scope, ctx)
    • scope: A generatorFunction which will execute all sqls of this transaction.
    • ctx: The context object of current request, it will ensures that even in the case of a nested transaction, there is only one active transaction in a request at the same time.
  • adventage: easy to use, as if there is no transaction in your code.
  • disadvantage: all transation will be successful or failed, cannot control precisely
    1. const result = await app.mysql.beginTransactionScope(async conn => {
    2. // don't commit or rollback by yourself
    3. await conn.insert(table, row1);
    4. await conn.update(table, row2);
    5. return { success: true };
    6. }, ctx); // ctx is the context of current request, accessed by `this.ctx` within in service file.
    7. // if error throw on scope, will auto rollback

Literal

Use Literal if need to call literals or functions in MySQL

Inner Literal

  • NOW():The database system time, obtained by app.mysql.literals.now
  1. await this.app.mysql.insert(table, {
  2. create_time: this.app.mysql.literals.now,
  3. });
  4. => INSERT INTO `$table`(`create_time`) VALUES(NOW())

Custom literal

The following demo showe how to call CONCAT(s1, ...sn) funtion in mysql to do string splicing.

  1. const Literal = this.app.mysql.literals.Literal;
  2. const first = 'James';
  3. const last = 'Bond';
  4. await this.app.mysql.insert(table, {
  5. id: 123,
  6. fullname: new Literal(`CONCAT("${first}", "${last}"`),
  7. });
  8. => INSERT INTO `$table`(`id`, `fullname`) VALUES(123, CONCAT("James", "Bond"))