Skip to content

Commit 09ad6e4

Browse files
authored
feat(drizzle): abstract shared sql code to new package (#7320)
- Abstract shared sql code to a new drizzle package - Adds sqlite package, not ready to publish until drizzle patches some issues - Add `transactionOptions` to allow customizing or disabling db transactions - Adds "experimental" label to the `schemaName` property until drizzle patches an issue
1 parent c129c10 commit 09ad6e4

File tree

166 files changed

+5245
-1941
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

166 files changed

+5245
-1941
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ meta_shared.json
2222
# Ignore test directory media folder/files
2323
/media
2424
test/media
25+
*payloadtests.db
26+
*payloadtests.db-journal
27+
*payloadtests.db-shm
28+
*payloadtests.db-wal
2529
/versions
2630

2731
# Created by https://www.toptal.com/developers/gitignore/api/node,macos,windows,webstorm,sublimetext,visualstudiocode

.idea/payload.iml

Lines changed: 5 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docs/database/postgres.mdx

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,18 +33,18 @@ export default buildConfig({
3333

3434
## Options
3535

36-
| Option | Description |
37-
|-----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
38-
| `pool` \* | [Pool connection options](https://orm.drizzle.team/docs/quick-postgresql/node-postgres) that will be passed to Drizzle and `node-postgres`. |
39-
| `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. |
40-
| `migrationDir` | Customize the directory that migrations are stored. |
41-
| `logger` | The instance of the logger to be passed to drizzle. By default Payload's will be used. |
42-
| `schemaName` | A string for the postgres schema to use, defaults to 'public'. |
43-
| `localesSuffix` | A string appended to the end of table names for storing localized fields. Default is '_locales'. |
44-
| `relationshipsSuffix` | A string appended to the end of table names for storing relationships. Default is '_rels'. |
45-
| `versionsSuffix` | A string appended to the end of table names for storing versions. Defaults to '_v'. |
46-
47-
36+
| Option | Description |
37+
|-----------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
38+
| `pool` \* | [Pool connection options](https://orm.drizzle.team/docs/quick-postgresql/node-postgres) that will be passed to Drizzle and `node-postgres`. |
39+
| `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. |
40+
| `migrationDir` | Customize the directory that migrations are stored. |
41+
| `logger` | The instance of the logger to be passed to drizzle. By default Payload's will be used. |
42+
| `schemaName` (experimental) | A string for the postgres schema to use, defaults to 'public'. |
43+
| `idType` | A string of 'serial', or 'uuid' that is used for the data type given to id columns. |
44+
| `transactionOptions` | A PgTransactionConfig object for transactions, or set to `false` to disable using transactions. [More details](https://orm.drizzle.team/docs/transactions) |
45+
| `localesSuffix` | A string appended to the end of table names for storing localized fields. Default is '_locales'. |
46+
| `relationshipsSuffix` | A string appended to the end of table names for storing relationships. Default is '_rels'. |
47+
| `versionsSuffix` | A string appended to the end of table names for storing versions. Defaults to '_v'. |
4848

4949
## Access to Drizzle
5050

docs/database/sqlite.mdx

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
---
2+
title: SQLite
3+
label: SQLite
4+
order: 60
5+
desc: Payload supports SQLite through an officially supported Drizzle Database Adapter.
6+
keywords: SQLite, documentation, typescript, Content Management System, cms, headless, javascript, node, react, nextjs
7+
---
8+
9+
To use Payload with SQLite, install the package `@payloadcms/db-sqlite`. It leverages Drizzle ORM and `libSQL` to interact with a SQLite database that you provide.
10+
11+
It automatically manages changes to your database for you in development mode, and exposes a full suite of migration controls for you to leverage in order to keep other database environments in sync with your schema. DDL transformations are automatically generated.
12+
13+
To configure Payload to use SQLite, pass the `sqliteAdapter` to your Payload Config as follows:
14+
15+
```ts
16+
import { sqliteAdapter } from '@payloadcms/db-sqlite'
17+
18+
export default buildConfig({
19+
// Your config goes here
20+
collections: [
21+
// Collections go here
22+
],
23+
// Configure the SQLite adapter here
24+
db: sqliteAdapter({
25+
// SQLite-specific arguments go here.
26+
// `client.url` is required.
27+
client: {
28+
url: process.env.DATABASE_URL,
29+
authToken: process.env.DATABASE_AUTH_TOKEN,
30+
}
31+
}),
32+
})
33+
```
34+
35+
## Options
36+
37+
| Option | Description |
38+
|-----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
39+
| `client` \* | [Client connection options](https://orm.drizzle.team/docs/get-started-sqlite#turso) that will be passed to `createClient` from `@libsql/client`. |
40+
| `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. |
41+
| `migrationDir` | Customize the directory that migrations are stored. |
42+
| `logger` | The instance of the logger to be passed to drizzle. By default Payload's will be used. |
43+
| `transactionOptions` | A SQLiteTransactionConfig object for transactions, or set to `false` to disable using transactions. [More details](https://orm.drizzle.team/docs/transactions) |
44+
| `localesSuffix` | A string appended to the end of table names for storing localized fields. Default is '_locales'. |
45+
| `relationshipsSuffix` | A string appended to the end of table names for storing relationships. Default is '_rels'. |
46+
| `versionsSuffix` | A string appended to the end of table names for storing versions. Defaults to '_v'. |
47+
48+
49+
50+
## Access to Drizzle
51+
52+
After Payload is initialized, this adapter will expose the full power of Drizzle to you for use if you need it.
53+
54+
You can access Drizzle as follows:
55+
56+
```text
57+
payload.db.drizzle
58+
```
59+
60+
## Tables and relations
61+
62+
In addition to exposing Drizzle directly, all of the tables and Drizzle relations are exposed for you via the `payload.db` property as well.
63+
64+
- Tables - `payload.db.tables`
65+
- Relations - `payload.db.relations`
66+
67+
## Prototyping in development mode
68+
69+
Drizzle exposes two ways to work locally in development mode.
70+
71+
The first is [`db push`](https://orm.drizzle.team/kit-docs/overview#prototyping-with-db-push), which automatically pushes changes you make to your Payload Config (and therefore, Drizzle schema) to your database so you don't have to manually migrate every time you change your Payload Config. This only works in development mode, and should not be mixed with manually running [`migrate`](/docs/database/migrations) commands.
72+
73+
You will be warned if any changes that you make will entail data loss while in development mode. Push is enabled by default, but you can opt out if you'd like.
74+
75+
Alternatively, you can disable `push` and rely solely on migrations to keep your local database in sync with your Payload Config.
76+
77+
## Migration workflows
78+
79+
In SQLite, migrations are a fundamental aspect of working with Payload and you should become familiar with how they work.
80+
81+
For more information about migrations, [click here](/docs/beta/database/migrations#when-to-run-migrations).

docs/database/transactions.mdx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,7 @@ The following functions can be used for managing transactions:
6868
`payload.db.beginTransaction` - Starts a new session and returns a transaction ID for use in other Payload Local API calls.
6969
`payload.db.commitTransaction` - Takes the identifier for the transaction, finalizes any changes.
7070
`payload.db.rollbackTransaction` - Takes the identifier for the transaction, discards any changes.
71+
72+
## Disabling Transactions
73+
74+
If you wish to disable transactions entirely, you can do so by passing `false` as the `transactionOptions` in your database adapter configuration. All the official Payload database adapters support this option.

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
"build:create-payload-app": "turbo build --filter create-payload-app",
1616
"build:db-mongodb": "turbo build --filter db-mongodb",
1717
"build:db-postgres": "turbo build --filter db-postgres",
18+
"build:db-sqlite": "turbo build --filter db-sqlite",
19+
"build:drizzle": "turbo build --filter drizzle",
1820
"build:email-nodemailer": "turbo build --filter email-nodemailer",
1921
"build:email-resend": "turbo build --filter email-resend",
2022
"build:eslint-config": "turbo build --filter eslint-config",
@@ -93,6 +95,7 @@
9395
},
9496
"devDependencies": {
9597
"@jest/globals": "29.7.0",
98+
"@libsql/client": "0.6.2",
9699
"@next/bundle-analyzer": "15.0.0-canary.53",
97100
"@payloadcms/eslint-config": "workspace:*",
98101
"@payloadcms/eslint-plugin": "workspace:*",
@@ -116,7 +119,6 @@
116119
"create-payload-app": "workspace:*",
117120
"cross-env": "7.0.3",
118121
"dotenv": "16.4.5",
119-
"drizzle-kit": "0.20.14-1f2c838",
120122
"drizzle-orm": "0.29.4",
121123
"escape-html": "^1.0.3",
122124
"execa": "5.1.1",

packages/db-postgres/bundle.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { fileURLToPath } from 'url'
55
const filename = fileURLToPath(import.meta.url)
66
const dirname = path.dirname(filename)
77
import { commonjs } from '@hyrious/esbuild-plugin-commonjs'
8-
8+
throw new Error('asfdadsf')
99
async function build() {
1010
const resultServer = await esbuild.build({
1111
entryPoints: ['src/index.ts'],
@@ -18,9 +18,9 @@ async function build() {
1818
'*.scss',
1919
'*.css',
2020
'drizzle-kit',
21-
'libsql',
2221
'pg',
2322
'@payloadcms/translations',
23+
'@payloadcms/drizzle',
2424
'payload',
2525
'payload/*',
2626
],

packages/db-postgres/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,12 @@
4040
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
4141
"build:types": "tsc --emitDeclarationOnly --outDir dist",
4242
"clean": "rimraf {dist,*.tsbuildinfo}",
43+
"prepack": "pnpm clean && pnpm turbo build",
4344
"prepublishOnly": "pnpm clean && pnpm turbo build",
4445
"renamePredefinedMigrations": "tsx ./scripts/renamePredefinedMigrations.ts"
4546
},
4647
"dependencies": {
47-
"@libsql/client": "^0.5.2",
48+
"@payloadcms/drizzle": "workspace:*",
4849
"console-table-printer": "2.11.2",
4950
"drizzle-kit": "0.20.14-1f2c838",
5051
"drizzle-orm": "0.29.4",

packages/db-postgres/src/connect.ts

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1+
import type { DrizzleAdapter } from '@payloadcms/drizzle/types'
12
import type { Connect, Payload } from 'payload'
23

3-
import { sql } from 'drizzle-orm'
4+
import { pushDevSchema } from '@payloadcms/drizzle'
45
import { drizzle } from 'drizzle-orm/node-postgres'
56
import pg from 'pg'
67

78
import type { PostgresAdapter } from './types.js'
89

9-
import { pushDevSchema } from './utilities/pushDevSchema.js'
10-
1110
const connectWithReconnect = async function ({
1211
adapter,
1312
payload,
@@ -71,12 +70,7 @@ export const connect: Connect = async function connect(
7170
if (!hotReload) {
7271
if (process.env.PAYLOAD_DROP_DATABASE === 'true') {
7372
this.payload.logger.info(`---- DROPPING TABLES SCHEMA(${this.schemaName || 'public'}) ----`)
74-
await this.drizzle.execute(
75-
sql.raw(`
76-
drop schema if exists ${this.schemaName || 'public'} cascade;
77-
create schema ${this.schemaName || 'public'};
78-
`),
79-
)
73+
await this.dropDatabase({ adapter: this })
8074
this.payload.logger.info('---- DROPPED TABLES ----')
8175
}
8276
}
@@ -92,7 +86,7 @@ export const connect: Connect = async function connect(
9286
process.env.PAYLOAD_MIGRATING !== 'true' &&
9387
this.push !== false
9488
) {
95-
await pushDevSchema(this)
89+
await pushDevSchema(this as unknown as DrizzleAdapter)
9690
}
9791

9892
if (typeof this.resolveInitializing === 'function') this.resolveInitializing()

packages/db-postgres/src/count.ts

Lines changed: 0 additions & 54 deletions
This file was deleted.

0 commit comments

Comments
 (0)