Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

dj-egg-mysql

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dj-egg-mysql - npm Package Compare versions

Comparing version 3.0.3 to 3.0.4

2

package.json
{
"name": "dj-egg-mysql",
"version": "3.0.3",
"version": "3.0.4",
"description": "MySQL plugin for egg",

@@ -5,0 +5,0 @@ "eggPlugin": {

@@ -1,2 +0,3 @@

# egg-mysql
# dj-egg-mysql(对egg-mysql进行修改。不在依赖ali-rds,用法参考)
[dj-node-mysql]:'https://www.npmjs.com/package/dj-node-mysql'

@@ -23,18 +24,14 @@ [![NPM version][npm-image]][npm-url]

Aliyun rds client(support mysql portocal) for egg framework
MySQL 插件是为 egg 提供 MySQL 数据库访问的功能
## Install
## 安装
```bash
$ npm i egg-mysql --save
$ npm i dj-egg-mysql --save
```
MySQL Plugin for egg, support egg application access to MySQL database.
## 配置
This plugin based on [ali-rds](https://github.com/ali-sdk/ali-rds), if you want to know specific usage, you should refer to the document of [ali-rds](https://github.com/ali-sdk/ali-rds).
通过 `config/plugin.js` 配置启动 MySQL 插件:
## Configuration
Change `${app_root}/config/plugin.js` to enable MySQL plugin:
```js

@@ -47,207 +44,2 @@ exports.mysql = {

Configure database information in `${app_root}/config/config.default.js`:
### Simple database instance
```js
exports.mysql = {
// database configuration
client: {
// host
host: 'mysql.com',
// port
port: '3306',
// username
user: 'test_user',
// password
password: 'test_password',
// database
database: 'test',
},
// load into app, default is open
app: true,
// load into agent, default is close
agent: false,
};
```
Usage:
```js
app.mysql.query(sql, values); // you can access to simple database instance by using app.mysql.
```
### Multiple database instance
```js
exports.mysql = {
clients: {
// clientId, access the client instance by app.mysql.get('clientId')
db1: {
// host
host: 'mysql.com',
// port
port: '3306',
// username
user: 'test_user',
// password
password: 'test_password',
// database
database: 'test',
},
// ...
},
// default configuration for all databases
default: {
},
// load into app, default is open
app: true,
// load into agent, default is close
agent: false,
};
```
Usage:
```js
const client1 = app.mysql.get('db1');
client1.query(sql, values);
const client2 = app.mysql.get('db2');
client2.query(sql, values);
```
## CRUD user guide
### Create
```js
// insert
const result = yield app.mysql.insert('posts', { title: 'Hello World' });
const insertSuccess = result.affectedRows === 1;
```
### Read
```js
// get
const post = yield app.mysql.get('posts', { id: 12 });
// query
const results = yield app.mysql.select('posts',{
where: { status: 'draft' },
orders: [['created_at','desc'], ['id','desc']],
limit: 10,
offset: 0
});
```
### Update
```js
// update by primary key ID, and refresh
const row = {
id: 123,
name: 'fengmk2',
otherField: 'other field value',
modifiedAt: app.mysql.literals.now, // `now()` on db server
};
const result = yield app.mysql.update('posts', row);
const updateSuccess = result.affectedRows === 1;
```
### Delete
```js
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.
```js
const conn = yield app.mysql.beginTransaction();
try {
yield conn.insert(table, row1);
yield conn.update(table, row2);
yield conn.commit();
} catch (err) {
// error, rollback
yield conn.rollback(); // rollback call won't throw err
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
```js
const result = yield app.mysql.beginTransactionScope(function* (conn) {
// don't commit or rollback by yourself
yield conn.insert(table, row1);
yield conn.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
```js
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`.
```js
yield app.mysql.insert(table, {
create_time: app.mysql.literals.now
});
// INSERT INTO `$table`(`create_time`) VALUES(NOW())
```
#### Custom literal
The following demo showed how to call `CONCAT(s1, ...sn)` funtion in mysql to do string splicing.
```js
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}"`),
});
// INSERT INTO `$table`(`id`, `fullname`) VALUES(123, CONCAT("James", "Bond"))
```
## Questions & Suggestions
Please open an issue [here](https://github.com/eggjs/egg/issues).
## License
[MIT](LICENSE)
在 `config/config.${env}.js` 配置各个环境的数据库连接信息:
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc