knexUtils.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const { isObject } = require('../utils/objectUtils');
  2. function getDialect(knex) {
  3. const type = typeof knex;
  4. return (
  5. (knex !== null &&
  6. (type === 'object' || type === 'function') &&
  7. knex.client &&
  8. knex.client.dialect) ||
  9. null
  10. );
  11. }
  12. function isPostgres(knex) {
  13. return getDialect(knex) === 'postgresql';
  14. }
  15. function isMySql(knex) {
  16. return getDialect(knex) === 'mysql';
  17. }
  18. function isSqlite(knex) {
  19. return getDialect(knex) === 'sqlite3';
  20. }
  21. function isMsSql(knex) {
  22. return getDialect(knex) === 'mssql';
  23. }
  24. function isKnexQueryBuilder(value) {
  25. return hasConstructor(value, 'Builder') && 'client' in value;
  26. }
  27. function isKnexJoinBuilder(value) {
  28. return hasConstructor(value, 'JoinClause') && 'joinType' in value;
  29. }
  30. function isKnexRaw(value) {
  31. return hasConstructor(value, 'Raw') && 'client' in value;
  32. }
  33. function isKnexTransaction(knex) {
  34. return (
  35. !!getDialect(knex) && typeof knex.commit === 'function' && typeof knex.rollback === 'function'
  36. );
  37. }
  38. function hasConstructor(value, constructorName) {
  39. return (
  40. isObject(value) &&
  41. typeof value.constructor === 'function' &&
  42. value.constructor.name === constructorName
  43. );
  44. }
  45. module.exports = {
  46. getDialect,
  47. isPostgres,
  48. isMySql,
  49. isSqlite,
  50. isMsSql,
  51. isKnexQueryBuilder,
  52. isKnexJoinBuilder,
  53. isKnexRaw,
  54. isKnexTransaction
  55. };