db_setup.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env node
  2. const params = require('../config/params');
  3. const r = require('../server/rethinkdb');
  4. if (!Object.entries) {
  5. const reduce = Function.call.bind(Array.prototype.reduce)
  6. const isEnumerable = Function.call.bind(Object.prototype.propertyIsEnumerable);
  7. const concat = Function.call.bind(Array.prototype.concat);
  8. const keys = Object.keys;
  9. // https://github.com/tc39/proposal-object-values-entries
  10. Object.entries = function entries(O) {
  11. return reduce(keys(O), (e, k) =>
  12. concat(e, typeof k === 'string' && isEnumerable(O, k) ? [[k, O[k]]] : []), []);
  13. };
  14. }
  15. const DB = params.RETHINKDB.DATABASE;
  16. const TABLES = [
  17. ['queue', {primaryKey: 'username'}],
  18. ];
  19. const INDICES = {};
  20. r.dbList()
  21. .then(dbs => {
  22. if (dbs.indexOf(DB) === -1) {
  23. console.log(`Create DB: ${DB}`);
  24. return r.dbCreate(DB);
  25. }
  26. })
  27. .then(() => r.db(DB).tableList())
  28. .then((tables=[]) => {
  29. const missing_tables = TABLES.filter(([t, _]) => tables.indexOf(t) === -1);
  30. return Promise.all(missing_tables.map(([table, options]) => {
  31. console.log(`Create table: ${table}`);
  32. return r.db(DB).tableCreate(table, options);
  33. }));
  34. })
  35. .then(() =>
  36. Promise.all(Object.entries(INDICES).map(([table, index_params]) =>
  37. r.db(DB).table(table).indexList()
  38. .then(indices =>
  39. Promise.all(Object.entries(index_params).map(([name, value]) => {
  40. if (indices.indexOf(name) !== -1) return Promise.resolve();
  41. console.log(`Create index on ${table}: ${name}`);
  42. return r.db(DB).table(table).indexCreate(name, value);
  43. }))
  44. )
  45. ))
  46. )
  47. .then(() => {
  48. r.getPoolMaster().drain();
  49. })