chore(db-sqlite): enable TypeScript strict (#11831)

- I installed `@types/uuid` because typescript required it in a file
- In `packages/db-sqlite/src/index.ts` I see four more errors in my IDE
that don't appear when I run the typecheck in the CLI with `tsc
--noEmit`. The same thing happened in
https://github.com/payloadcms/payload/pull/11560. Also referencing
https://github.com/payloadcms/payload/pull/11226#issuecomment-2713898801
for traceability.
This commit is contained in:
Germán Jabloñski
2025-03-24 23:41:07 -03:00
committed by GitHub
parent eb1434e986
commit fe9317a0dd
14 changed files with 66 additions and 78 deletions

View File

@@ -85,6 +85,7 @@
"@payloadcms/eslint-config": "workspace:*",
"@types/pg": "8.10.2",
"@types/to-snake-case": "1.0.0",
"@types/uuid": "10.0.0",
"payload": "workspace:*"
},
"peerDependencies": {

View File

@@ -23,6 +23,9 @@ export const columnToCodeConverter: ColumnToCodeConverter = ({
case 'enum': {
let options: string[]
if ('locale' in column) {
if (!locales?.length) {
throw new Error('Locales must be defined for locale columns')
}
options = locales
} else {
options = column.options

View File

@@ -1,5 +1,5 @@
import type { DrizzleAdapter } from '@payloadcms/drizzle/types'
import type { Connect } from 'payload'
import type { Connect, Migration } from 'payload'
import { createClient } from '@libsql/client'
import { pushDevSchema } from '@payloadcms/drizzle'
@@ -36,7 +36,8 @@ export const connect: Connect = async function connect(
}
}
} catch (err) {
this.payload.logger.error({ err, msg: `Error: cannot connect to SQLite: ${err.message}` })
const message = err instanceof Error ? err.message : String(err)
this.payload.logger.error({ err, msg: `Error: cannot connect to SQLite: ${message}` })
if (typeof this.rejectInitializing === 'function') {
this.rejectInitializing()
}
@@ -57,6 +58,6 @@ export const connect: Connect = async function connect(
}
if (process.env.NODE_ENV === 'production' && this.prodMigrations) {
await this.migrate({ migrations: this.prodMigrations })
await this.migrate({ migrations: this.prodMigrations as Migration[] })
}
}

View File

@@ -17,7 +17,7 @@ export const countDistinct: CountDistinct = async function countDistinct(
})
.from(this.tables[tableName])
.where(where)
return Number(countResult[0].count)
return Number(countResult[0]?.count)
}
const chainedMethods: ChainedMethods = []
@@ -45,5 +45,5 @@ export const countDistinct: CountDistinct = async function countDistinct(
.limit(1),
})
return Number(countResult[0].count)
return Number(countResult[0]?.count)
}

View File

@@ -74,7 +74,7 @@ export const createJSONQuery = ({
treatAsArray,
value,
}: CreateJSONQueryArgs): string => {
if (treatAsArray.includes(pathSegments[1])) {
if (treatAsArray?.includes(pathSegments[1]!) && table) {
return fromArray({
operator,
pathSegments,

View File

@@ -1,6 +1,11 @@
import type { DeleteWhere } from './types.js'
import type { DeleteWhere, SQLiteAdapter } from './types.js'
export const deleteWhere: DeleteWhere = async function deleteWhere({ db, tableName, where }) {
export const deleteWhere: DeleteWhere = async function (
// Here 'this' is not a parameter. See:
// https://www.typescriptlang.org/docs/handbook/2/classes.html#this-parameters
this: SQLiteAdapter,
{ db, tableName, where },
) {
const table = this.tables[tableName]
await db.delete(table).where(where)
}

View File

@@ -1,21 +1,23 @@
import type { DropDatabase } from './types.js'
import type { Row } from '@libsql/client'
const getTables = (adapter) => {
import type { DropDatabase, SQLiteAdapter } from './types.js'
const getTables = (adapter: SQLiteAdapter) => {
return adapter.client.execute(`SELECT name
FROM sqlite_master
WHERE type = 'table'
AND name NOT LIKE 'sqlite_%';`)
}
const dropTables = (adapter, rows) => {
const dropTables = (adapter: SQLiteAdapter, rows: Row[]) => {
const multi = `
PRAGMA foreign_keys = OFF;\n
${rows.map(({ name }) => `DROP TABLE IF EXISTS ${name}`).join(';\n ')};\n
${rows.map(({ name }) => `DROP TABLE IF EXISTS ${name as string}`).join(';\n ')};\n
PRAGMA foreign_keys = ON;`
return adapter.client.executeMultiple(multi)
}
export const dropDatabase: DropDatabase = async function dropDatabase({ adapter }) {
export const dropDatabase: DropDatabase = async function ({ adapter }) {
const result = await getTables(adapter)
await dropTables(adapter, result.rows)
}

View File

@@ -3,13 +3,13 @@ import { sql } from 'drizzle-orm'
import type { Execute } from './types.js'
export const execute: Execute<any> = function execute({ db, drizzle, raw, sql: statement }) {
const executeFrom = db ?? drizzle
const executeFrom = (db ?? drizzle)!
if (raw) {
const result = executeFrom.run(sql.raw(raw))
return result
} else {
const result = executeFrom.run(statement)
const result = executeFrom.run(statement!)
return result
}
}

View File

@@ -92,9 +92,11 @@ export function sqliteAdapter(args: Args): DatabaseAdapterObj<SQLiteAdapter> {
allowIDOnCreate,
autoIncrement: args.autoIncrement ?? false,
beforeSchemaInit: args.beforeSchemaInit ?? [],
// @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve
client: undefined,
clientConfig: args.client,
defaultDrizzleSnapshot,
// @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve
drizzle: undefined,
features: {
json: true,
@@ -112,6 +114,7 @@ export function sqliteAdapter(args: Args): DatabaseAdapterObj<SQLiteAdapter> {
logger: args.logger,
operators,
prodMigrations: args.prodMigrations,
// @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve
push: args.push,
rawRelations: {},
rawTables: {},
@@ -122,6 +125,7 @@ export function sqliteAdapter(args: Args): DatabaseAdapterObj<SQLiteAdapter> {
sessions: {},
tableNameMap: new Map<string, string>(),
tables: {},
// @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve
transactionOptions: args.transactionOptions || undefined,
updateMany,
versionsSuffix: args.versionsSuffix || '_v',
@@ -160,6 +164,7 @@ export function sqliteAdapter(args: Args): DatabaseAdapterObj<SQLiteAdapter> {
find,
findGlobal,
findGlobalVersions,
// @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve
findOne,
findVersions,
indexes: new Set<string>(),
@@ -175,8 +180,10 @@ export function sqliteAdapter(args: Args): DatabaseAdapterObj<SQLiteAdapter> {
packageName: '@payloadcms/db-sqlite',
payload,
queryDrafts,
// @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve
rejectInitializing,
requireDrizzleKit,
// @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve
resolveInitializing,
rollbackTransaction,
updateGlobal,

View File

@@ -28,7 +28,7 @@ export const init: Init = async function init(this: SQLiteAdapter) {
await executeSchemaHooks({ type: 'beforeSchemaInit', adapter: this })
for (const tableName in this.rawTables) {
buildDrizzleTable({ adapter, locales, rawTable: this.rawTables[tableName] })
buildDrizzleTable({ adapter, locales: locales!, rawTable: this.rawTables[tableName]! })
}
buildDrizzleRelations({

View File

@@ -1,19 +1,17 @@
import type { Insert } from './types.js'
import type { Insert, SQLiteAdapter } from './types.js'
export const insert: Insert = async function insert({
db,
onConflictDoUpdate,
tableName,
values,
}): Promise<Record<string, unknown>[]> {
export const insert: Insert = async function (
// Here 'this' is not a parameter. See:
// https://www.typescriptlang.org/docs/handbook/2/classes.html#this-parameters
this: SQLiteAdapter,
{ db, onConflictDoUpdate, tableName, values },
): Promise<Record<string, unknown>[]> {
const table = this.tables[tableName]
let result
if (onConflictDoUpdate) {
result = db.insert(table).values(values).onConflictDoUpdate(onConflictDoUpdate).returning()
} else {
result = db.insert(table).values(values).returning()
}
result = await result
return result
const result = onConflictDoUpdate
? await db.insert(table).values(values).onConflictDoUpdate(onConflictDoUpdate).returning()
: await db.insert(table).values(values).returning()
// See https://github.com/payloadcms/payload/pull/11831#discussion_r2010431908
return result as Record<string, unknown>[]
}

View File

@@ -81,8 +81,9 @@ export const buildDrizzleTable: BuildDrizzleTable = ({ adapter, locales, rawTabl
}
if (column.reference) {
columns[key].references(() => adapter.tables[column.reference.table][column.reference.name], {
onDelete: column.reference.onDelete,
const ref = column.reference
columns[key].references(() => adapter.tables[ref.table][ref.name], {
onDelete: ref.onDelete,
})
}

View File

@@ -1,10 +1,5 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
/* TODO: remove the following lines */
"strict": false,
"noUncheckedIndexedAccess": false,
},
"references": [
{
"path": "../payload"