knex.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. function knexUtils(knex) {
  2. function truncatedTimestamp(columnName, precision = 'hour') {
  3. switch (knex.client.driverName) {
  4. case 'sqlite3':
  5. case 'better-sqlite3':
  6. // SQLite uses strftime for date truncation
  7. const sqliteFormats = {
  8. second: '%Y-%m-%d %H:%M:%S',
  9. minute: '%Y-%m-%d %H:%M:00',
  10. hour: '%Y-%m-%d %H:00:00',
  11. day: '%Y-%m-%d 00:00:00',
  12. };
  13. return knex.raw(`strftime('${sqliteFormats[precision]}', ${columnName})`); // Default to 'hour'
  14. case 'mssql':
  15. // For MSSQL, we can use FORMAT or CONVERT to truncate the timestamp
  16. const mssqlFormats = {
  17. second: 'yyyy-MM-dd HH:mm:ss',
  18. minute: 'yyyy-MM-dd HH:mm:00',
  19. hour: 'yyyy-MM-dd HH:00:00',
  20. day: 'yyyy-MM-dd 00:00:00',
  21. };
  22. return knex.raw(`FORMAT(${columnName}, '${mssqlFormats[precision]}'`);
  23. case 'pg':
  24. case 'pgnative':
  25. case 'cockroachdb':
  26. // PostgreSQL has the `date_trunc` function, which is ideal for this task
  27. return knex.raw(`date_trunc(?, ${columnName})`, [precision]);
  28. case 'oracle':
  29. case 'oracledb':
  30. // Oracle truncates dates using the `TRUNC` function
  31. return knex.raw(`TRUNC(${columnName}, ?)`, [precision]);
  32. case 'mysql':
  33. case 'mysql2':
  34. // MySQL can use the DATE_FORMAT function to truncate
  35. const mysqlFormats = {
  36. second: '%Y-%m-%d %H:%i:%s',
  37. minute: '%Y-%m-%d %H:%i:00',
  38. hour: '%Y-%m-%d %H:00:00',
  39. day: '%Y-%m-%d 00:00:00',
  40. };
  41. return knex.raw(`DATE_FORMAT(${columnName}, '${mysqlFormats[precision]}')`);
  42. default:
  43. throw new Error(`${this.client.driverName} does not support timestamp truncation with precision`);
  44. }
  45. }
  46. return {
  47. truncatedTimestamp
  48. }
  49. }
  50. module.exports = {
  51. knexUtils
  52. }