path.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import nodePath from "path"
  2. import { customType } from "drizzle-orm/sqlite-core"
  3. import { AbsolutePath } from "../schema"
  4. function storagePath(input: string) {
  5. if (process.platform !== "win32") return input
  6. return input.replaceAll("\\", "/")
  7. }
  8. function isWindowsStoragePath(input: string) {
  9. return /^[A-Za-z]:\//.test(input) || input.startsWith("//")
  10. }
  11. function absolute(input: string) {
  12. const result = storagePath(input)
  13. if (!nodePath.posix.isAbsolute(result) && !(process.platform === "win32" && isWindowsStoragePath(result))) {
  14. throw new Error(`Path is not absolute: ${input}`)
  15. }
  16. return result
  17. }
  18. function toPlatform(input: string) {
  19. if (process.platform !== "win32" || !isWindowsStoragePath(input)) return input
  20. return input.replaceAll("/", "\\")
  21. }
  22. export const absoluteColumn = customType<{
  23. data: AbsolutePath
  24. driverData: string
  25. driverOutput: string
  26. }>({
  27. dataType() {
  28. return "text"
  29. },
  30. toDriver(input) {
  31. return absolute(input)
  32. },
  33. fromDriver(input) {
  34. return AbsolutePath.make(toPlatform(absolute(input)))
  35. },
  36. })
  37. // Legacy sessions may persist an empty directory. Keep that existing value
  38. // readable while normalizing and validating every real directory.
  39. export const directoryColumn = customType<{
  40. data: string
  41. driverData: string
  42. driverOutput: string
  43. }>({
  44. dataType() {
  45. return "text"
  46. },
  47. toDriver(input) {
  48. return input ? absolute(input) : input
  49. },
  50. fromDriver(input) {
  51. return input ? toPlatform(absolute(input)) : input
  52. },
  53. })
  54. export const pathColumn = customType<{
  55. data: string
  56. driverData: string
  57. driverOutput: string
  58. }>({
  59. dataType() {
  60. return "text"
  61. },
  62. toDriver(input) {
  63. return storagePath(input)
  64. },
  65. fromDriver(input) {
  66. return storagePath(input)
  67. },
  68. })
  69. export const absoluteArrayColumn = customType<{
  70. data: AbsolutePath[]
  71. driverData: string
  72. driverOutput: string
  73. }>({
  74. dataType() {
  75. return "text"
  76. },
  77. toDriver(input) {
  78. return JSON.stringify(input.map(absolute))
  79. },
  80. fromDriver(input) {
  81. return (JSON.parse(input) as string[]).map((item) => AbsolutePath.make(toPlatform(absolute(item))))
  82. },
  83. })