Skip to content

Commit

Permalink
refactor: optimize database schema generation bin script (#10086)
Browse files Browse the repository at this point in the history
* Avoids additional file system writes (1 for `await writeFile` and then
`npx prettier --write`) instead prettier now formats the javascript
string directly. Went from 650 MS to 250 MS for the prettify block.
* Disables database connection, since the `db.generateSchema` doesn't
need connection, this also disables Drizzle schema push.
* Properly exits the bin script process.
  • Loading branch information
r1tsuu authored Dec 20, 2024
1 parent 7292220 commit 7c4ea5b
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 11 deletions.
15 changes: 7 additions & 8 deletions packages/drizzle/src/utilities/createSchemaGenerator.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import type { GenerateSchema } from 'payload'

import { exec } from 'child_process'
import { existsSync } from 'fs'
import { writeFile } from 'fs/promises'
import path from 'path'
import { promisify } from 'util'

import type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'

const execAsync = promisify(exec)

/**
* @example
* console.log(sanitizeObjectKey("oneTwo")); // oneTwo
Expand Down Expand Up @@ -271,7 +267,7 @@ declare module '${this.packageName}/types' {
*/
`

const code = [
let code = [
warning,
...importDeclarationsSanitized,
schemaDeclaration,
Expand All @@ -295,15 +291,18 @@ declare module '${this.packageName}/types' {
}
}

await writeFile(outputFile, code, 'utf-8')

if (prettify) {
try {
await execAsync(`npx prettier ${outputFile} --write`)
const prettier = await import('prettier')
const configPath = await prettier.resolveConfigFile()
const config = configPath ? await prettier.resolveConfig(configPath) : {}
code = await prettier.format(code, { ...config, parser: 'typescript' })
// eslint-disable-next-line no-empty
} catch {}
}

await writeFile(outputFile, code, 'utf-8')

if (log) {
this.payload.logger.info(`Written ${outputFile}`)
}
Expand Down
11 changes: 9 additions & 2 deletions packages/payload/src/bin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import path from 'path'
import type { BinScript } from '../config/types.js'

import { findConfig } from '../config/find.js'
import { getPayload } from '../index.js'
import payload, { getPayload } from '../index.js'
import { generateImportMap } from './generateImportMap/index.js'
import { generateTypes } from './generateTypes.js'
import { info } from './info.js'
Expand Down Expand Up @@ -110,7 +110,12 @@ export const bin = async () => {
}

if (script === 'generate:db-schema') {
const payload = await getPayload({ config })
// Barebones instance to access database adapter, without connecting to the DB
await payload.init({
config,
disableDBConnect: true,
disableOnInit: true,
})

if (typeof payload.db.generateSchema !== 'function') {
payload.logger.error({
Expand All @@ -124,6 +129,8 @@ export const bin = async () => {
log: args.log === 'false' ? false : true,
prettify: args.prettify === 'false' ? false : true,
})

process.exit(0)
}

console.error(`Unknown script: "${script}".`)
Expand Down
39 changes: 38 additions & 1 deletion test/relationships/payload-generated-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -422,22 +422,44 @@ export const polymorphic_relationships = pgTable(
}),
)

export const polymorphic_relationships_locales = pgTable(
'polymorphic_relationships_locales',
{
id: serial('id').primaryKey(),
_locale: enum__locales('_locale').notNull(),
_parentID: integer('_parent_id').notNull(),
},
(columns) => ({
_localeParent: uniqueIndex('polymorphic_relationships_locales_locale_parent_id_unique').on(
columns._locale,
columns._parentID,
),
_parentIdFk: foreignKey({
columns: [columns['_parentID']],
foreignColumns: [polymorphic_relationships.id],
name: 'polymorphic_relationships_locales_parent_id_fk',
}).onDelete('cascade'),
}),
)

export const polymorphic_relationships_rels = pgTable(
'polymorphic_relationships_rels',
{
id: serial('id').primaryKey(),
order: integer('order'),
parent: integer('parent_id').notNull(),
path: varchar('path').notNull(),
locale: enum__locales('locale'),
moviesID: integer('movies_id'),
},
(columns) => ({
order: index('polymorphic_relationships_rels_order_idx').on(columns.order),
parentIdx: index('polymorphic_relationships_rels_parent_idx').on(columns.parent),
pathIdx: index('polymorphic_relationships_rels_path_idx').on(columns.path),
localeIdx: index('polymorphic_relationships_rels_locale_idx').on(columns.locale),
polymorphic_relationships_rels_movies_id_idx: index(
'polymorphic_relationships_rels_movies_id_idx',
).on(columns.moviesID),
).on(columns.moviesID, columns.locale),
parentFk: foreignKey({
columns: [columns['parent']],
foreignColumns: [polymorphic_relationships.id],
Expand Down Expand Up @@ -1093,6 +1115,16 @@ export const relations_movie_reviews = relations(movie_reviews, ({ one, many })
relationName: '_rels',
}),
}))
export const relations_polymorphic_relationships_locales = relations(
polymorphic_relationships_locales,
({ one }) => ({
_parentID: one(polymorphic_relationships, {
fields: [polymorphic_relationships_locales._parentID],
references: [polymorphic_relationships.id],
relationName: '_locales',
}),
}),
)
export const relations_polymorphic_relationships_rels = relations(
polymorphic_relationships_rels,
({ one }) => ({
Expand All @@ -1111,6 +1143,9 @@ export const relations_polymorphic_relationships_rels = relations(
export const relations_polymorphic_relationships = relations(
polymorphic_relationships,
({ many }) => ({
_locales: many(polymorphic_relationships_locales, {
relationName: '_locales',
}),
_rels: many(polymorphic_relationships_rels, {
relationName: '_rels',
}),
Expand Down Expand Up @@ -1347,6 +1382,7 @@ type DatabaseSchema = {
movie_reviews: typeof movie_reviews
movie_reviews_rels: typeof movie_reviews_rels
polymorphic_relationships: typeof polymorphic_relationships
polymorphic_relationships_locales: typeof polymorphic_relationships_locales
polymorphic_relationships_rels: typeof polymorphic_relationships_rels
tree: typeof tree
pages_menu: typeof pages_menu
Expand Down Expand Up @@ -1377,6 +1413,7 @@ type DatabaseSchema = {
relations_directors: typeof relations_directors
relations_movie_reviews_rels: typeof relations_movie_reviews_rels
relations_movie_reviews: typeof relations_movie_reviews
relations_polymorphic_relationships_locales: typeof relations_polymorphic_relationships_locales
relations_polymorphic_relationships_rels: typeof relations_polymorphic_relationships_rels
relations_polymorphic_relationships: typeof relations_polymorphic_relationships
relations_tree: typeof relations_tree
Expand Down

0 comments on commit 7c4ea5b

Please sign in to comment.