@platformatic/db 2.71.1-alpha.0 → 3.0.0-alpha.1

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 (58) hide show
  1. package/config.d.ts +1 -19
  2. package/eslint.config.js +9 -5
  3. package/index.d.ts +56 -31
  4. package/index.js +67 -128
  5. package/lib/application.js +102 -0
  6. package/lib/commands/index.js +59 -0
  7. package/lib/commands/migrations-apply.js +62 -0
  8. package/lib/commands/migrations-create.js +48 -0
  9. package/lib/commands/print-schema.js +30 -0
  10. package/lib/commands/seed.js +88 -0
  11. package/lib/commands/types.js +21 -0
  12. package/lib/errors.js +15 -11
  13. package/lib/{generator/db-generator.js → generator.js} +57 -52
  14. package/lib/{migrator.mjs → migrator.js} +45 -37
  15. package/lib/{root-endpoint/index.js → root.js} +6 -7
  16. package/lib/schema.js +31 -21
  17. package/lib/stackable.js +14 -26
  18. package/lib/{generator/code-templates.js → templates.js} +47 -17
  19. package/lib/types.js +160 -0
  20. package/lib/upgrade.js +7 -10
  21. package/lib/utils.js +12 -23
  22. package/lib/versions/0.18.0.js +3 -5
  23. package/lib/versions/{from-zero-twenty-height-to-will-see.js → 0.28.0.js} +3 -5
  24. package/lib/versions/2.0.0.js +3 -5
  25. package/package.json +16 -23
  26. package/schema.json +2 -73
  27. package/tsconfig.json +16 -6
  28. package/.snapshots/810d795d512560f3863d8db472c81c27/0.json +0 -1
  29. package/.snapshots/810d795d512560f3863d8db472c81c27/1.json +0 -1
  30. package/db.mjs +0 -86
  31. package/help/compile.txt +0 -17
  32. package/help/create.txt +0 -13
  33. package/help/help.txt +0 -11
  34. package/help/migrations apply.txt +0 -45
  35. package/help/migrations create.txt +0 -27
  36. package/help/migrations.txt +0 -4
  37. package/help/schema.txt +0 -25
  38. package/help/seed.txt +0 -36
  39. package/help/start.txt +0 -47
  40. package/help/types.txt +0 -40
  41. package/index.test-d.ts +0 -43
  42. package/lib/adjust-config.js +0 -42
  43. package/lib/create.mjs +0 -89
  44. package/lib/gen-migration.mjs +0 -53
  45. package/lib/gen-schema.mjs +0 -68
  46. package/lib/gen-types.mjs +0 -202
  47. package/lib/generator/README.md +0 -38
  48. package/lib/generator.d.ts +0 -7
  49. package/lib/migrate.mjs +0 -87
  50. package/lib/seed.mjs +0 -90
  51. /package/{lib/root-endpoint/public → public}/images/dark_mode.svg +0 -0
  52. /package/{lib/root-endpoint/public → public}/images/favicon.ico +0 -0
  53. /package/{lib/root-endpoint/public → public}/images/light_mode.svg +0 -0
  54. /package/{lib/root-endpoint/public → public}/images/platformatic-logo-dark.svg +0 -0
  55. /package/{lib/root-endpoint/public → public}/images/platformatic-logo-light.svg +0 -0
  56. /package/{lib/root-endpoint/public → public}/images/triangle_dark.svg +0 -0
  57. /package/{lib/root-endpoint/public → public}/images/triangle_light.svg +0 -0
  58. /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,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,87 +0,0 @@
1
- #! /usr/bin/env node
2
-
3
- import { loadConfig } from '@platformatic/config'
4
- import { checkForDependencies } from '@platformatic/utils'
5
- import { utimesSync } from 'fs'
6
- import { createRequire } from 'node:module'
7
- import pino from 'pino'
8
- import pretty from 'pino-pretty'
9
- import { platformaticDB } from '../index.js'
10
- import errors from './errors.js'
11
- import { execute as generateTypes } from './gen-types.mjs'
12
- import { Migrator } from './migrator.mjs'
13
- import { updateSchemaLock } from './utils.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(
36
- pretty({
37
- translateTime: 'SYS:HH:MM:ss',
38
- ignore: 'hostname,pid'
39
- })
40
- )
41
-
42
- try {
43
- const { configManager, args } = await loadConfig(
44
- {
45
- string: ['to'],
46
- boolean: ['rollback'],
47
- alias: {
48
- t: 'to',
49
- r: 'rollback'
50
- }
51
- },
52
- _args,
53
- platformaticDB
54
- )
55
-
56
- const config = configManager.current
57
- const appliedMigrations = await execute({ logger, ...args, config })
58
-
59
- if (config.types && config.types.autogenerate) {
60
- await generateTypes({ logger, config, configManager })
61
- const modules = ['@platformatic/db']
62
- if (config.plugins?.typescript) {
63
- modules.push('typescript')
64
- }
65
- await checkForDependencies(logger, args, createRequire(import.meta.url), config, modules)
66
- }
67
-
68
- if (appliedMigrations) {
69
- await updateSchemaLock(logger, configManager)
70
- }
71
-
72
- // touch the platformatic db config to trigger a restart
73
- const now = new Date()
74
-
75
- const configPath = configManager.fullPath
76
- utimesSync(configPath, now, now)
77
- } catch (err) {
78
- if (err.code === 'PTL_DB_MIGRATE_ERROR') {
79
- logger.error(err.message)
80
- process.exit(1)
81
- }
82
- /* c8 ignore next 2 */
83
- throw err
84
- }
85
- }
86
-
87
- export { applyMigrations, execute }
package/lib/seed.mjs DELETED
@@ -1,90 +0,0 @@
1
- import pino from 'pino'
2
- import pretty from 'pino-pretty'
3
- import { access, readFile } from 'fs/promises'
4
- import { setupDB } from './utils.js'
5
- import { Migrator } from './migrator.mjs'
6
- import { pathToFileURL } from 'url'
7
- import { loadConfig } from '@platformatic/config'
8
- import { platformaticDB } from '../index.js'
9
- import errors from './errors.js'
10
- import tsCompiler from '@platformatic/ts-compiler'
11
- import { join, resolve } from 'node:path'
12
-
13
- async function execute (logger, seedFile, config) {
14
- const { db, sql, entities } = await setupDB(logger, config.db)
15
-
16
- await access(seedFile)
17
-
18
- logger.info(`seeding from ${seedFile}`)
19
- let seedFunction
20
- const importedFunction = await import(pathToFileURL(seedFile))
21
-
22
- if (typeof importedFunction === 'function') {
23
- seedFunction = importedFunction
24
- } else if (typeof importedFunction.seed === 'function') {
25
- seedFunction = importedFunction.seed
26
- } else if (typeof importedFunction.default === 'function') {
27
- seedFunction = importedFunction.default
28
- }
29
-
30
- if (!seedFunction) {
31
- logger.error('Cannot find seed function.')
32
- logger.error('If you use an ESM module use the signature \'export async function seed (opts)\'.')
33
- logger.error('If you use a CJS module use the signature \'module.exports = async function seed (opts)\'.')
34
- logger.error('If you use Typescript use the signature \'export async function seed(opts)\'')
35
- return
36
- }
37
- await seedFunction({ db, sql, entities, logger })
38
- logger.info('seeding complete')
39
-
40
- // Once done seeding, close your connection.
41
- await db.dispose()
42
- }
43
-
44
- async function seed (_args) {
45
- const logger = pino(pretty({
46
- translateTime: 'SYS:HH:MM:ss',
47
- ignore: 'hostname,pid',
48
- }))
49
-
50
- const { configManager, args } = await loadConfig({
51
- alias: {
52
- c: 'config',
53
- },
54
- }, _args, platformaticDB)
55
- await configManager.parseAndValidate()
56
- const config = configManager.current
57
-
58
- if (config.migrations !== undefined) {
59
- const migrator = new Migrator(config.migrations, config.db, logger)
60
-
61
- try {
62
- const hasMigrationsToApply = await migrator.hasMigrationsToApply()
63
- if (hasMigrationsToApply) {
64
- throw new errors.MigrationsToApplyError()
65
- }
66
- } finally {
67
- await migrator.close()
68
- }
69
- }
70
- let seedFile = args._[0]
71
- if (!seedFile) {
72
- throw new errors.MissingSeedFileError()
73
- }
74
- // check if we are in Typescript and, in case, compile it
75
- if (seedFile.endsWith('.ts')) {
76
- await tsCompiler.compile({
77
- cwd: process.cwd(),
78
- logger,
79
- tsConfig: configManager.current.plugins?.typescript?.tsConfig,
80
- flags: configManager.current.plugins?.typescript?.flags,
81
- })
82
- const tsConfigPath = config?.plugins?.typescript?.tsConfig || resolve(process.cwd(), 'tsconfig.json')
83
- const tsConfig = JSON.parse(await readFile(tsConfigPath, 'utf8'))
84
- const outDir = tsConfig.compilerOptions.outDir
85
- seedFile = join(outDir, seedFile.replace('.ts', '.js'))
86
- }
87
- await execute(logger, seedFile, config)
88
- }
89
-
90
- export { seed, execute }
File without changes