Skip to content

Commit

Permalink
fix(db-postgres): create relationship-v2-v3 migration (#9178)
Browse files Browse the repository at this point in the history
### What?
This command from here:
#6339
```sh
payload migrate:create --file @payloadcms/db-postgres/relationships-v2-v3
```
stopped working after db-postgers and drizzle packages were separated 

### How?
Passes correct `dirname` to `getPredefinedMigration`

Additionally, adds support for `.js` files in `getPredefinedMigration`
  • Loading branch information
r1tsuu authored Nov 13, 2024
1 parent bcbca0e commit 5b9cee6
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 22 deletions.
9 changes: 8 additions & 1 deletion packages/db-postgres/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,17 @@ import {
requireDrizzleKit,
} from '@payloadcms/drizzle/postgres'
import { pgEnum, pgSchema, pgTable } from 'drizzle-orm/pg-core'
import path from 'path'
import { createDatabaseAdapter, defaultBeginTransaction } from 'payload'
import { fileURLToPath } from 'url'

import type { Args, PostgresAdapter } from './types.js'

import { connect } from './connect.js'

const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)

export function postgresAdapter(args: Args): DatabaseAdapterObj<PostgresAdapter> {
const postgresIDType = args.idType || 'serial'
const payloadIDType = postgresIDType === 'serial' ? 'number' : 'text'
Expand Down Expand Up @@ -88,6 +93,9 @@ export function postgresAdapter(args: Args): DatabaseAdapterObj<PostgresAdapter>
beforeSchemaInit: args.beforeSchemaInit ?? [],
createDatabase,
createExtensions,
createMigration(args) {
return createMigration.bind(this)({ ...args, dirname })
},
defaultDrizzleSnapshot,
disableCreateDatabase: args.disableCreateDatabase ?? false,
drizzle: undefined,
Expand Down Expand Up @@ -132,7 +140,6 @@ export function postgresAdapter(args: Args): DatabaseAdapterObj<PostgresAdapter>
createGlobal,
createGlobalVersion,
createJSONQuery,
createMigration,
createVersion,
defaultIDType: payloadIDType,
deleteMany,
Expand Down
9 changes: 8 additions & 1 deletion packages/db-vercel-postgres/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,17 @@ import {
requireDrizzleKit,
} from '@payloadcms/drizzle/postgres'
import { pgEnum, pgSchema, pgTable } from 'drizzle-orm/pg-core'
import path from 'path'
import { createDatabaseAdapter, defaultBeginTransaction } from 'payload'
import { fileURLToPath } from 'url'

import type { Args, VercelPostgresAdapter } from './types.js'

import { connect } from './connect.js'

const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)

export function vercelPostgresAdapter(args: Args = {}): DatabaseAdapterObj<VercelPostgresAdapter> {
const postgresIDType = args.idType || 'serial'
const payloadIDType = postgresIDType === 'serial' ? 'number' : 'text'
Expand Down Expand Up @@ -133,7 +138,9 @@ export function vercelPostgresAdapter(args: Args = {}): DatabaseAdapterObj<Verce
createGlobal,
createGlobalVersion,
createJSONQuery,
createMigration,
createMigration(args) {
return createMigration.bind(this)({ ...args, dirname })
},
createVersion,
defaultIDType: payloadIDType,
deleteMany,
Expand Down
6 changes: 1 addition & 5 deletions packages/drizzle/src/postgres/createMigration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ import type { CreateMigration } from 'payload'

import fs from 'fs'
import { createRequire } from 'module'
import path from 'path'
import { getPredefinedMigration, writeMigrationIndex } from 'payload'
import prompts from 'prompts'
import { fileURLToPath } from 'url'

import type { BasePostgresAdapter } from './types.js'

Expand All @@ -16,10 +14,8 @@ const require = createRequire(import.meta.url)

export const createMigration: CreateMigration = async function createMigration(
this: BasePostgresAdapter,
{ file, forceAcceptWarning, migrationName, payload },
{ dirname, file, forceAcceptWarning, migrationName, payload },
) {
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const dir = payload.db.migrationDir
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
Expand Down
33 changes: 18 additions & 15 deletions packages/payload/src/database/migrations/getPredefinedMigration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,28 +24,31 @@ export const getPredefinedMigration = async ({
if (file || migrationNameArg?.startsWith('@payloadcms/')) {
// removes the package name from the migrationName.
const migrationName = (file || migrationNameArg).split('/').slice(2).join('/')
let cleanPath = path.join(dirname, `./predefinedMigrations/${migrationName}.mjs`)
let cleanPath = path.join(dirname, `./predefinedMigrations/${migrationName}`)

// Check if predefined migration exists
if (fs.existsSync(cleanPath)) {
cleanPath = cleanPath.replaceAll('\\', '/')
const moduleURL = pathToFileURL(cleanPath)
try {
const { downSQL, imports, upSQL } = await eval(`import('${moduleURL.href}')`)
return { downSQL, imports, upSQL }
} catch (error) {
payload.logger.error({
error,
msg: `Error loading predefined migration ${migrationName}`,
})
process.exit(1)
}
if (fs.existsSync(`${cleanPath}.mjs`)) {
cleanPath = `${cleanPath}.mjs`
} else if (fs.existsSync(`${cleanPath}.js`)) {
cleanPath = `${cleanPath}.js`
} else {
payload.logger.error({
msg: `Canned migration ${migrationName} not found.`,
})
process.exit(1)
}

cleanPath = cleanPath.replaceAll('\\', '/')
const moduleURL = pathToFileURL(cleanPath)
try {
const { downSQL, imports, upSQL } = await eval(`import('${moduleURL.href}')`)
return { downSQL, imports, upSQL }
} catch (err) {
payload.logger.error({
err,
msg: `Error loading predefined migration ${migrationName}`,
})
process.exit(1)
}
}
return {}
}
2 changes: 2 additions & 0 deletions packages/payload/src/database/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ export type Connect = (args?: ConnectArgs) => Promise<void>
export type Destroy = () => Promise<void>

export type CreateMigration = (args: {
/** dirname of the package, required in drizzle */
dirname?: string
file?: string
/**
* Skips the prompt asking to create empty migrations
Expand Down

0 comments on commit 5b9cee6

Please sign in to comment.