even even more

This commit is contained in:
Sasha
2025-06-03 01:09:59 +03:00
parent 115af04406
commit e7749468c2
13 changed files with 63 additions and 36 deletions

View File

@@ -1,5 +1,5 @@
export const appendPrefixToObjectKeys = <T>(obj: Record<string, unknown>, prefix: string): T =>
Object.entries(obj).reduce((res, [key, val]) => {
Object.entries(obj).reduce((res: any, [key, val]) => {
res[`${prefix}_${key}`] = val
return res
}, {} as T)

View File

@@ -34,11 +34,11 @@ export const buildCreateMigration = ({
const drizzleJsonAfter = await generateDrizzleJson(this.schema)
const [yyymmdd, hhmmss] = new Date().toISOString().split('T')
const formattedDate = yyymmdd.replace(/\D/g, '')
const formattedTime = hhmmss.split('.')[0].replace(/\D/g, '')
let imports: string = ''
let downSQL: string
let upSQL: string
const formattedDate = yyymmdd?.replace(/\D/g, '')
const formattedTime = hhmmss?.split('.')[0]?.replace(/\D/g, '')
let imports: string | undefined = ''
let downSQL: string | undefined
let upSQL: string | undefined
;({ downSQL, imports, upSQL } = await getPredefinedMigration({
dirname,
file,

View File

@@ -9,7 +9,11 @@ export const createBlocksMap = (data: Record<string, unknown>): BlocksMap => {
if (key.startsWith('_blocks_') && Array.isArray(rows)) {
let blockType = key.replace('_blocks_', '')
const parsed = blockType.split('_')
if (parsed.length === 2 && Number.isInteger(Number(parsed[1]))) {
if (
parsed.length === 2 &&
Number.isInteger(Number(parsed[1])) &&
typeof parsed[0] === 'string'
) {
blockType = parsed[0]
}
@@ -20,7 +24,7 @@ export const createBlocksMap = (data: Record<string, unknown>): BlocksMap => {
}
row.blockType = blockType
blocksMap[row._path].push(row)
blocksMap[row._path]?.push(row)
delete row._path
}
@@ -30,7 +34,7 @@ export const createBlocksMap = (data: Record<string, unknown>): BlocksMap => {
}
})
Object.entries(blocksMap).reduce((sortedBlocksMap, [path, blocks]) => {
Object.entries(blocksMap).reduce((sortedBlocksMap: any, [path, blocks]) => {
sortedBlocksMap[path] = blocks.sort((a, b) => {
if (typeof a._order === 'number' && typeof b._order === 'number') {
return a._order - b._order

View File

@@ -75,7 +75,7 @@ export const createSchemaGenerator = ({
let schemaDeclaration: null | string = null
if (this.schemaName) {
if (this.schemaName && schemaImport) {
addImport(corePackage, schemaImport)
schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`
}
@@ -113,11 +113,18 @@ export const createSchemaGenerator = ({
for (const tableName in this.rawTables) {
const table = this.rawTables[tableName]
if (!table) {
continue
}
const extrasDeclarations: string[] = []
if (table.indexes) {
for (const key in table.indexes) {
const index = table.indexes[key]
if (!index) {
continue
}
let indexDeclaration = `${sanitizeObjectKey(key)}: ${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`
indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`
extrasDeclarations.push(indexDeclaration)
@@ -127,7 +134,9 @@ export const createSchemaGenerator = ({
if (table.foreignKeys) {
for (const key in table.foreignKeys) {
const foreignKey = table.foreignKeys[key]
if (!foreignKey) {
continue
}
let foreignKeyDeclaration = `${sanitizeObjectKey(key)}: foreignKey({
columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],
foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],
@@ -179,10 +188,16 @@ ${Object.entries(table.columns)
for (const tableName in this.rawRelations) {
const relations = this.rawRelations[tableName]
if (!relations) {
continue
}
const properties: string[] = []
for (const key in relations) {
const relation = relations[key]
if (!relation) {
continue
}
let declaration: string
if (relation.type === 'one') {
@@ -221,7 +236,7 @@ ${Object.entries(table.columns)
relationsDeclarations.push(declaration)
}
if (enumDeclarations.length && !this.schemaName) {
if (enumDeclarations.length && !this.schemaName && enumImport) {
addImport(corePackage, enumImport)
}
@@ -229,6 +244,9 @@ ${Object.entries(table.columns)
for (const moduleName in importDeclarations) {
const moduleImports = importDeclarations[moduleName]
if (!moduleImports) {
continue
}
importDeclarationsSanitized.push(
`import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,

View File

@@ -26,7 +26,9 @@ type Args = {
/**
* Extends the passed table with additional columns / extra config
*/
export const extendDrizzleTable = ({ columns, extraConfig, table }: Args): void => {
export const extendDrizzleTable = ({ columns, extraConfig, table: tableFromArgs }: Args): void => {
// hard drizzle types
const table: any = tableFromArgs
const InlineForeignKeys = Object.getOwnPropertySymbols(table).find((symbol) => {
return symbol.description?.includes('InlineForeignKeys')
})
@@ -53,7 +55,7 @@ export const extendDrizzleTable = ({ columns, extraConfig, table }: Args): void
if (extraConfig) {
const originalExtraConfigBuilder = table[DrizzleSymbol.ExtraConfigBuilder]
table[DrizzleSymbol.ExtraConfigBuilder] = (t) => {
table[DrizzleSymbol.ExtraConfigBuilder] = (t: any) => {
return {
...originalExtraConfigBuilder(t),
...extraConfig(t),

View File

@@ -14,10 +14,10 @@ export const getMigrationTemplate = ({
}: MigrationTemplateArgs): string => `import { MigrateUpArgs, MigrateDownArgs, sql } from '${packageName}'
${imports ? `${imports}\n` : ''}
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
${indent(upSQL)}
${upSQL ? indent(upSQL) : ''}
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
${indent(downSQL)}
${downSQL ? indent(downSQL) : ''}
}
`

View File

@@ -1,9 +1,9 @@
import type { Table } from 'drizzle-orm'
export const getNameFromDrizzleTable = (table: Table): string => {
const symbol = Object.getOwnPropertySymbols(table).find((symb) =>
symb.description.includes('Name'),
const symbol = Object.getOwnPropertySymbols(table).find(
(symb) => symb && symb.description?.includes('Name'),
)
return table[symbol]
return (table as any)[symbol!]
}

View File

@@ -4,7 +4,7 @@ import { fieldAffectsData, fieldHasSubFields, fieldShouldBeLocalized } from 'pay
export const hasLocalesTable = ({
fields,
parentIsLocalized,
parentIsLocalized = false,
}: {
fields: Field[]
/**

View File

@@ -6,11 +6,11 @@ export const isPolymorphicRelationship = (
relationTo: CollectionSlug
value: number | string
} => {
return (
return Boolean(
value &&
typeof value === 'object' &&
'relationTo' in value &&
typeof value.relationTo === 'string' &&
'value' in value
typeof value === 'object' &&
'relationTo' in value &&
typeof value.relationTo === 'string' &&
'value' in value,
)
}

View File

@@ -31,5 +31,5 @@ export const migrationTableExists = async (
const [row] = result.rows
return row && typeof row === 'object' && 'exists' in row && !!row.exists
return Boolean(row && typeof row === 'object' && 'exists' in row && !!row.exists)
}

View File

@@ -35,14 +35,14 @@ export const pushDevSchema = async (adapter: DrizzleAdapter) => {
return
} else {
previousSchema.localeCodes = localeCodes
previousSchema.localeCodes = localeCodes || null
previousSchema.rawTables = adapter.rawTables
}
}
const { pushSchema } = adapter.requireDrizzleKit()
const { extensions = {}, tablesFilter } = adapter as BasePostgresAdapter
const { extensions = {}, tablesFilter } = adapter as unknown as BasePostgresAdapter
// This will prompt if clarifications are needed for Drizzle to push new schema
const { apply, hasDataLoss, warnings } = await pushSchema(

View File

@@ -9,5 +9,7 @@ export const rawConstraint = (value: unknown) => ({
})
export const isRawConstraint = (value: unknown): value is ReturnType<typeof rawConstraint> => {
return value && typeof value === 'object' && 'type' in value && value.type === RawConstraintSymbol
return Boolean(
value && typeof value === 'object' && 'type' in value && value.type === RawConstraintSymbol,
)
}

View File

@@ -27,7 +27,7 @@ const getFlattenedFieldNames = (args: {
prefix?: string
}): { localized?: boolean; name: string }[] => {
const { fields, parentIsLocalized, prefix = '' } = args
return fields.reduce((fieldsToUse, field) => {
return fields.reduce<{ localized?: boolean; name: string }[]>((fieldsToUse, field) => {
let fieldPrefix = prefix
if (
@@ -43,7 +43,8 @@ const getFlattenedFieldNames = (args: {
...fieldsToUse,
...getFlattenedFieldNames({
fields: field.fields,
parentIsLocalized: parentIsLocalized || ('localized' in field && field.localized),
parentIsLocalized:
(parentIsLocalized || ('localized' in field && field.localized)) ?? false,
prefix: fieldPrefix,
}),
]
@@ -52,7 +53,7 @@ const getFlattenedFieldNames = (args: {
if (field.type === 'tabs') {
return [
...fieldsToUse,
...field.tabs.reduce((tabFields, tab) => {
...field.tabs.reduce<{ localized?: boolean; name: string }[]>((tabFields, tab) => {
fieldPrefix = 'name' in tab ? `${prefix}_${tab.name}` : prefix
return [
...tabFields,
@@ -60,7 +61,7 @@ const getFlattenedFieldNames = (args: {
? [{ ...tab, type: 'tab' }]
: getFlattenedFieldNames({
fields: tab.fields,
parentIsLocalized: parentIsLocalized || tab.localized,
parentIsLocalized: (parentIsLocalized || tab.localized) ?? false,
prefix: fieldPrefix,
})),
]
@@ -119,13 +120,13 @@ export const validateExistingBlockIsIdentical = ({
export const InternalBlockTableNameIndex = Symbol('InternalBlockTableNameIndex')
export const setInternalBlockIndex = (block: FlattenedBlock, index: number) => {
block[InternalBlockTableNameIndex] = index
;(block as any)[InternalBlockTableNameIndex] = index
}
export const resolveBlockTableName = (block: FlattenedBlock, originalTableName: string) => {
if (!block[InternalBlockTableNameIndex]) {
if (!(block as any)[InternalBlockTableNameIndex]) {
return originalTableName
}
return `${originalTableName}_${block[InternalBlockTableNameIndex]}`
return `${originalTableName}_${(block as any)[InternalBlockTableNameIndex]}`
}