@contember/engine-http 1.1.1 → 1.2.0-alpha.10
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.
- package/dist/src/ProjectContainer.d.ts +5 -2
- package/dist/src/ProjectContainer.d.ts.map +1 -1
- package/dist/src/ProjectGroupContainer.d.ts +2 -3
- package/dist/src/ProjectGroupContainer.d.ts.map +1 -1
- package/dist/src/common/ErrorMiddleware.d.ts.map +1 -1
- package/dist/src/common/ErrorMiddleware.js +5 -2
- package/dist/src/common/ErrorMiddleware.js.map +1 -1
- package/dist/src/common/TimerMiddleware.d.ts.map +1 -1
- package/dist/src/common/TimerMiddleware.js +24 -7
- package/dist/src/common/TimerMiddleware.js.map +1 -1
- package/dist/src/config.d.ts +3 -2
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/content/ContentApiMiddlewareFactory.d.ts +1 -2
- package/dist/src/content/ContentApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/src/content/ContentApiMiddlewareFactory.js +25 -23
- package/dist/src/content/ContentApiMiddlewareFactory.js.map +1 -1
- package/dist/src/content/ContentGraphQLContextFactory.d.ts +2 -2
- package/dist/src/content/ContentGraphQLContextFactory.d.ts.map +1 -1
- package/dist/src/content/ContentGraphQLContextFactory.js +2 -5
- package/dist/src/content/ContentGraphQLContextFactory.js.map +1 -1
- package/dist/src/content/ContentSchemaResolver.d.ts +2 -3
- package/dist/src/content/ContentSchemaResolver.d.ts.map +1 -1
- package/dist/src/content/GraphQlSchemaFactory.d.ts.map +1 -1
- package/dist/src/content/GraphQlSchemaFactory.js +1 -2
- package/dist/src/content/GraphQlSchemaFactory.js.map +1 -1
- package/dist/src/content/ProjectMembershipFetcher.d.ts +12 -0
- package/dist/src/content/ProjectMembershipFetcher.d.ts.map +1 -0
- package/dist/src/content/ProjectMembershipFetcher.js +14 -0
- package/dist/src/content/ProjectMembershipFetcher.js.map +1 -0
- package/dist/src/content/ProjectMembershipResolver.d.ts +25 -0
- package/dist/src/content/ProjectMembershipResolver.d.ts.map +1 -0
- package/dist/src/content/ProjectMembershipResolver.js +113 -0
- package/dist/src/content/ProjectMembershipResolver.js.map +1 -0
- package/dist/src/content/index.d.ts +2 -0
- package/dist/src/content/index.d.ts.map +1 -1
- package/dist/src/content/index.js +2 -0
- package/dist/src/content/index.js.map +1 -1
- package/dist/src/graphql/execution.js +2 -2
- package/dist/src/graphql/execution.js.map +1 -1
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +1 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/koa/types.d.ts +1 -0
- package/dist/src/koa/types.d.ts.map +1 -1
- package/dist/src/project-common/ProjectGroupResolver.d.ts +2 -9
- package/dist/src/project-common/ProjectGroupResolver.d.ts.map +1 -1
- package/dist/src/project-common/ProjectGroupResolver.js +0 -47
- package/dist/src/project-common/ProjectGroupResolver.js.map +1 -1
- package/dist/src/system/SystemApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/src/system/SystemApiMiddlewareFactory.js +11 -3
- package/dist/src/system/SystemApiMiddlewareFactory.js.map +1 -1
- package/dist/src/system/SystemGraphQLContextFactory.d.ts +2 -2
- package/dist/src/system/SystemGraphQLContextFactory.d.ts.map +1 -1
- package/dist/src/transfer/Command.d.ts +23 -0
- package/dist/src/transfer/Command.d.ts.map +1 -0
- package/dist/src/transfer/Command.js +53 -0
- package/dist/src/transfer/Command.js.map +1 -0
- package/dist/src/transfer/CommandStream.d.ts +6 -0
- package/dist/src/transfer/CommandStream.d.ts.map +1 -0
- package/dist/src/transfer/CommandStream.js +90 -0
- package/dist/src/transfer/CommandStream.js.map +1 -0
- package/dist/src/transfer/ContentSchemaTransferMappingFactory.d.ts +8 -0
- package/dist/src/transfer/ContentSchemaTransferMappingFactory.d.ts.map +1 -0
- package/dist/src/transfer/ContentSchemaTransferMappingFactory.js +106 -0
- package/dist/src/transfer/ContentSchemaTransferMappingFactory.js.map +1 -0
- package/dist/src/transfer/ExportApiMiddlewareFactory.d.ts +15 -0
- package/dist/src/transfer/ExportApiMiddlewareFactory.d.ts.map +1 -0
- package/dist/src/transfer/ExportApiMiddlewareFactory.js +73 -0
- package/dist/src/transfer/ExportApiMiddlewareFactory.js.map +1 -0
- package/dist/src/transfer/ExportExecutor.d.ts +24 -0
- package/dist/src/transfer/ExportExecutor.d.ts.map +1 -0
- package/dist/src/transfer/ExportExecutor.js +130 -0
- package/dist/src/transfer/ExportExecutor.js.map +1 -0
- package/dist/src/transfer/ImportApiMiddlewareFactory.d.ts +15 -0
- package/dist/src/transfer/ImportApiMiddlewareFactory.d.ts.map +1 -0
- package/dist/src/transfer/ImportApiMiddlewareFactory.js +35 -0
- package/dist/src/transfer/ImportApiMiddlewareFactory.js.map +1 -0
- package/dist/src/transfer/ImportExecutor.d.ts +40 -0
- package/dist/src/transfer/ImportExecutor.d.ts.map +1 -0
- package/dist/src/transfer/ImportExecutor.js +318 -0
- package/dist/src/transfer/ImportExecutor.js.map +1 -0
- package/dist/src/transfer/SystemSchemaTransferMappingFactory.d.ts +8 -0
- package/dist/src/transfer/SystemSchemaTransferMappingFactory.d.ts.map +1 -0
- package/dist/src/transfer/SystemSchemaTransferMappingFactory.js +167 -0
- package/dist/src/transfer/SystemSchemaTransferMappingFactory.js.map +1 -0
- package/dist/src/transfer/TransferMapping.d.ts +38 -0
- package/dist/src/transfer/TransferMapping.d.ts.map +1 -0
- package/dist/src/transfer/TransferMapping.js +3 -0
- package/dist/src/transfer/TransferMapping.js.map +1 -0
- package/dist/src/transfer/index.d.ts +7 -0
- package/dist/src/transfer/index.d.ts.map +1 -0
- package/dist/src/transfer/index.js +23 -0
- package/dist/src/transfer/index.js.map +1 -0
- package/dist/src/tsconfig.tsbuildinfo +1 -1
- package/dist/src/utils/CryptoWrapper.d.ts +1 -0
- package/dist/src/utils/CryptoWrapper.d.ts.map +1 -1
- package/dist/tests/cases/unit/projectMembershipResolver.test.d.ts +2 -0
- package/dist/tests/cases/unit/projectMembershipResolver.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/projectMembershipResolver.test.js +105 -0
- package/dist/tests/cases/unit/projectMembershipResolver.test.js.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/tests/utils.d.ts +6 -0
- package/dist/tests/utils.d.ts.map +1 -0
- package/dist/tests/utils.js +8 -0
- package/dist/tests/utils.js.map +1 -0
- package/package.json +14 -14
- package/src/ProjectContainer.ts +2 -2
- package/src/ProjectGroupContainer.ts +2 -4
- package/src/common/ErrorMiddleware.ts +5 -2
- package/src/common/TimerMiddleware.ts +30 -9
- package/src/config.ts +7 -2
- package/src/content/ContentApiMiddlewareFactory.ts +23 -30
- package/src/content/ContentGraphQLContextFactory.ts +4 -7
- package/src/content/ContentSchemaResolver.ts +1 -1
- package/src/content/GraphQlSchemaFactory.ts +1 -2
- package/src/content/ProjectMembershipFetcher.ts +18 -0
- package/src/content/ProjectMembershipResolver.ts +119 -0
- package/src/content/index.ts +2 -0
- package/src/graphql/execution.ts +2 -2
- package/src/index.ts +1 -0
- package/src/koa/types.ts +1 -1
- package/src/project-common/ProjectGroupResolver.ts +3 -53
- package/src/system/SystemApiMiddlewareFactory.ts +10 -3
- package/src/system/SystemGraphQLContextFactory.ts +2 -2
- package/src/transfer/Command.ts +42 -0
- package/src/transfer/CommandStream.ts +72 -0
- package/src/transfer/ContentSchemaTransferMappingFactory.ts +115 -0
- package/src/transfer/ExportApiMiddlewareFactory.ts +93 -0
- package/src/transfer/ExportExecutor.ts +132 -0
- package/src/transfer/ImportApiMiddlewareFactory.ts +49 -0
- package/src/transfer/ImportExecutor.ts +393 -0
- package/src/transfer/SystemSchemaTransferMappingFactory.ts +178 -0
- package/src/transfer/TransferMapping.ts +24 -0
- package/src/transfer/index.ts +8 -0
- package/tests/cases/unit/projectMembershipResolver.test.ts +107 -0
- package/tests/utils.ts +5 -0
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
import { asyncIterableTransaction, Client, Connection, ConstraintHelper, wrapIdentifier } from '@contember/database'
|
|
2
|
+
import { Model, Schema } from '@contember/schema'
|
|
3
|
+
import * as Typesafe from '@contember/typesafe'
|
|
4
|
+
import { ParseError } from '@contember/typesafe'
|
|
5
|
+
import { Command, CommandArgsMap, CommandName } from './Command'
|
|
6
|
+
import { DatabaseContext, StageBySlugQuery } from '@contember/engine-system-api'
|
|
7
|
+
import { ProjectGroupContainer } from '../ProjectGroupContainer'
|
|
8
|
+
import { DbColumnSchema, TransferMapping, TransferTableMapping } from './TransferMapping'
|
|
9
|
+
import { Logger } from '@contember/engine-common'
|
|
10
|
+
import { ContentSchemaTransferMappingFactory } from './ContentSchemaTransferMappingFactory'
|
|
11
|
+
import { SystemSchemaTransferMappingFactory } from './SystemSchemaTransferMappingFactory'
|
|
12
|
+
import { AuthResult, HttpError } from '../common/index'
|
|
13
|
+
|
|
14
|
+
type Cell = boolean | number | string | null
|
|
15
|
+
type Row = readonly Cell[]
|
|
16
|
+
|
|
17
|
+
type InsertContext = {
|
|
18
|
+
tableName: string
|
|
19
|
+
insertStartFragment: string
|
|
20
|
+
rowFragment: string
|
|
21
|
+
rowParser: Typesafe.Type<Row>
|
|
22
|
+
rows: Array<Row>
|
|
23
|
+
insertedRowCount: number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class ImportError extends Error {
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type CommandProcessor<T extends CommandName> = (it: CommandIterator<T>) => AsyncGenerator<ImportProgress, CommandIterator | null>
|
|
30
|
+
type CommandProcessorMap<T extends CommandName> = { [N in CommandName]?: N extends T ? CommandProcessor<N> : undefined }
|
|
31
|
+
|
|
32
|
+
class CommandIterator<T extends CommandName = CommandName> {
|
|
33
|
+
private constructor(
|
|
34
|
+
public readonly commandName: T,
|
|
35
|
+
public readonly commandArgs: CommandArgsMap[T],
|
|
36
|
+
private readonly commandIterator: AsyncIterator<Command>,
|
|
37
|
+
) {
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
public static async create(commands: AsyncIterable<Command>): Promise<CommandIterator | null> {
|
|
41
|
+
const commandIterator = commands[Symbol.asyncIterator]()
|
|
42
|
+
const result = await commandIterator.next()
|
|
43
|
+
|
|
44
|
+
if (result.done) {
|
|
45
|
+
return null
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const [name, ...args] = result.value
|
|
49
|
+
return new CommandIterator(name, args, commandIterator)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async next(): Promise<CommandIterator | null> {
|
|
53
|
+
const result = await this.commandIterator.next()
|
|
54
|
+
|
|
55
|
+
if (result.done) {
|
|
56
|
+
return null
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const [name, ...args] = result.value
|
|
60
|
+
return new CommandIterator(name, args, this.commandIterator)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export type ImportProgress =
|
|
65
|
+
| [kind: 'error', message: string]
|
|
66
|
+
| [kind: 'insertRow', details: { table: string; insertedRowCount: number }]
|
|
67
|
+
| [kind: 'insertEnd', details: { table: string; insertedRowCount: number }]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
export class ImportExecutor {
|
|
71
|
+
constructor(
|
|
72
|
+
private readonly contentSchemaTransferMappingFactory: ContentSchemaTransferMappingFactory,
|
|
73
|
+
private readonly systemSchemaTransferMappingFactory: SystemSchemaTransferMappingFactory,
|
|
74
|
+
private readonly logger: Logger,
|
|
75
|
+
) {
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async* import(groupContainer: ProjectGroupContainer, authResult: AuthResult, commands: AsyncIterable<Command>): AsyncIterable<ImportProgress> {
|
|
79
|
+
try {
|
|
80
|
+
const it = await CommandIterator.create(commands)
|
|
81
|
+
|
|
82
|
+
const final = yield* this.match(it, {
|
|
83
|
+
importContentSchemaBegin: it => this.importContentSchemaBegin(groupContainer, authResult, it),
|
|
84
|
+
importSystemSchemaBegin: it => this.importSystemSchemaBegin(groupContainer, authResult, it),
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
if (final !== null) {
|
|
88
|
+
throw new ImportError(`Unexpected ${final.commandName}`)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
} catch (e) {
|
|
92
|
+
if (e instanceof ImportError) {
|
|
93
|
+
yield ['error', e.message]
|
|
94
|
+
|
|
95
|
+
} else {
|
|
96
|
+
throw e
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
private async* match<T extends CommandName>(it: CommandIterator<T> | null, processors: CommandProcessorMap<T>) {
|
|
102
|
+
let next: CommandIterator | null = it
|
|
103
|
+
|
|
104
|
+
while (next !== null) {
|
|
105
|
+
const processor = processors[next.commandName]
|
|
106
|
+
|
|
107
|
+
if (processor) {
|
|
108
|
+
next = yield* processor(next as any)
|
|
109
|
+
|
|
110
|
+
} else {
|
|
111
|
+
break
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return next
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private async* importContentSchemaBegin(groupContainer: ProjectGroupContainer, authResult: AuthResult, it: CommandIterator<'importContentSchemaBegin'>) {
|
|
119
|
+
const [options] = it.commandArgs
|
|
120
|
+
const projectContainer = await this.createProjectContainer(groupContainer, options.project)
|
|
121
|
+
const systemDatabaseContext = projectContainer.systemDatabaseContextFactory.create()
|
|
122
|
+
const stage = await this.fetchStageBySlug(systemDatabaseContext, options.project, options.stage)
|
|
123
|
+
|
|
124
|
+
const contentSchema = await projectContainer.contentSchemaResolver.getSchema(systemDatabaseContext, stage.slug)
|
|
125
|
+
|
|
126
|
+
if (contentSchema.version !== options.schemaVersion) {
|
|
127
|
+
throw new ImportError(`Incompatible schema version (import version ${options.schemaVersion} does not match server version ${contentSchema.version})`)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
await this.requireImportAccess(groupContainer, contentSchema, authResult, options.project, 'content')
|
|
131
|
+
const contentDatabaseClient = projectContainer.connection.createClient(stage.schema, {})
|
|
132
|
+
const mapping = this.contentSchemaTransferMappingFactory.createContentSchemaMapping(contentSchema)
|
|
133
|
+
|
|
134
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
135
|
+
const that = this
|
|
136
|
+
return yield* asyncIterableTransaction(contentDatabaseClient, async function* (db) {
|
|
137
|
+
await that.disableTriggers(db, options.tables)
|
|
138
|
+
await that.lockTables(db, options.tables)
|
|
139
|
+
await that.truncateTables(db, options.tables)
|
|
140
|
+
|
|
141
|
+
const constraintHelper = new ConstraintHelper(db)
|
|
142
|
+
await constraintHelper.setFkConstraintsDeferred()
|
|
143
|
+
|
|
144
|
+
const result = yield* that.match(await it.next(), {
|
|
145
|
+
importSequence: it => that.importSequence(db, mapping, it),
|
|
146
|
+
insertBegin: it => that.insertBegin(db, mapping, it),
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
await constraintHelper.setFkConstraintsImmediate()
|
|
150
|
+
await that.enableTriggers(db, options.tables)
|
|
151
|
+
|
|
152
|
+
return result
|
|
153
|
+
})
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
private async* importSystemSchemaBegin(groupContainer: ProjectGroupContainer, authResult: AuthResult, it: CommandIterator<'importSystemSchemaBegin'>) {
|
|
157
|
+
const [options] = it.commandArgs
|
|
158
|
+
const projectContainer = await this.createProjectContainer(groupContainer, options.project)
|
|
159
|
+
const schema = await groupContainer.projectSchemaResolver.getSchema(options.project)
|
|
160
|
+
|
|
161
|
+
if (schema === undefined) {
|
|
162
|
+
throw new ImportError(`Project ${options.project} does not have schema`)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
await this.requireImportAccess(groupContainer, schema, authResult, options.project, 'system')
|
|
166
|
+
const systemDatabaseContext = projectContainer.systemDatabaseContextFactory.create()
|
|
167
|
+
const mapping = this.systemSchemaTransferMappingFactory.build()
|
|
168
|
+
|
|
169
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
170
|
+
const that = this
|
|
171
|
+
return yield* asyncIterableTransaction(systemDatabaseContext.client, async function* (db) {
|
|
172
|
+
await that.truncateTables(db, options.tables)
|
|
173
|
+
|
|
174
|
+
const constraintHelper = new ConstraintHelper(db)
|
|
175
|
+
await constraintHelper.setFkConstraintsDeferred()
|
|
176
|
+
|
|
177
|
+
return yield* that.match(await it.next(), {
|
|
178
|
+
insertBegin: it => that.insertBegin(db, mapping, it),
|
|
179
|
+
})
|
|
180
|
+
})
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
private async* importSequence(db: Client<Connection.TransactionLike>, mapping: TransferMapping, it: CommandIterator<'importSequence'>): AsyncGenerator<ImportProgress, CommandIterator | null> {
|
|
184
|
+
const [options] = it.commandArgs
|
|
185
|
+
|
|
186
|
+
await db.query(
|
|
187
|
+
'SELECT setval(pg_get_serial_sequence(?, ?), ?)',
|
|
188
|
+
[`${db.schema}.${options.table}`, options.column, options.value],
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
return it.next()
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private async* insertBegin(db: Client<Connection.TransactionLike>, mapping: TransferMapping, it: CommandIterator<'insertBegin'>): AsyncGenerator<ImportProgress, CommandIterator | null> {
|
|
195
|
+
const [options] = it.commandArgs
|
|
196
|
+
const insertContext = await this.buildInsertContext(db, mapping, db.schema, options.table, options.columns)
|
|
197
|
+
let insertRowsPromise: Promise<Connection.Result> | null = null
|
|
198
|
+
let lastEmitAt = process.hrtime.bigint()
|
|
199
|
+
|
|
200
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
201
|
+
const that = this
|
|
202
|
+
const result = yield* this.match(await it.next(), {
|
|
203
|
+
insertRow: async function* (it) {
|
|
204
|
+
const [values] = it.commandArgs
|
|
205
|
+
|
|
206
|
+
try {
|
|
207
|
+
insertContext.rows.push(insertContext.rowParser(values))
|
|
208
|
+
|
|
209
|
+
} catch (e) {
|
|
210
|
+
if (e instanceof ParseError) {
|
|
211
|
+
throw new ImportError(`Invalid row ${JSON.stringify(values)} for table ${options.table}: ${e.message}`)
|
|
212
|
+
|
|
213
|
+
} else {
|
|
214
|
+
throw e
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (insertContext.rows.length === 1000) {
|
|
219
|
+
await insertRowsPromise
|
|
220
|
+
insertRowsPromise = that.insertRows(db, insertContext)
|
|
221
|
+
insertContext.insertedRowCount += insertContext.rows.length
|
|
222
|
+
insertContext.rows = []
|
|
223
|
+
|
|
224
|
+
const now = process.hrtime.bigint()
|
|
225
|
+
|
|
226
|
+
if (now - lastEmitAt > 1e9) {
|
|
227
|
+
yield ['insertRow', { table: insertContext.tableName, insertedRowCount: insertContext.insertedRowCount }]
|
|
228
|
+
lastEmitAt = now
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return await it.next()
|
|
233
|
+
},
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
if (insertContext.rows.length > 0) {
|
|
237
|
+
await insertRowsPromise
|
|
238
|
+
await this.insertRows(db, insertContext)
|
|
239
|
+
insertContext.insertedRowCount += insertContext.rows.length
|
|
240
|
+
insertContext.rows = []
|
|
241
|
+
|
|
242
|
+
yield ['insertEnd', { table: insertContext.tableName, insertedRowCount: insertContext.insertedRowCount }]
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (result === null || result.commandName !== 'insertEnd') {
|
|
246
|
+
throw new ImportError(`Missing insertEnd command`)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return await result.next()
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
private async createProjectContainer(groupContainer: ProjectGroupContainer, projectSlug: string) {
|
|
253
|
+
const projectContainerResolver = groupContainer.projectContainerResolver
|
|
254
|
+
const projectContainer = await projectContainerResolver.getProjectContainer(projectSlug, { alias: true, logger: this.logger })
|
|
255
|
+
|
|
256
|
+
if (projectContainer === undefined) {
|
|
257
|
+
throw new ImportError(`Project ${projectSlug} does not exists.`)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return projectContainer
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
private async requireImportAccess(groupContainer: ProjectGroupContainer, schema: Schema, authResult: AuthResult, projectSlug: string, kind: 'content' | 'system') {
|
|
264
|
+
const memberships = await groupContainer.projectMembershipResolver.resolveMemberships({
|
|
265
|
+
request: { get: () => '' },
|
|
266
|
+
acl: schema.acl,
|
|
267
|
+
projectSlug: projectSlug,
|
|
268
|
+
identity: {
|
|
269
|
+
identityId: authResult.identityId,
|
|
270
|
+
roles: authResult.roles,
|
|
271
|
+
},
|
|
272
|
+
})
|
|
273
|
+
|
|
274
|
+
const projectRoles = memberships.map(it => it.role)
|
|
275
|
+
|
|
276
|
+
if (!projectRoles.some(role => schema.acl.roles[role]?.[kind]?.import)) {
|
|
277
|
+
throw new HttpError(`You are not allowed to import ${kind} in ${projectSlug}`, 403)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
private async fetchStageBySlug(systemDatabaseContext: DatabaseContext, projectSlug: string, stageSlug: string) {
|
|
282
|
+
const stage = await systemDatabaseContext.queryHandler.fetch(new StageBySlugQuery(stageSlug))
|
|
283
|
+
|
|
284
|
+
if (stage === null) {
|
|
285
|
+
throw new ImportError(`Project ${projectSlug} does not have stage ${stageSlug}.`)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return stage
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
private async disableTriggers(db: Client, tableNames: readonly string[]) {
|
|
292
|
+
for (const tableName of tableNames) {
|
|
293
|
+
const tableNameQuoted = `${wrapIdentifier(db.schema)}.${wrapIdentifier(tableName)}`
|
|
294
|
+
await db.query(`ALTER TABLE ${tableNameQuoted} DISABLE TRIGGER USER`)
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
private async enableTriggers(db: Client, tableNames: readonly string[]) {
|
|
299
|
+
for (const tableName of tableNames) {
|
|
300
|
+
const tableNameQuoted = `${wrapIdentifier(db.schema)}.${wrapIdentifier(tableName)}`
|
|
301
|
+
await db.query(`ALTER TABLE ${tableNameQuoted} ENABLE TRIGGER USER`)
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private async lockTables(db: Client, tableNames: readonly string[]) {
|
|
306
|
+
const tableNamesQuoted = tableNames.map(it => `${wrapIdentifier(db.schema)}.${wrapIdentifier(it)}`)
|
|
307
|
+
await db.query(`LOCK ${tableNamesQuoted.join(', ')} IN EXCLUSIVE MODE`)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private async truncateTables(db: Client, tableNames: readonly string[]) {
|
|
311
|
+
const tableNamesQuoted = tableNames.map(it => `${wrapIdentifier(db.schema)}.${wrapIdentifier(it)}`)
|
|
312
|
+
await db.query(`TRUNCATE ${tableNamesQuoted.join(', ')}`)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
private async insertRows(db: Client, context: InsertContext) {
|
|
316
|
+
const rowsFragment = context.rows.map(_ => context.rowFragment).join(',\n')
|
|
317
|
+
const sql = context.insertStartFragment + rowsFragment
|
|
318
|
+
const parameters: Cell[] = []
|
|
319
|
+
|
|
320
|
+
for (const row of context.rows) {
|
|
321
|
+
for (const cell of row) {
|
|
322
|
+
parameters.push(cell)
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
return await db.query(sql, parameters)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
private async buildInsertContext(db: Client, mapping: TransferMapping, schema: string, tableName: string, columnNames: readonly string[]): Promise<InsertContext> {
|
|
330
|
+
const tableMapping = mapping.tables[tableName]
|
|
331
|
+
const columns = []
|
|
332
|
+
|
|
333
|
+
if (tableMapping === undefined) {
|
|
334
|
+
throw new ImportError(`Unknown table ${tableName}`)
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
for (const columnName of columnNames) {
|
|
338
|
+
const column = tableMapping.columns[columnName]
|
|
339
|
+
|
|
340
|
+
if (column === undefined) {
|
|
341
|
+
throw new ImportError(`Unknown column ${tableName}.${columnName}`)
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
columns.push(column)
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const insertStartFragment = (tableMapping.createInsertStartFragment ?? this.createInsertStartFragment)(schema, tableName, columnNames)
|
|
348
|
+
const rowFragment = '(' + columns.map(_ => '?').join(', ') + ')'
|
|
349
|
+
const rowParser = await this.buildRowParser(db, tableMapping, columns)
|
|
350
|
+
|
|
351
|
+
return {
|
|
352
|
+
tableName,
|
|
353
|
+
insertStartFragment,
|
|
354
|
+
rowFragment,
|
|
355
|
+
rowParser,
|
|
356
|
+
rows: [],
|
|
357
|
+
insertedRowCount: 0,
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private createInsertStartFragment(schema: string, tableName: string, columnNames: readonly string[]): string {
|
|
362
|
+
const tableQuoted = `${wrapIdentifier(schema)}.${wrapIdentifier(tableName)}`
|
|
363
|
+
const columnsQuoted = '(' + columnNames.map(it => wrapIdentifier(it)).join(', ') + ')'
|
|
364
|
+
return `INSERT INTO ${tableQuoted} ${columnsQuoted} VALUES\n`
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private async buildRowParser(db: Client, tableMapping: TransferTableMapping, columns: DbColumnSchema[]): Promise<Typesafe.Type<readonly Cell[]>> {
|
|
368
|
+
const baseType = Typesafe.tuple(...columns.map(it => {
|
|
369
|
+
const base = this.buildColumnRuntimeType(it.type)
|
|
370
|
+
return it.nullable ? Typesafe.nullable(base) : base
|
|
371
|
+
}))
|
|
372
|
+
|
|
373
|
+
if (tableMapping.createRowParser === undefined) {
|
|
374
|
+
return baseType
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
return await tableMapping.createRowParser(db, columns.map(it => it.name), baseType)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
private buildColumnRuntimeType(columnType: Model.ColumnType): Typesafe.Type<Exclude<Cell, null>> {
|
|
381
|
+
switch (columnType) {
|
|
382
|
+
case Model.ColumnType.Uuid: return Typesafe.string // TODO
|
|
383
|
+
case Model.ColumnType.String: return Typesafe.string
|
|
384
|
+
case Model.ColumnType.Int: return Typesafe.number // TODO
|
|
385
|
+
case Model.ColumnType.Double: return Typesafe.number
|
|
386
|
+
case Model.ColumnType.Bool: return Typesafe.boolean
|
|
387
|
+
case Model.ColumnType.Enum: return Typesafe.string // TODO
|
|
388
|
+
case Model.ColumnType.DateTime: return Typesafe.string // TODO
|
|
389
|
+
case Model.ColumnType.Date: return Typesafe.string // TODO
|
|
390
|
+
case Model.ColumnType.Json: return Typesafe.string
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { TransferMapping, TransferTableMapping } from './TransferMapping'
|
|
2
|
+
import { Model } from '@contember/schema'
|
|
3
|
+
import * as Typesafe from '@contember/typesafe'
|
|
4
|
+
import { Compiler, Operator, wrapIdentifier } from '@contember/database'
|
|
5
|
+
import { ImportError } from './ImportExecutor'
|
|
6
|
+
|
|
7
|
+
export class SystemSchemaTransferMappingFactory {
|
|
8
|
+
build(): TransferMapping {
|
|
9
|
+
return {
|
|
10
|
+
tables: this.associateByName([
|
|
11
|
+
this.buildEventDataMapping(),
|
|
12
|
+
this.buildStageTransactionDataMapping(),
|
|
13
|
+
]),
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
private buildStageTransactionDataMapping(): TransferTableMapping {
|
|
18
|
+
return {
|
|
19
|
+
name: 'stage_transaction',
|
|
20
|
+
|
|
21
|
+
columns: this.associateByName([
|
|
22
|
+
{ name: 'transaction_id', type: Model.ColumnType.Uuid },
|
|
23
|
+
{ name: 'stage_slug', type: Model.ColumnType.String },
|
|
24
|
+
{ name: 'applied_at', type: Model.ColumnType.DateTime },
|
|
25
|
+
]),
|
|
26
|
+
|
|
27
|
+
createSelect: (db, table) => {
|
|
28
|
+
const namespaceContext = new Compiler.Context(db.schema, new Set())
|
|
29
|
+
|
|
30
|
+
let builder = db.selectBuilder()
|
|
31
|
+
|
|
32
|
+
for (const column of Object.values(table.columns)) {
|
|
33
|
+
if (column.name === 'stage_slug') {
|
|
34
|
+
builder = builder.select(['stage', 'slug'], 'stage_slug')
|
|
35
|
+
|
|
36
|
+
} else if (column.type === Model.ColumnType.Json || column.type === Model.ColumnType.Date || column.type === Model.ColumnType.DateTime) {
|
|
37
|
+
builder = builder.select(expr => expr.raw(`${wrapIdentifier('stage_transaction')}.${wrapIdentifier(column.name)}::text`))
|
|
38
|
+
|
|
39
|
+
} else {
|
|
40
|
+
builder = builder.select(['stage_transaction', column.name])
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return builder
|
|
45
|
+
.from('stage_transaction')
|
|
46
|
+
.join(
|
|
47
|
+
'stage',
|
|
48
|
+
undefined,
|
|
49
|
+
expr => expr.compareColumns(['stage', 'id'], Operator.eq, ['stage_transaction', 'stage_id']),
|
|
50
|
+
)
|
|
51
|
+
.createQuery(namespaceContext)
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
createInsertStartFragment: (schema, tableName, columnNames) => {
|
|
55
|
+
const columnNames2 = columnNames.map(name => name === 'stage_slug' ? 'stage_id' : name)
|
|
56
|
+
const tableQuoted = `${wrapIdentifier(schema)}.${wrapIdentifier(tableName)}`
|
|
57
|
+
const columnsQuoted = '(' + columnNames2.map(it => wrapIdentifier(it)).join(', ') + ')'
|
|
58
|
+
return `INSERT INTO ${tableQuoted} ${columnsQuoted} VALUES\n`
|
|
59
|
+
},
|
|
60
|
+
|
|
61
|
+
createRowParser: async (db, columns, baseType) => {
|
|
62
|
+
const stages = await db.selectBuilder<{id: string; slug: string}>()
|
|
63
|
+
.select('id')
|
|
64
|
+
.select('slug')
|
|
65
|
+
.from('stage')
|
|
66
|
+
.getResult(db)
|
|
67
|
+
|
|
68
|
+
const stageSlugToId = new Map(stages.map(row => ([row.slug, row.id])))
|
|
69
|
+
const stageSlugColumnIndex = columns.indexOf('stage_slug')
|
|
70
|
+
|
|
71
|
+
if (stageSlugColumnIndex < 0) {
|
|
72
|
+
return baseType
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return (input, path) => {
|
|
76
|
+
const row = baseType(input, path)
|
|
77
|
+
const stageSlug = Typesafe.string(row[stageSlugColumnIndex])
|
|
78
|
+
const stageSlugId = stageSlugToId.get(stageSlug)
|
|
79
|
+
|
|
80
|
+
if (stageSlugId === undefined) {
|
|
81
|
+
throw new ImportError(`Unknown stage slug ${stageSlug}`)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const newRow = [...row]
|
|
85
|
+
newRow[stageSlugColumnIndex] = stageSlugId
|
|
86
|
+
|
|
87
|
+
return newRow
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private buildEventDataMapping(): TransferTableMapping {
|
|
94
|
+
return {
|
|
95
|
+
name: 'event_data',
|
|
96
|
+
|
|
97
|
+
columns: this.associateByName([
|
|
98
|
+
{ name: 'id', type: Model.ColumnType.Uuid },
|
|
99
|
+
{ name: 'type', type: Model.ColumnType.Enum, values: ['create', 'update', 'delete'] },
|
|
100
|
+
{ name: 'table_name', type: Model.ColumnType.String },
|
|
101
|
+
{ name: 'row_ids', type: Model.ColumnType.Json, schema: Typesafe.array(Typesafe.string) },
|
|
102
|
+
{ name: 'values', type: Model.ColumnType.Json, nullable: true, schema: Typesafe.object({}) },
|
|
103
|
+
{ name: 'created_at', type: Model.ColumnType.DateTime },
|
|
104
|
+
{ name: 'schema_version', type: Model.ColumnType.String },
|
|
105
|
+
{ name: 'identity_id', type: Model.ColumnType.Uuid },
|
|
106
|
+
{ name: 'transaction_id', type: Model.ColumnType.Uuid },
|
|
107
|
+
]),
|
|
108
|
+
|
|
109
|
+
createSelect: (db, table) => {
|
|
110
|
+
const namespaceContext = new Compiler.Context(db.schema, new Set())
|
|
111
|
+
|
|
112
|
+
let builder = db.selectBuilder()
|
|
113
|
+
|
|
114
|
+
for (const column of Object.values(table.columns)) {
|
|
115
|
+
if (column.name === 'schema_version') {
|
|
116
|
+
builder = builder.select(['schema_migration', 'version'], 'schema_version')
|
|
117
|
+
|
|
118
|
+
} else if (column.type === Model.ColumnType.Json || column.type === Model.ColumnType.Date || column.type === Model.ColumnType.DateTime) {
|
|
119
|
+
builder = builder.select(expr => expr.raw(`${wrapIdentifier('event_data')}.${wrapIdentifier(column.name)}::text`))
|
|
120
|
+
|
|
121
|
+
} else {
|
|
122
|
+
builder = builder.select(['event_data', column.name])
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return builder
|
|
127
|
+
.from('event_data')
|
|
128
|
+
.join(
|
|
129
|
+
'schema_migration',
|
|
130
|
+
undefined,
|
|
131
|
+
expr => expr.compareColumns(['schema_migration', 'id'], Operator.eq, ['event_data', 'schema_id']),
|
|
132
|
+
)
|
|
133
|
+
.createQuery(namespaceContext)
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
createInsertStartFragment: (schema, tableName, columnNames) => {
|
|
137
|
+
const columnNames2 = columnNames.map(name => name === 'schema_version' ? 'schema_id' : name)
|
|
138
|
+
const tableQuoted = `${wrapIdentifier(schema)}.${wrapIdentifier(tableName)}`
|
|
139
|
+
const columnsQuoted = '(' + columnNames2.map(it => wrapIdentifier(it)).join(', ') + ')'
|
|
140
|
+
return `INSERT INTO ${tableQuoted} ${columnsQuoted} VALUES\n`
|
|
141
|
+
},
|
|
142
|
+
|
|
143
|
+
createRowParser: async (db, columns, baseType) => {
|
|
144
|
+
const schemaMigrations = await db.selectBuilder<{id: string; version: string}>()
|
|
145
|
+
.select('id')
|
|
146
|
+
.select('version')
|
|
147
|
+
.from('schema_migration')
|
|
148
|
+
.getResult(db)
|
|
149
|
+
|
|
150
|
+
const versionToId = new Map(schemaMigrations.map(row => ([row.version, row.id])))
|
|
151
|
+
const schemaVersionColumnIndex = columns.indexOf('schema_version')
|
|
152
|
+
|
|
153
|
+
if (schemaVersionColumnIndex < 0) {
|
|
154
|
+
return baseType
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return (input, path) => {
|
|
158
|
+
const row = baseType(input, path)
|
|
159
|
+
const schemaVersion = Typesafe.string(row[schemaVersionColumnIndex])
|
|
160
|
+
const schemaVersionId = versionToId.get(schemaVersion)
|
|
161
|
+
|
|
162
|
+
if (schemaVersionId === undefined) {
|
|
163
|
+
throw new ImportError(`Unknown schema version ${schemaVersion}`)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const newRow = [...row]
|
|
167
|
+
newRow[schemaVersionColumnIndex] = schemaVersionId
|
|
168
|
+
|
|
169
|
+
return newRow
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private associateByName<T extends { name: string }>(items: T[]): Record<string, T> {
|
|
176
|
+
return Object.fromEntries(items.map(item => [item.name, item]))
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Model } from '@contember/schema'
|
|
2
|
+
import * as Typesafe from '@contember/typesafe'
|
|
3
|
+
import { Client, Literal } from '@contember/database'
|
|
4
|
+
|
|
5
|
+
type Cell = boolean | number | string | null
|
|
6
|
+
|
|
7
|
+
export type TransferMapping = { tables: TransferTableMappingMap }
|
|
8
|
+
|
|
9
|
+
export type TransferTableMappingMap = Record<string, TransferTableMapping>
|
|
10
|
+
export type TransferTableMapping = {
|
|
11
|
+
name: string
|
|
12
|
+
columns: DbColumnSchemaMap
|
|
13
|
+
|
|
14
|
+
createSelect?: (db: Client, table: TransferTableMapping) => Literal
|
|
15
|
+
createInsertStartFragment?: (schema: string, tableName: string, columnNames: readonly string[]) => string
|
|
16
|
+
createRowParser?: (db: Client, columns: string[], baseType: Typesafe.Type<readonly Cell[]>) => Promise<Typesafe.Type<readonly Cell[]>>
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type DbColumnSchemaMap = Record<string, DbColumnSchema>
|
|
20
|
+
export type DbColumnSchema =
|
|
21
|
+
| { name: string; nullable?: boolean; type: Exclude<Model.ColumnType, Model.ColumnType.Enum | Model.ColumnType.Json | Model.ColumnType.Int> }
|
|
22
|
+
| { name: string; nullable?: boolean; type: Model.ColumnType.Int; sequence?: boolean }
|
|
23
|
+
| { name: string; nullable?: boolean; type: Model.ColumnType.Json; schema?: Typesafe.Type }
|
|
24
|
+
| { name: string; nullable?: boolean; type: Model.ColumnType.Enum; values: readonly string[] }
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './ImportApiMiddlewareFactory'
|
|
2
|
+
export * from './ExportApiMiddlewareFactory'
|
|
3
|
+
|
|
4
|
+
export * from './ImportExecutor'
|
|
5
|
+
export * from './ExportExecutor'
|
|
6
|
+
|
|
7
|
+
export * from './ContentSchemaTransferMappingFactory'
|
|
8
|
+
export * from './SystemSchemaTransferMappingFactory'
|