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-mysql

v4.0.0

Published

MySQL plugin for egg

Downloads

24,180

Readme

egg-mysql

NPM version Node.js CI Test coverage npm download

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.ts to enable MySQL plugin:

export default {
  mysql: {
    enable: true,
    package: 'egg-mysql',
  },
}

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

Simple database instance

export default {
  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:

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

Multiple database instance

export default {
  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:

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

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

CRUD user guide

Create

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

Read

// get
const post = await app.mysql.get('posts', { id: 12 });
// query
const results = await app.mysql.select('posts',{
  where: { status: 'draft' },
  orders: [['created_at','desc'], ['id','desc']],
  limit: 10,
  offset: 0
});

Update

// 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 = await app.mysql.update('posts', row);
const updateSuccess = result.affectedRows === 1;

Delete

const result = await 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 = await app.mysql.beginTransaction();

try {
  await conn.insert(table, row1);
  await conn.update(table, row2);
  await conn.commit();
} catch (err) {
  // error, rollback
  await conn.rollback(); // rollback call won't throw err
  throw err;
}

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
const result = await app.mysql.beginTransactionScope(async (conn) => {
  // don't commit or rollback by yourself
  await conn.insert(table, row1);
  await 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

const results = await 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.
await 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.

const Literal = app.mysql.literals.Literal;
const first = 'James';
const last = 'Bond';
await 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

Contributors

|fengmk2|jtyjty99999|popomore|atian25|dead-horse|AntiMoron| | :---: | :---: | :---: | :---: | :---: | :---: | guoshencheng|cnwangjie|starandtina|shangwenhe

This project follows the git-contributor spec, auto updated at Sat Dec 03 2022 22:52:06 GMT+0800.