@platformatic/db 3.4.1 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +1 -1
  2. package/config.d.ts +442 -107
  3. package/eslint.config.js +9 -5
  4. package/index.d.ts +53 -31
  5. package/index.js +30 -139
  6. package/lib/application.js +102 -0
  7. package/lib/capability.js +35 -0
  8. package/lib/commands/index.js +59 -0
  9. package/lib/commands/migrations-apply.js +63 -0
  10. package/lib/commands/migrations-create.js +48 -0
  11. package/lib/commands/print-schema.js +31 -0
  12. package/lib/commands/seed.js +74 -0
  13. package/lib/commands/types.js +22 -0
  14. package/lib/config.js +52 -0
  15. package/lib/errors.js +16 -12
  16. package/lib/generator.js +229 -0
  17. package/lib/{migrator.mjs → migrator.js} +46 -38
  18. package/lib/{root-endpoint/index.js → root.js} +6 -7
  19. package/lib/schema.js +41 -20
  20. package/lib/{generator/code-templates.js → templates.js} +57 -16
  21. package/lib/types.js +161 -0
  22. package/lib/upgrade.js +8 -12
  23. package/lib/utils.js +12 -23
  24. package/lib/versions/0.18.0.js +3 -5
  25. package/lib/versions/{from-zero-twenty-height-to-will-see.js → 0.28.0.js} +3 -5
  26. package/lib/versions/2.0.0.js +3 -5
  27. package/lib/versions/3.0.0.js +14 -0
  28. package/package.json +32 -40
  29. package/schema.json +1385 -164
  30. package/tsconfig.json +16 -6
  31. package/db.mjs +0 -86
  32. package/help/compile.txt +0 -17
  33. package/help/create.txt +0 -13
  34. package/help/help.txt +0 -11
  35. package/help/migrations apply.txt +0 -45
  36. package/help/migrations create.txt +0 -27
  37. package/help/migrations.txt +0 -4
  38. package/help/schema.txt +0 -25
  39. package/help/seed.txt +0 -36
  40. package/help/start.txt +0 -47
  41. package/help/types.txt +0 -40
  42. package/index.test-d.ts +0 -43
  43. package/lib/adjust-config.js +0 -42
  44. package/lib/create.mjs +0 -89
  45. package/lib/gen-migration.mjs +0 -53
  46. package/lib/gen-schema.mjs +0 -68
  47. package/lib/gen-types.mjs +0 -202
  48. package/lib/generator/README.md +0 -38
  49. package/lib/generator/db-generator.js +0 -260
  50. package/lib/generator.d.ts +0 -7
  51. package/lib/migrate.mjs +0 -81
  52. package/lib/seed.mjs +0 -90
  53. package/lib/stackable.js +0 -49
  54. /package/{lib/root-endpoint/public → public}/images/dark_mode.svg +0 -0
  55. /package/{lib/root-endpoint/public → public}/images/favicon.ico +0 -0
  56. /package/{lib/root-endpoint/public → public}/images/light_mode.svg +0 -0
  57. /package/{lib/root-endpoint/public → public}/images/platformatic-logo-dark.svg +0 -0
  58. /package/{lib/root-endpoint/public → public}/images/platformatic-logo-light.svg +0 -0
  59. /package/{lib/root-endpoint/public → public}/images/triangle_dark.svg +0 -0
  60. /package/{lib/root-endpoint/public → public}/images/triangle_light.svg +0 -0
  61. /package/{lib/root-endpoint/public → public}/index.html +0 -0
@@ -1,68 +0,0 @@
1
- import pino from 'pino'
2
- import pretty from 'pino-pretty'
3
- import Fastify from 'fastify'
4
- import graphql from 'graphql'
5
- import { writeFile } from 'fs/promises'
6
- import { loadConfig } from '@platformatic/config'
7
- import { createServerConfig } from '@platformatic/utils'
8
- import { platformaticDB } from '../index.js'
9
- import { schema as platformaticDBschema } from './schema.js'
10
-
11
- async function buildServer (_args, onServer) {
12
- const logger = pino(pretty({
13
- translateTime: 'SYS:HH:MM:ss',
14
- ignore: 'hostname,pid',
15
- minimumLevel: 'error',
16
- }))
17
-
18
- try {
19
- const { configManager } = await loadConfig({}, _args, platformaticDB)
20
-
21
- await configManager.parseAndValidate()
22
- const config = configManager.current
23
- delete config.logger
24
- config.loggerInstance = logger
25
-
26
- const serverConfig = createServerConfig(config)
27
- serverConfig.originalConfig = config
28
- serverConfig.configManager = configManager
29
- delete serverConfig.logger
30
- serverConfig.loggerInstance = logger
31
-
32
- const app = Fastify(serverConfig)
33
- app.decorate('platformatic', { configManager, config: configManager.current })
34
- app.register(platformaticDB, serverConfig)
35
-
36
- await app.ready()
37
-
38
- await onServer(app)
39
- /* c8 ignore next 4 */
40
- } catch (err) {
41
- logger.error(err)
42
- process.exit(1)
43
- }
44
- }
45
-
46
- function printGraphQLSchema (_args) {
47
- buildServer(_args, async function (app) {
48
- const schema = graphql.printSchema(app.graphql.schema)
49
- console.log(schema)
50
- await app.close()
51
- })
52
- }
53
-
54
- function printOpenAPISchema (_args) {
55
- buildServer(_args, async function (app) {
56
- const schema = app.swagger()
57
- console.log(JSON.stringify(schema, null, 2))
58
- await app.close()
59
- })
60
- }
61
-
62
- const filenameConfigJsonSchema = 'platformatic.db.schema.json'
63
-
64
- async function generateJsonSchemaConfig () {
65
- await writeFile(filenameConfigJsonSchema, JSON.stringify(platformaticDBschema, null, 2))
66
- }
67
-
68
- export { printGraphQLSchema, printOpenAPISchema, generateJsonSchemaConfig, filenameConfigJsonSchema }
package/lib/gen-types.mjs DELETED
@@ -1,202 +0,0 @@
1
- import { loadConfig } from '@platformatic/config'
2
- import { mapOpenAPItoTypes, mapSQLEntityToJSONSchema } from '@platformatic/sql-json-schema-mapper'
3
- import utils, { createDirectory } from '@platformatic/utils'
4
- import camelcase from 'camelcase'
5
- import { readFile, readdir, unlink, writeFile } from 'fs/promises'
6
- import { createRequire } from 'node:module'
7
- import { basename, join, parse, posix, relative, resolve } from 'path'
8
- import pino from 'pino'
9
- import pretty from 'pino-pretty'
10
- import { platformaticDB } from '../index.js'
11
- import { isFileAccessible, setupDB } from './utils.js'
12
-
13
- const checkForDependencies = utils.checkForDependencies
14
-
15
- const GLOBAL_TYPES_TEMPLATE = `\
16
- import type { PlatformaticApp, PlatformaticDBMixin, PlatformaticDBConfig, Entity, Entities, EntityHooks } from '@platformatic/db'
17
- ENTITIES_IMPORTS_PLACEHOLDER
18
-
19
- interface AppEntities extends Entities {
20
- ENTITIES_DEFINITION_PLACEHOLDER
21
- }
22
-
23
- interface AppEntityHooks {
24
- HOOKS_DEFINITION_PLACEHOLDER
25
- }
26
-
27
- declare module 'fastify' {
28
- interface FastifyInstance {
29
- platformatic: PlatformaticApp<PlatformaticDBConfig> &
30
- PlatformaticDBMixin<AppEntities> &
31
- AppEntityHooks
32
- }
33
- }
34
- `
35
-
36
- async function removeUnusedTypeFiles (entities, dir) {
37
- const entityTypes = await readdir(dir)
38
- const entityNames = Object.values(entities).map(entity => entity.name)
39
- const removedEntityNames = entityTypes.filter(file => !entityNames.includes(basename(file, '.d.ts')))
40
- await Promise.all(removedEntityNames.map(file => unlink(join(dir, file))))
41
- }
42
-
43
- function getTypesFolderPath (cwd, config) {
44
- return resolve(cwd, config.types?.dir ?? 'types')
45
- }
46
-
47
- async function generateEntityType (entity) {
48
- const jsonSchema = mapSQLEntityToJSONSchema(entity)
49
- const fieldDefinitions = Object.fromEntries(
50
- Object.entries(entity.fields).map(([, value]) => [value.camelcase, value])
51
- )
52
- const tsCode = mapOpenAPItoTypes(jsonSchema, fieldDefinitions)
53
- entity.name = camelcase(entity.name).replace(/^\w/, c => c.toUpperCase())
54
- return tsCode + `\nexport { ${entity.name} };\n`
55
- }
56
-
57
- async function generateEntityGroupExport (entities) {
58
- const completeTypesImports = []
59
- const interfaceRows = []
60
- for (const name of entities) {
61
- completeTypesImports.push(`import { ${name} } from './${name}'`)
62
- interfaceRows.push(`${name}: ${name}`)
63
- }
64
-
65
- const content = `${completeTypesImports.join('\n')}
66
-
67
- interface EntityTypes {
68
- ${interfaceRows.join('\n ')}
69
- }
70
-
71
- export { EntityTypes, ${entities.join(', ')} }`
72
- return content
73
- }
74
-
75
- async function generateGlobalTypes (entities, config) {
76
- const globalTypesImports = []
77
- const globalTypesInterface = []
78
- const globalHooks = []
79
- const completeTypesImports = []
80
-
81
- let typesRelativePath = relative(process.cwd(), getTypesFolderPath(process.cwd(), config))
82
- {
83
- const parsedPath = parse(typesRelativePath)
84
- typesRelativePath = posix.format(parsedPath)
85
- }
86
-
87
- const schemaIdTypes = []
88
- const names = []
89
- const keys = Object.keys(entities).sort()
90
- for (const key of keys) {
91
- const { name, singularName } = entities[key]
92
- schemaIdTypes.push(name)
93
- completeTypesImports.push(`import { ${name} } from './${typesRelativePath}/${name}'`)
94
- globalTypesInterface.push(`${key}: Entity<${name}>,`)
95
- globalHooks.push(`addEntityHooks(entityName: '${singularName}', hooks: EntityHooks<${name}>): any`)
96
- names.push(name)
97
- }
98
- globalTypesImports.push(`import { EntityTypes, ${names.join(',')} } from './${typesRelativePath}'`)
99
-
100
- const schemaIdType = schemaIdTypes.length === 0 ? 'string' : schemaIdTypes.map(type => `'${type}'`).join(' | ')
101
-
102
- globalTypesImports.push(`
103
- declare module 'fastify' {
104
- interface FastifyInstance {
105
- getSchema<T extends ${schemaIdType}>(schemaId: T): {
106
- '$id': string,
107
- title: string,
108
- description: string,
109
- type: string,
110
- properties: {
111
- [x in keyof EntityTypes[T]]: { type: string, nullable?: boolean }
112
- },
113
- required: string[]
114
- };
115
- }
116
- }`)
117
-
118
- return GLOBAL_TYPES_TEMPLATE.replace('ENTITIES_IMPORTS_PLACEHOLDER', globalTypesImports.join('\n'))
119
- .replace('ENTITIES_DEFINITION_PLACEHOLDER', globalTypesInterface.join('\n '))
120
- .replace('HOOKS_DEFINITION_PLACEHOLDER', globalHooks.join('\n '))
121
- }
122
-
123
- async function writeFileIfChanged (filename, content) {
124
- const isFileExists = await isFileAccessible(filename)
125
- if (isFileExists) {
126
- const fileContent = await readFile(filename, 'utf-8')
127
- if (fileContent === content) return false
128
- }
129
- await writeFile(filename, content)
130
- return true
131
- }
132
-
133
- async function execute ({ logger, config, configManager }) {
134
- const wrap = await setupDB(logger, config.db)
135
- const { db, entities } = wrap
136
- if (Object.keys(entities).length === 0) {
137
- // do not generate types if no schema is found
138
- return 0
139
- }
140
-
141
- const servicePath = configManager.dirname
142
- const typesFolderPath = getTypesFolderPath(servicePath, config)
143
-
144
- const isTypeFolderExists = await isFileAccessible(typesFolderPath)
145
- if (isTypeFolderExists) {
146
- await removeUnusedTypeFiles(entities, typesFolderPath)
147
- } else {
148
- await createDirectory(typesFolderPath)
149
- }
150
-
151
- let count = 0
152
- const entitiesValues = Object.values(entities)
153
- const entitiesNames = entitiesValues.map(({ name }) => name).sort()
154
- for (const entity of entitiesValues) {
155
- count++
156
- const types = await generateEntityType(entity)
157
-
158
- const pathToFile = join(typesFolderPath, entity.name + '.d.ts')
159
- const isTypeChanged = await writeFileIfChanged(pathToFile, types)
160
-
161
- if (isTypeChanged) {
162
- logger.info(`Generated type for ${entity.name} entity.`)
163
- }
164
- }
165
- const pathToFile = join(typesFolderPath, 'index.d.ts')
166
- // maybe better to check here for changes
167
- const content = await generateEntityGroupExport(entitiesNames)
168
- const isTypeChanged = await writeFileIfChanged(pathToFile, content)
169
- if (isTypeChanged) {
170
- logger.info('Regenerating global.d.ts')
171
- }
172
-
173
- const globalTypes = await generateGlobalTypes(entities, config)
174
- const globalTypesFilePath = join(servicePath, 'global.d.ts')
175
- await writeFileIfChanged(globalTypesFilePath, globalTypes)
176
-
177
- await db.dispose()
178
- return count
179
- }
180
-
181
- async function generateTypes (_args) {
182
- const logger = pino(
183
- pretty({
184
- translateTime: 'SYS:HH:MM:ss',
185
- ignore: 'hostname,pid',
186
- })
187
- )
188
-
189
- const { configManager, args } = await loadConfig({}, _args, platformaticDB)
190
-
191
- await configManager.parseAndValidate()
192
- const config = configManager.current
193
-
194
- const count = await execute({ logger, config, configManager })
195
- if (count === 0) {
196
- logger.warn('No entities found in your schema. Types were NOT generated.')
197
- logger.warn('Please run `platformatic db migrations apply` to generate types.')
198
- }
199
- await checkForDependencies(logger, args, createRequire(import.meta.url), config, ['@platformatic/db'])
200
- }
201
-
202
- export { execute, generateTypes }
@@ -1,38 +0,0 @@
1
- # Platformatic DB API
2
-
3
- This is a generated [Platformatic DB](https://docs.platformatic.dev/docs/db/overview) application.
4
-
5
- ## Requirements
6
-
7
- Platformatic supports macOS, Linux and Windows ([WSL](https://docs.microsoft.com/windows/wsl/) recommended).
8
- You'll need to have [Node.js](https://nodejs.org/) >= v18.8.0 or >= v20.6.0
9
-
10
- ## Setup
11
-
12
- 1. Install dependencies:
13
-
14
- ```bash
15
- npm install
16
- ```
17
-
18
- 2. Apply migrations:
19
-
20
- ```bash
21
- npm run migrate
22
- ```
23
-
24
-
25
- ## Usage
26
-
27
- Run the API with:
28
-
29
- ```bash
30
- npm start
31
- ```
32
-
33
- ### Explore
34
- - ⚡ The Platformatic DB server is running at http://localhost:3042/
35
- - 📔 View the REST API's Swagger documentation at http://localhost:3042/documentation/
36
- - 🔍 Try out the GraphiQL web UI at http://localhost:3042/graphiql
37
-
38
-
@@ -1,260 +0,0 @@
1
- 'use strict'
2
-
3
- const { BaseGenerator, generateTests } = require('@platformatic/generators')
4
- const { jsHelperSqlite, jsHelperMySQL, jsHelperPostgres, moviesTestTS, moviesTestJS } = require('./code-templates')
5
- const { join } = require('node:path')
6
- const { readFile } = require('node:fs/promises')
7
-
8
- class DBGenerator extends BaseGenerator {
9
- constructor (opts = {}) {
10
- super({
11
- ...opts,
12
- module: '@platformatic/db',
13
- })
14
- this.connectionStrings = {
15
- postgres: 'postgres://postgres:postgres@127.0.0.1:5432/postgres',
16
- sqlite: 'sqlite://./db.sqlite',
17
- mysql: 'mysql://root@127.0.0.1:3306/platformatic',
18
- mariadb: 'mysql://root@127.0.0.1:3306/platformatic',
19
- }
20
- }
21
-
22
- getDefaultConfig () {
23
- const defaultBaseConfig = super.getDefaultConfig()
24
- return {
25
- ...defaultBaseConfig,
26
- database: 'sqlite',
27
- connectionString: null,
28
- plugin: true,
29
- tests: true,
30
- types: true,
31
- migrations: 'migrations',
32
- createMigrations: true,
33
- }
34
- }
35
-
36
- async _getConfigFileContents () {
37
- const { isRuntimeContext, migrations, plugin, types } = this.config
38
- const version = this.platformaticVersion
39
-
40
- const config = {
41
- $schema: `https://schemas.platformatic.dev/@platformatic/db/${version}.json`,
42
- db: {
43
- connectionString: `{${this.getEnvVarName('DATABASE_URL')}}`,
44
- graphql: true,
45
- openapi: true,
46
- schemalock: true,
47
- },
48
- watch: {
49
- ignore: ['*.sqlite', '*.sqlite-journal'],
50
- },
51
- }
52
-
53
- if (!isRuntimeContext) {
54
- config.server = {
55
- hostname: '{PLT_SERVER_HOSTNAME}',
56
- port: '{PORT}',
57
- logger: {
58
- level: '{PLT_SERVER_LOGGER_LEVEL}',
59
- },
60
- }
61
- }
62
-
63
- if (migrations) {
64
- config.migrations = {
65
- dir: migrations,
66
- autoApply: `{${this.getEnvVarName('PLT_APPLY_MIGRATIONS')}}`,
67
- }
68
- }
69
-
70
- if (plugin === true) {
71
- config.plugins = {
72
- paths: [{
73
- path: './plugins',
74
- encapsulate: false,
75
- }, {
76
- path: './routes',
77
- }],
78
- typescript: `{${this.getEnvVarName('PLT_TYPESCRIPT')}}`,
79
- }
80
- }
81
-
82
- if (types === true) {
83
- config.types = {
84
- autogenerate: true,
85
- }
86
- }
87
-
88
- return config
89
- }
90
-
91
- async _beforePrepare () {
92
- if (!this.config.isUpdating) {
93
- this.config.connectionString = this.config.connectionString || this.connectionStrings[this.config.database]
94
- this.config.dependencies = {
95
- '@platformatic/db': `^${this.platformaticVersion}`,
96
- }
97
-
98
- if (!this.config.isRuntimeContext) {
99
- this.addEnvVars({
100
- PLT_SERVER_HOSTNAME: this.config.hostname,
101
- PLT_SERVER_LOGGER_LEVEL: 'info',
102
- PORT: 3042,
103
- }, { overwrite: false, default: true })
104
- }
105
-
106
- this.addEnvVars({
107
- PLT_TYPESCRIPT: this.config.typescript,
108
- DATABASE_URL: this.connectionStrings[this.config.database],
109
- PLT_APPLY_MIGRATIONS: 'true',
110
- }, { overwrite: false, default: true })
111
- }
112
- }
113
-
114
- async _afterPrepare () {
115
- if (!this.config.isUpdating) {
116
- if (this.config.createMigrations) {
117
- this.createMigrationFiles()
118
- }
119
-
120
- this.addFile({ path: '', file: 'README.md', contents: await readFile(join(__dirname, 'README.md'), 'utf-8') })
121
-
122
- if (this.config.plugin) {
123
- let jsHelper = { pre: '', config: '', post: '' }
124
- switch (this.config.database) {
125
- case 'sqlite':
126
- jsHelper = jsHelperSqlite
127
- break
128
- case 'mysql':
129
- jsHelper = jsHelperMySQL(this.config.connectionString)
130
- break
131
- case 'postgres':
132
- jsHelper = jsHelperPostgres(this.config.connectionString)
133
- break
134
- case 'mariadb':
135
- jsHelper = jsHelperMySQL(this.config.connectionString)
136
- break
137
- }
138
-
139
- if (this.config.createMigrations) {
140
- if (this.config.typescript) {
141
- this.addFile({ path: join('test', 'routes'), file: 'movies.test.ts', contents: moviesTestTS })
142
- } else {
143
- this.addFile({ path: join('test', 'routes'), file: 'movies.test.js', contents: moviesTestJS })
144
- }
145
- }
146
-
147
- // TODO(leorossi): this is unfortunate. We have already generated tests in BaseGenerator
148
- // next line will override the test files
149
- generateTests(this.config.typescript, '@platformatic/db', jsHelper).forEach((fileObject) => {
150
- this.addFile(fileObject)
151
- })
152
-
153
- if (this.config.isRuntimeContext) {
154
- // remove .env file and env variables since they are all for the config.server property
155
- const envFile = this.getFileObject('.env')
156
- if (envFile) {
157
- envFile.contents = ''
158
- }
159
- }
160
- }
161
-
162
- const GLOBAL_TYPES_TEMPLATE = `
163
- import { FastifyInstance } from 'fastify'
164
- import { PlatformaticApp, PlatformaticDBConfig, PlatformaticDBMixin, Entities } from '@platformatic/db'
165
-
166
- declare module 'fastify' {
167
- interface FastifyInstance {
168
- platformatic: PlatformaticApp<PlatformaticDBConfig> & PlatformaticDBMixin<Entities>
169
- }
170
- }
171
- `
172
- this.addFile({ path: '', file: 'global.d.ts', contents: GLOBAL_TYPES_TEMPLATE })
173
- }
174
- }
175
-
176
- createMigrationFiles () {
177
- this.addFile({ path: 'migrations', file: '001.do.sql', contents: this.getMoviesMigrationDo() })
178
- this.addFile({ path: 'migrations', file: '001.undo.sql', contents: this.getMoviesMigrationUndo() })
179
- }
180
-
181
- getMoviesMigrationDo () {
182
- const key = {
183
- postgres: 'SERIAL',
184
- sqlite: 'INTEGER',
185
- mysql: 'INTEGER UNSIGNED AUTO_INCREMENT',
186
- mariadb: 'INTEGER UNSIGNED AUTO_INCREMENT',
187
- }
188
-
189
- return `
190
- -- Add SQL in this file to create the database tables for your API
191
- CREATE TABLE IF NOT EXISTS movies (
192
- id ${key[this.config.database]} PRIMARY KEY,
193
- title TEXT NOT NULL
194
- );
195
- `
196
- }
197
-
198
- getMoviesMigrationUndo () {
199
- return '-- Add SQL in this file to drop the database tables\nDROP TABLE movies;'
200
- }
201
-
202
- setConfigFields (fields) {
203
- super.setConfigFields(fields)
204
- this.config.database = this.getDatabaseFromConnectionString()
205
- }
206
-
207
- getDatabaseFromConnectionString () {
208
- if (this.config.connectionString) {
209
- if (this.config.connectionString.indexOf('://') !== -1) {
210
- const splitted = this.config.connectionString.split('://')
211
- return splitted[0]
212
- }
213
- return null
214
- }
215
- return null
216
- }
217
-
218
- getConfigFieldsDefinitions () {
219
- return [
220
- {
221
- var: 'DATABASE_URL',
222
- label: 'What is the connection string?',
223
- default: this.connectionStrings.sqlite,
224
- type: 'string',
225
- configValue: 'connectionString',
226
- },
227
- {
228
- var: 'PLT_APPLY_MIGRATIONS',
229
- label: 'Should migrations be applied automatically on startup?',
230
- default: true,
231
- type: 'boolean',
232
- },
233
- ]
234
- }
235
-
236
- async prepareQuestions () {
237
- await super.prepareQuestions()
238
- if (!this.config.connectionString) {
239
- const def = this.getConfigFieldsDefinitions().find((q) => q.var === 'DATABASE_URL')
240
- this.questions.push({
241
- type: 'input',
242
- name: def.configValue,
243
- message: def.label,
244
- default: def.default,
245
- })
246
- }
247
-
248
- this.questions.push({
249
- type: 'list',
250
- name: 'createMigrations',
251
- message: 'Do you want to create default migrations?',
252
- default: true,
253
- choices: [{ name: 'yes', value: true }, { name: 'no', value: false }],
254
- })
255
- }
256
- }
257
-
258
- module.exports = DBGenerator
259
- module.exports.DBGenerator = DBGenerator
260
- module.exports.Generator = DBGenerator
@@ -1,7 +0,0 @@
1
- import { BaseGenerator } from '@platformatic/generators'
2
-
3
- type DBGeneratorOptions = BaseGenerator.BaseGeneratorOptions
4
- export class DBGenerator extends BaseGenerator.BaseGenerator {
5
- connectionStrings: string[]
6
- constructor (opts?: DBGeneratorOptions)
7
- }
package/lib/migrate.mjs DELETED
@@ -1,81 +0,0 @@
1
- #! /usr/bin/env node
2
-
3
- import { Migrator } from './migrator.mjs'
4
- import pino from 'pino'
5
- import pretty from 'pino-pretty'
6
- import { checkForDependencies } from '@platformatic/utils'
7
- import { createRequire } from 'node:module'
8
- import { execute as generateTypes } from './gen-types.mjs'
9
- import { utimesSync } from 'fs'
10
- import { updateSchemaLock } from './utils.js'
11
- import { loadConfig } from '@platformatic/config'
12
- import { platformaticDB } from '../index.js'
13
- import errors from './errors.js'
14
-
15
- async function execute ({ logger, rollback, to, config }) {
16
- const migrationsConfig = config.migrations
17
- if (migrationsConfig === undefined) {
18
- throw new errors.MigrateMissingMigrationsError()
19
- }
20
- const migrator = new Migrator(migrationsConfig, config.db, logger)
21
-
22
- try {
23
- if (rollback) {
24
- await migrator.rollbackMigration()
25
- } else {
26
- await migrator.applyMigrations(to)
27
- }
28
- return migrator.appliedMigrationsCount > 0
29
- } finally {
30
- await migrator.close()
31
- }
32
- }
33
-
34
- async function applyMigrations (_args) {
35
- const logger = pino(pretty({
36
- translateTime: 'SYS:HH:MM:ss',
37
- ignore: 'hostname,pid',
38
- }))
39
-
40
- try {
41
- const { configManager, args } = await loadConfig({
42
- string: ['to'],
43
- boolean: ['rollback'],
44
- alias: {
45
- t: 'to',
46
- r: 'rollback',
47
- },
48
- }, _args, platformaticDB)
49
-
50
- const config = configManager.current
51
- const appliedMigrations = await execute({ logger, ...args, config })
52
-
53
- if (config.types && config.types.autogenerate) {
54
- await generateTypes({ logger, config, configManager })
55
- const modules = ['@platformatic/db']
56
- if (config.plugins?.typescript) {
57
- modules.push('typescript')
58
- }
59
- await checkForDependencies(logger, args, createRequire(import.meta.url), config, modules)
60
- }
61
-
62
- if (appliedMigrations) {
63
- await updateSchemaLock(logger, configManager)
64
- }
65
-
66
- // touch the platformatic db config to trigger a restart
67
- const now = new Date()
68
-
69
- const configPath = configManager.fullPath
70
- utimesSync(configPath, now, now)
71
- } catch (err) {
72
- if (err.code === 'PTL_DB_MIGRATE_ERROR') {
73
- logger.error(err.message)
74
- process.exit(1)
75
- }
76
- /* c8 ignore next 2 */
77
- throw err
78
- }
79
- }
80
-
81
- export { applyMigrations, execute }