egg-mysql
Aliyun rds client(support mysql portocal) for egg framework
Install
$ npm i egg-mysql --save
MySQL Plugin for egg, support egg application access to MySQL database.
This plugin based on ali-rds, if you want to know specific usage, you should refer to the document of ali-rds.
Configuration
Change ${app_root}/config/plugin.js
to enable MySQL plugin:
exports.mysql = {
enable: true,
package: 'egg-mysql',
};
Configure database information in ${app_root}/config/config.default.js
:
Simple database instance
exports.mysql = {
client: {
host: 'mysql.com',
port: '3306',
user: 'test_user',
password: 'test_password',
database: 'test',
},
app: true,
agent: false,
};
Usage:
app.mysql.query(sql, values);
Multiple database instance
exports.mysql = {
clients: {
db1: {
host: 'mysql.com',
port: '3306',
user: 'test_user',
password: 'test_password',
database: 'test',
},
},
default: {
},
app: true,
agent: false,
};
Usage:
const client1 = app.mysql.get('db1');
client1.query(sql, values);
const client2 = app.mysql.get('db2');
client2.query(sql, values);
CRUD user guide
Create
const result = yield app.mysql.insert('posts', { title: 'Hello World' });
const insertSuccess = result.affectedRows === 1;
Read
const post = yield app.mysql.get('posts', { id: 12 });
const results = yield app.mysql.select('posts',{
where: { status: 'draft' },
orders: [['created_at','desc'], ['id','desc']],
limit: 10,
offset: 0
});
Update
const row = {
id: 123,
name: 'fengmk2',
otherField: 'other field value',
modifiedAt: app.mysql.literals.now,
};
const result = yield app.mysql.update('posts', row);
const updateSuccess = result.affectedRows === 1;
Delete
const result = yield app.mysql.delete('table-name', {
name: 'fengmk2'
});
Transaction
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.
const conn = yield app.mysql.beginTransaction();
try {
yield conn.insert(table, row1);
yield conn.update(table, row2);
yield conn.commit();
} catch (err) {
yield conn.rollback();
throw err;
}
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
const result = yield app.mysql.beginTransactionScope(function* (conn) {
yield conn.insert(table, row1);
yield conn.update(table, row2);
return { success: true };
}, ctx);
Advance
Custom SQL splicing
const results = yield app.mysql.query('update posts set hits = (hits + ?) where id = ?', [1, postId]);
Literal
If you want to call literals or functions in mysql , you can use Literal
.
Inner Literal
- NOW(): The database system time, you can obtain by
app.mysql.literals.now
.
yield app.mysql.insert(table, {
create_time: app.mysql.literals.now
});
Custom literal
The following demo showed how to call CONCAT(s1, ...sn)
funtion in mysql to do string splicing.
const Literal = app.mysql.literals.Literal;
const first = 'James';
const last = 'Bond';
yield app.mysql.insert(table, {
id: 123,
fullname: new Literal(`CONCAT("${first}", "${last}"`),
});
Questions & Suggestions
Please open an issue here.
License
MIT