Skip to content

Commit

Permalink
feat(db-sqlite): add idType: 'uuid' support
Browse files Browse the repository at this point in the history
  • Loading branch information
r1tsuu committed Dec 17, 2024
1 parent 2d2a52b commit 99c5a58
Show file tree
Hide file tree
Showing 10 changed files with 42 additions and 16 deletions.
1 change: 1 addition & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ jobs:
- postgres-uuid
- supabase
- sqlite
- sqlite-uuid
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
Expand Down
1 change: 1 addition & 0 deletions docs/database/sqlite.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export default buildConfig({
| `push` | Disable Drizzle's [`db push`](https://orm.drizzle.team/kit-docs/overview#prototyping-with-db-push) in development mode. By default, `push` is enabled for development mode only. |
| `migrationDir` | Customize the directory that migrations are stored. |
| `logger` | The instance of the logger to be passed to drizzle. By default Payload's will be used. |
| `idType` | A string of 'number', or 'uuid' that is used for the data type given to id columns. |
| `transactionOptions` | A SQLiteTransactionConfig object for transactions, or set to `false` to disable using transactions. [More details](https://orm.drizzle.team/docs/transactions) |
| `localesSuffix` | A string appended to the end of table names for storing localized fields. Default is '_locales'. |
| `relationshipsSuffix` | A string appended to the end of table names for storing relationships. Default is '_rels'. |
Expand Down
6 changes: 3 additions & 3 deletions packages/db-sqlite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ export { sql } from 'drizzle-orm'
const filename = fileURLToPath(import.meta.url)

export function sqliteAdapter(args: Args): DatabaseAdapterObj<SQLiteAdapter> {
const postgresIDType = args.idType || 'serial'
const payloadIDType = postgresIDType === 'serial' ? 'number' : 'text'
const sqliteIDType = args.idType || 'number'
const payloadIDType = sqliteIDType === 'uuid' ? 'text' : 'number'

function adapter({ payload }: { payload: Payload }) {
const migrationDir = findMigrationDir(args.migrationDir)
Expand Down Expand Up @@ -93,7 +93,7 @@ export function sqliteAdapter(args: Args): DatabaseAdapterObj<SQLiteAdapter> {
json: true,
},
fieldConstraints: {},
idType: postgresIDType,
idType: sqliteIDType,
initializing,
localesSuffix: args.localesSuffix || '_locales',
logger: args.logger,
Expand Down
3 changes: 1 addition & 2 deletions packages/db-sqlite/src/schema/buildDrizzleTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,8 @@ export const buildDrizzleTable: BuildDrizzleTable = ({ adapter, locales, rawTabl
break
}

// Not used yet in SQLite but ready here.
case 'uuid': {
let builder = text(column.name)
let builder = text(column.name, { length: 36 })

if (column.defaultRandom) {
builder = builder.$defaultFn(() => uuidv4())
Expand Down
13 changes: 12 additions & 1 deletion packages/db-sqlite/src/schema/setColumnID.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { SetColumnID } from '@payloadcms/drizzle/types'

export const setColumnID: SetColumnID = ({ columns, fields }) => {
export const setColumnID: SetColumnID = ({ adapter, columns, fields }) => {
const idField = fields.find((field) => field.name === 'id')
if (idField) {
if (idField.type === 'number') {
Expand All @@ -22,6 +22,17 @@ export const setColumnID: SetColumnID = ({ columns, fields }) => {
}
}

if (adapter.idType === 'uuid') {
columns.id = {
name: 'id',
type: 'uuid',
defaultRandom: true,
primaryKey: true,
}

return 'uuid'
}

columns.id = {
name: 'id',
type: 'integer',
Expand Down
3 changes: 2 additions & 1 deletion packages/db-sqlite/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export type Args = {
client: Config
/** Generated schema from payload generate:db-schema file path */
generateSchemaOutputFile?: string
idType?: 'serial' | 'uuid'
idType?: 'number' | 'uuid'
localesSuffix?: string
logger?: DrizzleConfig['logger']
migrationDir?: string
Expand Down Expand Up @@ -106,6 +106,7 @@ type SQLiteDrizzleAdapter = Omit<
| 'drizzle'
| 'dropDatabase'
| 'execute'
| 'idType'
| 'insert'
| 'operators'
| 'relations'
Expand Down
15 changes: 9 additions & 6 deletions packages/drizzle/src/utilities/pushDevSchema.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import prompts from 'prompts'

import type { BasePostgresAdapter } from '../postgres/types.js'
import type { DrizzleAdapter } from '../types.js'
import type { DrizzleAdapter, PostgresDB } from '../types.js'

/**
* Pushes the development schema to the database using Drizzle.
Expand Down Expand Up @@ -60,21 +60,24 @@ export const pushDevSchema = async (adapter: DrizzleAdapter) => {
? `"${adapter.schemaName}"."payload_migrations"`
: '"payload_migrations"'

const drizzle = adapter.drizzle as PostgresDB

const result = await adapter.execute({
drizzle: adapter.drizzle,
drizzle,
raw: `SELECT * FROM ${migrationsTable} WHERE batch = '-1'`,
})

const devPush = result.rows

if (!devPush.length) {
await adapter.execute({
drizzle: adapter.drizzle,
raw: `INSERT INTO ${migrationsTable} (name, batch) VALUES ('dev', '-1')`,
// Use drizzle for insert so $defaultFn's are called
drizzle.insert(adapter.tables.payload_migrations).values({
name: 'dev',
batch: -1,
})
} else {
await adapter.execute({
drizzle: adapter.drizzle,
drizzle,
raw: `UPDATE ${migrationsTable} SET updated_at = CURRENT_TIMESTAMP WHERE batch = '-1'`,
})
}
Expand Down
2 changes: 1 addition & 1 deletion test/custom-graphql/int.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ describe('Custom GraphQL', () => {
}
})

if (!['sqlite'].includes(process.env.PAYLOAD_DATABASE || '')) {
if (!['sqlite', 'sqlite-uuid'].includes(process.env.PAYLOAD_DATABASE || '')) {
describe('Isolated Transaction ID', () => {
it('should isolate transaction IDs between queries in the same request', async () => {
const query = `query {
Expand Down
5 changes: 3 additions & 2 deletions test/database/int.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,7 @@ describe('database', () => {
describe('transactions', () => {
describe('local api', () => {
// sqlite cannot handle concurrent write transactions
if (!['sqlite'].includes(process.env.PAYLOAD_DATABASE)) {
if (!['sqlite', 'sqlite-uuid'].includes(process.env.PAYLOAD_DATABASE)) {
it('should commit multiple operations in isolation', async () => {
const req = {
payload,
Expand Down Expand Up @@ -1074,7 +1074,8 @@ describe('database', () => {
data: { title: 'invalid', relationship: 'not-real-id' },
})
} catch (error) {
expect(error).toBeInstanceOf(Error)
// instanceof checks don't work with libsql
expect(error).toBeTruthy()
}

expect(invalidDoc).toBeUndefined()
Expand Down
9 changes: 9 additions & 0 deletions test/generateDatabaseAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ export const allDatabaseAdapters = {
url: process.env.SQLITE_URL || 'file:./payloadtests.db',
},
})`,
'sqlite-uuid': `
import { sqliteAdapter } from '@payloadcms/db-sqlite'
export const databaseAdapter = sqliteAdapter({
idType: 'uuid',
client: {
url: process.env.SQLITE_URL || 'file:./payloadtests.db',
},
})`,
supabase: `
import { postgresAdapter } from '@payloadcms/db-postgres'
Expand Down

0 comments on commit 99c5a58

Please sign in to comment.