Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

MySQL plugin for egg

License

NotificationsYou must be signed in to change notification settings

eggjs/mysql

Repository files navigation

NPM versionCITest coveragenpm downloadNode.js VersionPRs WelcomeCodeRabbit Pull Request Reviews

MySQL plugin for Egg.js

Install

npm i @eggjs/mysql

MySQL Plugin foregg@4, support egg application access to MySQL database.

If you're usingegg@3, please useegg-mysql@5 instead.

This plugin based on@eggjs/rds, if you want to know specific usage, you should refer to the document of@eggjs/rds.

Configuration

Change${app_root}/config/plugin.ts to enable MySQL plugin:

exportdefault{mysql:{enable:true,package:'@eggjs/mysql',},};

Configure database information in${app_root}/config/config.default.ts:

Simple database instance

exportdefault{mysql:{// database configurationclient:{// hosthost:'mysql.com',// portport:'3306',// usernameuser:'test_user',// passwordpassword:'test_password',// databasedatabase:'test',},// load into app, default is `true`app:true,// load into agent, default is `false`agent:false,},};

Usage:

awaitapp.mysql.query(sql,values);// you can access to simple database instance by using app.mysql.

Multiple database instance

exportdefault{mysql:{clients:{// clientId, access the client instance by app.mysql.get('clientId')db1:{// hosthost:'mysql.com',// portport:'3306',// usernameuser:'test_user',// passwordpassword:'test_password',// databasedatabase:'test',},// ...},// default configuration for all databasesdefault:{},// load into app, default is openapp:true,// load into agent, default is closeagent:false,},};

Usage:

constclient1=app.mysqls.getSingletonInstance('db1');awaitclient1.query(sql,values);constclient2=app.mysqls.getSingletonInstance('db2');awaitclient2.query(sql,values);

CRUD user guide

Create

// insertconstresult=awaitapp.mysql.insert('posts',{title:'Hello World'});constinsertSuccess=result.affectedRows===1;

Read

// getconstpost=awaitapp.mysql.get('posts',{id:12});// queryconstresults=awaitapp.mysql.select('posts',{where:{status:'draft'},orders:[['created_at','desc'],['id','desc'],],limit:10,offset:0,});

Update

// update by primary key ID, and refreshconstrow={id:123,name:'fengmk2',otherField:'other field value',modifiedAt:app.mysql.literals.now,// `now()` on db server};constresult=awaitapp.mysql.update('posts',row);constupdateSuccess=result.affectedRows===1;

Delete

constresult=awaitapp.mysql.delete('table-name',{name:'fengmk2',});

Transaction

Manual control

  • adventage:beginTransaction,commit orrollback can be completely under control by developer
  • disadventage: more handwritten code, Forgot catching error or cleanup will lead to serious bug.
constconn=awaitapp.mysql.beginTransaction();try{awaitconn.insert(table,row1);awaitconn.update(table,row2);awaitconn.commit();}catch(err){// error, rollbackawaitconn.rollback();// rollback call won't throw errthrowerr;}

Automatic control: Transaction with scope

  • API:async 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
constresult=awaitapp.mysql.beginTransactionScope(asyncconn=>{// don't commit or rollback by yourselfawaitconn.insert(table,row1);awaitconn.update(table,row2);return{success:true};},ctx);// ctx is the context of current request, access by `this.ctx`.// if error throw on scope, will auto rollback

Advance

Custom SQL splicing

constresults=awaitapp.mysql.query('update posts set hits = (hits + ?) where id = ?',[1,postId]);

Literal

If you want to call literals or functions in mysql , you can useLiteral.

Inner Literal

  • NOW(): The database system time, you can obtain byapp.mysql.literals.now.
awaitapp.mysql.insert(table,{create_time:app.mysql.literals.now,});// INSERT INTO `$table`(`create_time`) VALUES(NOW())

Custom literal

The following demo showed how to callCONCAT(s1, ...sn) function in mysql to do string splicing.

constLiteral=app.mysql.literals.Literal;constfirst='James';constlast='Bond';awaitapp.mysql.insert(table,{id:123,fullname:newLiteral(`CONCAT("${first}", "${last}"`),});// INSERT INTO `$table`(`id`, `fullname`) VALUES(123, CONCAT("James", "Bond"))

For the local dev

Run docker compose to start test mysql service

docker compose -f docker-compose.yml up -d# if you run the first time, should wait for ~20s to let mysql service init started

Run the unit tests

npmtest

Stop test mysql service

docker compose -f docker-compose.yml down

Questions & Suggestions

Please open an issuehere.

License

MIT

Contributors

Contributors

Made withcontributors-img.

About

MySQL plugin for egg

Topics

Resources

License

Stars

Watchers

Forks

Contributors13


[8]ページ先頭

©2009-2025 Movatter.jp