npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

egg-dj-mysql

v1.0.0

Published

MySQL plugin for egg

Downloads

3

Readme

egg-dj-mysql(与egg-mysql保持一致,依赖的ali-rds 修改为dj-ali-rds)

MySQL 插件是为 egg 提供 MySQL 数据库访问的功能

此插件基于 dj-ali-rds 实现一个简单的配置封装,具体使用方法你还需要阅读 [dj-ali-rds] 的文档。

安装

$ npm i egg-dj-mysql --save

配置

通过 config/plugin.js 配置启动 MySQL 插件:

exports.mysql = {
  enable: true,
  package: 'egg-dj-mysql',
};

config/config.${env}.js 配置各个环境的数据库连接信息:

单数据源

exports.mysql = {
  // 单数据库信息配置
  client: {
    // host
    host: 'mysql.com',
    // 端口号
    port: '3306',
    // 用户名
    user: 'test_user',
    // 密码
    password: 'test_password',
    // 数据库名
    database: 'test',    
  },
  // 是否加载到 app 上,默认开启
  app: true,
  // 是否加载到 agent 上,默认关闭
  agent: false,
};

使用方式:

app.mysql.query(sql, values); // 单实例可以直接通过 app.mysql 访问

多数据源

exports.mysql = {
  clients: {
    // clientId, 获取client实例,需要通过 app.mysql.get('clientId') 获取
    db1: {
      // host
      host: 'mysql.com',
      // 端口号
      port: '3306',
      // 用户名
      user: 'test_user',
      // 密码
      password: 'test_password',
      // 数据库名
      database: 'test',
    },
    // ...
  },
  // 所有数据库配置的默认值
  default: {

  },

  // 是否加载到 app 上,默认开启
  app: true,
  // 是否加载到 agent 上,默认关闭
  agent: false,
};

使用方式:

const client1 = app.mysql.get('db1');
client1.query(sql, values);

const client2 = app.mysql.get('db2');
client2.query(sql, values);

扩展

app.js

app.mysql

如果开启了 config.mysql.app = true,则会在 app 上注入 ali-rds 客户端 的 Singleton 单例

app.mysql.query(sql);
app.mysql.get('db1').query(sql);

agent.js

agent.mysql

如果开启了 config.mysql.agent = true,则会在 agent 上注入 ali-rds 客户端 的 Singleton 单例

agent.mysql.query(sql);
agent.mysql.get('db1').query(sql);

CRUD 使用指南

Create

// 插入
const result = yield app.mysql.insert('posts', { title: 'Hello World' });
const insertSuccess = result.affectedRows === 1;

Read

Select

  • Select all rows
let rows = yield db.select('table-name');

=> SELECT * FROM `table-name`
  • Select rows with condition
let rows = yield db.select('table-name', {
  where: {
    type: 'javascript'
  },
  columns: ['author', 'title'],
  orders: [['id', 'desc']]
});

=> SELECT `author`, `title` FROM `table-name`
 WHERE `type` = 'javascript' ORDER BY `id` DESC
let rows = yield db.select('table-name', {
      where: { a.state: 0, a.create_time: {'>=':1522133665520, '<=':Date.now()}},
      columns: ['.aname as kk', 'a.like_count', 'a.avatar', 'a.uid'],
      orders: [['like_count', 'desc']],
      limit: limit,
      joins:([{
        'as': 'b',
        join: 'left',
        table: 'table2',
        on: ['a.uid', 'b.user_id']
      }]),
      group: 'a.uid',
      offset: (page - 1)*limit
    })
});
#### 连表查询第一张表默认为a表
=> SELECT `a.name` as kk, `a.like_count`, 'a.avatar', 'a.uid' FROM `table-name` AS
LEFT JOIN table2 as b ON a.uid = b.user_id
 WHERE a.state =0 AND a.create_time>=1522133665520 AND a.create_time<=Date.now()  GROUP BY 'a.uid' ORDER BY `a.like_count` DESC

Update

// 修改数据,将会根据主键 ID 查找,并更新
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

const result = yield app.mysql.delete('table-name', {
  name: 'fengmk2'
});

事务

手动控制

  • 优点:beginTransaction, commit 或 rollback 都由开发者来完全控制,可以做到非常细粒度的控制。
  • 缺点:手写代码比较多,不是每个人都能写好。忘记了捕获异常和 cleanup 都会导致严重 bug。
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;
}

自动控制:Transaction with scope

  • API:*beginTransactionScope(scope, ctx)
    • scope: 一个 generatorFunction,在这个函数里面执行这次事务的所有 sql 语句。
    • ctx: 当前请求的上下文对象,传入 ctx 可以保证即便在出现事务嵌套的情况下,一次请求中同时只有一个激活状态的事务。
  • 优点:使用简单,不容易犯错,就感觉事务不存在的样子。
  • 缺点:整个事务要么成功,要么失败,无法做细粒度控制。
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 是当前请求的上下文,如果是在 service 文件中,可以从 `this.ctx` 获取到
// if error throw on scope, will auto rollback

进阶

自定义SQL拼接

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

表达式(Literal)

如果需要调用mysql内置的函数(或表达式),可以使用Literal

内置表达式

  • NOW(): 数据库当前系统时间,通过app.mysql.literals.now获取。
yield app.mysql.insert(table, {
  create_time: app.mysql.literals.now
});

// INSERT INTO `$table`(`create_time`) VALUES(NOW())

自定义表达式

下例展示了如何调用mysql内置的CONCAT(s1, ...sn)函数,做字符串拼接。

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.

License

MIT