mysql.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const { createPool, createConnection } = require( 'mysql2/promise' );
  2. const cpus = require( 'os' ).cpus().length
  3. let clientOpts = {
  4. host: process.env.DB_HOST || 'localhost',
  5. user: 'benchmarkdbuser',
  6. password: 'benchmarkdbpass',
  7. database: 'hello_world'
  8. };
  9. let pool
  10. const execute = async ( text, values ) => ( await pool.execute( text, values || undefined ) )[0]
  11. module.exports = {
  12. async init() {
  13. const client = await createConnection( clientOpts )
  14. const res = await client.query( 'SHOW VARIABLES LIKE "max_connections"' )
  15. let maxConnections = Math.floor( res[0][0].Value * 0.9 / cpus )
  16. //1 worker per cpu, each worker pool gets a fraction of the max connections
  17. //only use 90% to avoid too many clients errors
  18. pool = createPool( Object.assign( { ...clientOpts }, { max: maxConnections } ) )
  19. await client.end()
  20. },
  21. allFortunes: async () =>
  22. execute( 'SELECT * FROM fortune' ),
  23. worldById: async ( id ) =>
  24. execute( 'SELECT * FROM world WHERE id = ?', [id] )
  25. .then( arr => arr[0] ),
  26. allWorlds: async () =>
  27. execute( 'SELECT * FROM world' ),
  28. bulkUpdateWorld: async worlds => Promise.all(
  29. worlds.map( world =>
  30. execute( 'UPDATE world SET randomnumber = ? WHERE id = ?',
  31. [world.randomnumber, world.id] ) )
  32. ).then( () => worlds )
  33. }