or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-adapter.mddrizzle-integration.mdindex.mdmigration-utils.md

core-adapter.mddocs/

0

# Core Database Adapter

1

2

Core functionality for creating and configuring PostgreSQL database adapters for Payload CMS. The adapter provides connection management, schema handling, and transaction support.

3

4

## Capabilities

5

6

### PostgreSQL Adapter Factory

7

8

Creates a configured PostgreSQL database adapter for Payload CMS with full support for connection pooling, schema management, and advanced features.

9

10

```typescript { .api }

11

/**

12

* Creates a PostgreSQL database adapter for Payload CMS

13

* @param args - Configuration options for the adapter

14

* @returns DatabaseAdapterObj containing the configured adapter

15

*/

16

function postgresAdapter(args: PostgresAdapterArgs): DatabaseAdapterObj<PostgresAdapter>;

17

18

interface PostgresAdapterArgs {

19

/** PostgreSQL connection pool configuration (required) */

20

pool: PoolConfig;

21

22

/** Primary key type for generated IDs */

23

idType?: 'serial' | 'uuid';

24

25

/** Database schema name (experimental) */

26

schemaName?: string;

27

28

/** PostgreSQL extensions to enable */

29

extensions?: string[];

30

31

/** Directory containing migration files */

32

migrationDir?: string;

33

34

/** Allow custom ID values in create operations */

35

allowIDOnCreate?: boolean;

36

37

/** Store blocks as JSON instead of relational structure */

38

blocksAsJSON?: boolean;

39

40

/** Disable automatic database creation */

41

disableCreateDatabase?: boolean;

42

43

/** Suffix for locale tables */

44

localesSuffix?: string;

45

46

/** Suffix for relationship tables */

47

relationshipsSuffix?: string;

48

49

/** Suffix for version tables */

50

versionsSuffix?: string;

51

52

/** Filter specific tables */

53

tablesFilter?: string[];

54

55

/** Read replica connection strings */

56

readReplicas?: string[];

57

58

/** Transaction configuration or false to disable */

59

transactionOptions?: false | PgTransactionConfig;

60

61

/** Schema transformation hooks before schema initialization */

62

beforeSchemaInit?: PostgresSchemaHook[];

63

64

/** Schema transformation hooks after schema initialization */

65

afterSchemaInit?: PostgresSchemaHook[];

66

67

/** Drizzle query logger configuration */

68

logger?: DrizzleConfig['logger'];

69

70

/** Custom pg dependency injection */

71

pg?: typeof import('pg');

72

73

/** Enable schema pushing in development */

74

push?: boolean;

75

76

/** Production migration definitions */

77

prodMigrations?: Array<{

78

name: string;

79

up: (args: MigrateUpArgs) => Promise<void>;

80

down: (args: MigrateDownArgs) => Promise<void>;

81

}>;

82

}

83

```

84

85

**Usage Examples:**

86

87

```typescript

88

import { postgresAdapter } from '@payloadcms/db-postgres';

89

import { buildConfig } from 'payload';

90

91

// Basic configuration

92

export default buildConfig({

93

db: postgresAdapter({

94

pool: {

95

connectionString: process.env.DATABASE_URI,

96

},

97

}),

98

});

99

100

// Advanced configuration

101

export default buildConfig({

102

db: postgresAdapter({

103

pool: {

104

host: 'localhost',

105

port: 5432,

106

user: 'postgres',

107

password: 'password',

108

database: 'myapp',

109

ssl: false,

110

max: 20,

111

min: 5,

112

},

113

idType: 'uuid',

114

schemaName: 'payload',

115

extensions: ['uuid-ossp', 'postgis'],

116

allowIDOnCreate: true,

117

blocksAsJSON: false,

118

readReplicas: [

119

'postgresql://user:pass@replica1:5432/db',

120

'postgresql://user:pass@replica2:5432/db',

121

],

122

beforeSchemaInit: [

123

({ schema }) => {

124

// Preserve existing schema elements

125

return { ...existingSchema, ...schema };

126

},

127

],

128

afterSchemaInit: [

129

({ schema }) => {

130

// Add custom indices or constraints

131

return enhanceSchemaWithCustomFeatures(schema);

132

},

133

],

134

transactionOptions: {

135

isolationLevel: 'read committed',

136

accessMode: 'read write',

137

},

138

}),

139

});

140

```

141

142

### Connection Pool Configuration

143

144

PostgreSQL connection pool settings for managing database connections efficiently.

145

146

```typescript { .api }

147

interface PoolConfig {

148

/** Full connection string (alternative to individual options) */

149

connectionString?: string;

150

151

/** Database host */

152

host?: string;

153

154

/** Database port */

155

port?: number;

156

157

/** Database user */

158

user?: string;

159

160

/** Database password */

161

password?: string;

162

163

/** Database name */

164

database?: string;

165

166

/** SSL configuration */

167

ssl?: boolean | {

168

rejectUnauthorized?: boolean;

169

ca?: string;

170

cert?: string;

171

key?: string;

172

};

173

174

/** Maximum number of connections in pool */

175

max?: number;

176

177

/** Minimum number of connections in pool */

178

min?: number;

179

180

/** Idle timeout in milliseconds */

181

idle?: number;

182

183

/** Acquire timeout in milliseconds */

184

acquire?: number;

185

186

/** Eviction timeout in milliseconds */

187

evict?: number;

188

}

189

```

190

191

### Transaction Configuration

192

193

Configuration options for PostgreSQL transactions.

194

195

```typescript { .api }

196

interface PgTransactionConfig {

197

/** Transaction isolation level */

198

isolationLevel?: 'read uncommitted' | 'read committed' | 'repeatable read' | 'serializable';

199

200

/** Transaction access mode */

201

accessMode?: 'read only' | 'read write';

202

203

/** Whether transaction is deferrable */

204

deferrable?: boolean;

205

}

206

```

207

208

### Schema Hooks

209

210

Functions for transforming database schemas before and after initialization.

211

212

```typescript { .api }

213

/**

214

* Schema transformation hook function

215

* @param args - Object containing the current schema

216

* @returns Modified schema object

217

*/

218

type PostgresSchemaHook = (args: { schema: Record<string, unknown> }) => Record<string, unknown>;

219

```

220

221

**Usage Examples:**

222

223

```typescript

224

// Preserve existing database schema

225

const beforeSchemaInit: PostgresSchemaHook[] = [

226

({ schema }) => {

227

// Merge with existing schema to avoid conflicts

228

return { ...existingDatabaseSchema, ...schema };

229

},

230

];

231

232

// Add custom features after schema generation

233

const afterSchemaInit: PostgresSchemaHook[] = [

234

({ schema }) => {

235

// Add composite indices

236

schema.users.indices = {

237

...schema.users.indices,

238

email_name_idx: { columns: ['email', 'name'], unique: true },

239

};

240

return schema;

241

},

242

];

243

```

244

245

### Migration Arguments

246

247

Arguments passed to migration functions for database schema changes.

248

249

```typescript { .api }

250

interface MigrateUpArgs {

251

/** The Postgres Drizzle instance for executing SQL directly within the current transaction */

252

db: PostgresDB;

253

/** The Payload instance for executing Local API methods */

254

payload: Payload;

255

/** The PayloadRequest object containing the current transaction */

256

req: PayloadRequest;

257

}

258

259

interface MigrateDownArgs {

260

/** The Postgres Drizzle instance for executing SQL directly within the current transaction */

261

db: PostgresDB;

262

/** The Payload instance for executing Local API methods */

263

payload: Payload;

264

/** The PayloadRequest object containing the current transaction */

265

req: PayloadRequest;

266

}

267

```

268

269

## Return Types

270

271

### Database Adapter Object

272

273

The return value from `postgresAdapter()` containing the configured adapter.

274

275

```typescript { .api }

276

interface DatabaseAdapterObj<PostgresAdapter> {

277

/** Adapter name identifier */

278

name: 'postgres';

279

280

/** Whether custom IDs are allowed on create */

281

allowIDOnCreate: boolean;

282

283

/** Default ID type for the adapter */

284

defaultIDType: 'number' | 'text';

285

286

/** Initialization function that creates the adapter instance */

287

init: (options: { payload: Payload }) => PostgresAdapter;

288

}

289

```

290

291

### PostgreSQL Adapter Instance

292

293

The configured adapter instance created by the init function.

294

295

```typescript { .api }

296

interface PostgresAdapter extends BasePostgresAdapter {

297

/** Drizzle ORM database instance */

298

drizzle: Drizzle;

299

300

/** PostgreSQL driver dependency */

301

pg: typeof import('pg');

302

303

/** Active connection pool */

304

pool: Pool;

305

306

/** Pool configuration options */

307

poolOptions: PoolConfig;

308

}

309

```