## Description Prior to this change, the `defaultValue` for fields have only been used in the application layer of Payload. With this change, you get the added benefit of having the database columns get the default also. This is especially helpful when adding new columns to postgres with existing data to avoid needing to write complex migrations. In MongoDB this change applies the default to the Mongoose model which is useful when calling payload.db.create() directly. This only works for statically defined values. 🙏 A big thanks to @r1tsuu for the feature and implementation idea as I lifted some code from PR https://github.com/payloadcms/payload/pull/6983 - [x] I have read and understand the [CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md) document in this repository. ## Type of change - [x] New feature (non-breaking change which adds functionality) - [x] This change requires a documentation update ## Checklist: - [x] I have added tests that prove my fix is effective or that my feature works - [x] Existing test suite passes locally with my changes - [x] I have made corresponding changes to the documentation
48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
import type { CreateGlobalVersionArgs, PayloadRequest, TypeWithID, TypeWithVersion } from 'payload'
|
|
|
|
import { sql } from 'drizzle-orm'
|
|
import { buildVersionGlobalFields } from 'payload'
|
|
import toSnakeCase from 'to-snake-case'
|
|
|
|
import type { DrizzleAdapter } from './types.js'
|
|
|
|
import { upsertRow } from './upsertRow/index.js'
|
|
|
|
export async function createGlobalVersion<T extends TypeWithID>(
|
|
this: DrizzleAdapter,
|
|
{ autosave, globalSlug, req = {} as PayloadRequest, versionData }: CreateGlobalVersionArgs,
|
|
) {
|
|
const db = this.sessions[await req?.transactionID]?.db || this.drizzle
|
|
const global = this.payload.globals.config.find(({ slug }) => slug === globalSlug)
|
|
|
|
const tableName = this.tableNameMap.get(`_${toSnakeCase(global.slug)}${this.versionsSuffix}`)
|
|
|
|
const result = await upsertRow<TypeWithVersion<T>>({
|
|
adapter: this,
|
|
data: {
|
|
autosave,
|
|
latest: true,
|
|
version: versionData,
|
|
},
|
|
db,
|
|
fields: buildVersionGlobalFields(global),
|
|
operation: 'create',
|
|
req,
|
|
tableName,
|
|
})
|
|
|
|
const table = this.tables[tableName]
|
|
if (global.versions.drafts) {
|
|
await this.execute({
|
|
db,
|
|
sql: sql`
|
|
UPDATE ${table}
|
|
SET latest = false
|
|
WHERE ${table.id} != ${result.id};
|
|
`,
|
|
})
|
|
}
|
|
|
|
return result
|
|
}
|