@contember/engine-http 1.2.0-alpha.2 → 1.2.0-alpha.5
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/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/content/ContentApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/src/content/ContentApiMiddlewareFactory.js +13 -9
- 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 +3 -2
- package/dist/src/content/ProjectMembershipFetcher.d.ts.map +1 -1
- package/dist/src/content/ProjectMembershipFetcher.js.map +1 -1
- package/dist/src/content/ProjectMembershipResolver.d.ts +4 -3
- package/dist/src/content/ProjectMembershipResolver.d.ts.map +1 -1
- package/dist/src/content/ProjectMembershipResolver.js +23 -6
- package/dist/src/content/ProjectMembershipResolver.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/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.js +20 -6
- package/dist/tests/cases/unit/projectMembershipResolver.test.js.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/package.json +14 -15
- package/src/common/TimerMiddleware.ts +30 -9
- package/src/content/ContentApiMiddlewareFactory.ts +2 -1
- 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 +3 -2
- package/src/content/ProjectMembershipResolver.ts +36 -12
- package/src/index.ts +1 -0
- package/src/koa/types.ts +1 -1
- 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 +23 -10
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { asyncIterableTransaction, Client, Compiler, Connection, wrapIdentifier } from '@contember/database'
|
|
2
|
+
import { Command } from './Command'
|
|
3
|
+
import { TransferMapping, TransferTableMapping } from './TransferMapping'
|
|
4
|
+
import { Model } from '@contember/schema'
|
|
5
|
+
import { ContentSchemaTransferMappingFactory } from './ContentSchemaTransferMappingFactory'
|
|
6
|
+
import { SystemSchemaTransferMappingFactory } from './SystemSchemaTransferMappingFactory'
|
|
7
|
+
import * as Typesafe from '@contember/typesafe'
|
|
8
|
+
import { StagesQuery } from '@contember/engine-system-api'
|
|
9
|
+
import { ProjectContainer } from '../ProjectContainer'
|
|
10
|
+
|
|
11
|
+
export type ExportRequest = ReturnType<typeof ExportRequest>
|
|
12
|
+
export const ExportRequest = Typesafe.object({
|
|
13
|
+
// tenant: Typesafe.boolean,
|
|
14
|
+
projects: Typesafe.array(Typesafe.object({
|
|
15
|
+
slug: Typesafe.string,
|
|
16
|
+
system: Typesafe.boolean,
|
|
17
|
+
})),
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
export class ExportExecutor {
|
|
21
|
+
constructor(
|
|
22
|
+
private readonly contentSchemaTransferMappingFactory: ContentSchemaTransferMappingFactory,
|
|
23
|
+
private readonly systemSchemaTransferMappingFactory: SystemSchemaTransferMappingFactory,
|
|
24
|
+
) {
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async* export(request: ExportRequest, projectContainers: Record<string, ProjectContainer>): AsyncIterable<Command> {
|
|
28
|
+
for (const project of request.projects) {
|
|
29
|
+
const projectContainer = projectContainers[project.slug]
|
|
30
|
+
const systemContext = projectContainer.systemDatabaseContextFactory.create()
|
|
31
|
+
|
|
32
|
+
if (project.system) {
|
|
33
|
+
const systemMapping = this.systemSchemaTransferMappingFactory.build()
|
|
34
|
+
yield ['importSystemSchemaBegin', { project: project.slug, tables: Object.keys(systemMapping.tables) }]
|
|
35
|
+
yield* this.exportSchema(systemContext.client, systemMapping)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
for (const stage of await systemContext.queryHandler.fetch(new StagesQuery())) {
|
|
39
|
+
const contentSchema = await projectContainer.contentSchemaResolver.getSchema(systemContext, stage.slug)
|
|
40
|
+
const contentMapping = this.contentSchemaTransferMappingFactory.createContentSchemaMapping(contentSchema)
|
|
41
|
+
const contentDatabaseClient = projectContainer.connection.createClient(stage.schema, {})
|
|
42
|
+
|
|
43
|
+
yield [
|
|
44
|
+
'importContentSchemaBegin', {
|
|
45
|
+
project: project.slug,
|
|
46
|
+
stage: stage.slug,
|
|
47
|
+
schemaVersion: contentSchema.version,
|
|
48
|
+
tables: Object.keys(contentMapping.tables),
|
|
49
|
+
},
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
yield* this.exportSchema(contentDatabaseClient, contentMapping)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private async* exportSchema(db: Client, mapping: TransferMapping): AsyncIterable<Command> {
|
|
58
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
59
|
+
const that = this
|
|
60
|
+
yield* asyncIterableTransaction(db, async function* (db) {
|
|
61
|
+
await db.query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE')
|
|
62
|
+
for (const table of Object.values(mapping.tables)) {
|
|
63
|
+
yield* that.exportSequences(db, table)
|
|
64
|
+
yield* that.exportTable(db, table)
|
|
65
|
+
}
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private async* exportSequences(db: Client<Connection.TransactionLike>, table: TransferTableMapping): AsyncIterable<Command> {
|
|
70
|
+
for (const column of Object.values(table.columns)) {
|
|
71
|
+
if (column.type === Model.ColumnType.Int && column.sequence) {
|
|
72
|
+
const seqResult = await db.query<{ nextval: number }>(
|
|
73
|
+
'SELECT nextval(pg_get_serial_sequence(?, ?))',
|
|
74
|
+
[table.name, column.name],
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
const seqValue = seqResult.rows[0].nextval
|
|
78
|
+
yield ['importSequence', { table: table.name, column: column.name, value: seqValue }]
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private async* exportTable(db: Client<Connection.TransactionLike>, table: TransferTableMapping): AsyncIterable<Command> {
|
|
84
|
+
const DB_FETCH_BATCH_SIZE = 100
|
|
85
|
+
const query = (table.createSelect ?? this.buildQuery)(db, table)
|
|
86
|
+
let empty = true
|
|
87
|
+
|
|
88
|
+
for await (const row of this.cursorQuery(db, DB_FETCH_BATCH_SIZE, query.sql, query.parameters)) {
|
|
89
|
+
if (empty) {
|
|
90
|
+
yield ['insertBegin', { table: table.name, columns: Object.keys(table.columns) }]
|
|
91
|
+
empty = false
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
yield ['insertRow', Object.values(row)]
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (!empty) {
|
|
98
|
+
yield ['insertEnd']
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private buildQuery(db: Client<Connection.TransactionLike>, table: TransferTableMapping) {
|
|
103
|
+
let builder = db.selectBuilder().from(table.name)
|
|
104
|
+
|
|
105
|
+
for (const column of Object.values(table.columns)) {
|
|
106
|
+
if (column.type === Model.ColumnType.Json || column.type === Model.ColumnType.Date || column.type === Model.ColumnType.DateTime) {
|
|
107
|
+
builder = builder.select(expr => expr.raw(`${wrapIdentifier(column.name)}::text`))
|
|
108
|
+
|
|
109
|
+
} else {
|
|
110
|
+
builder = builder.select(column.name)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const namespaceContext = new Compiler.Context(db.schema, new Set())
|
|
115
|
+
return builder.createQuery(namespaceContext)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private async* cursorQuery(db: Client<Connection.TransactionLike>, batchSize: number, sql: string, parameters: readonly any[] = []) {
|
|
119
|
+
await db.query(`DECLARE contember_cursor NO SCROLL CURSOR FOR ${sql}`, parameters)
|
|
120
|
+
|
|
121
|
+
const fetchSql = `FETCH ${Number(batchSize)} FROM contember_cursor`
|
|
122
|
+
let resultPromise: Promise<Connection.Result> | null = db.query(fetchSql)
|
|
123
|
+
|
|
124
|
+
while (resultPromise !== null) {
|
|
125
|
+
const result: Connection.Result = await resultPromise
|
|
126
|
+
resultPromise = result.rowCount < batchSize ? null : db.query(fetchSql) // pipeline
|
|
127
|
+
yield* result.rows
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
await db.query(`CLOSE contember_cursor`)
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { KoaMiddleware, KoaRequestState } from '../koa'
|
|
2
|
+
import { AuthResult, HttpError, TimerMiddlewareState } from '../common'
|
|
3
|
+
import { ProjectGroupResolver, ProjectInfoMiddlewareState } from '../project-common'
|
|
4
|
+
import { TenantRole } from '@contember/engine-tenant-api'
|
|
5
|
+
import { fromBuffer, toBuffer } from './CommandStream'
|
|
6
|
+
import { ImportExecutor } from './ImportExecutor'
|
|
7
|
+
import { createGunzip } from 'zlib'
|
|
8
|
+
import { Readable } from 'stream'
|
|
9
|
+
|
|
10
|
+
type ImportApiMiddlewareState =
|
|
11
|
+
& TimerMiddlewareState
|
|
12
|
+
& KoaRequestState
|
|
13
|
+
& ProjectInfoMiddlewareState
|
|
14
|
+
& { authResult: AuthResult }
|
|
15
|
+
|
|
16
|
+
export class ImportApiMiddlewareFactory {
|
|
17
|
+
constructor(
|
|
18
|
+
private readonly projectGroupResolver: ProjectGroupResolver,
|
|
19
|
+
private readonly importExecutor: ImportExecutor,
|
|
20
|
+
) {
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
create(): KoaMiddleware<ImportApiMiddlewareState> {
|
|
24
|
+
return async koaContext => {
|
|
25
|
+
const { request, response, state: { timer } } = koaContext
|
|
26
|
+
|
|
27
|
+
const groupContainer = await this.projectGroupResolver.resolveContainer({ request })
|
|
28
|
+
koaContext.state.projectGroup = groupContainer.slug
|
|
29
|
+
|
|
30
|
+
const authResult = await groupContainer.authenticator.authenticate({ request, timer })
|
|
31
|
+
koaContext.state.authResult = authResult
|
|
32
|
+
|
|
33
|
+
if (request.headers['content-type'] !== 'application/x-ndjson') {
|
|
34
|
+
throw new HttpError(`Unsupported content type`, 400)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (request.headers['content-encoding'] !== undefined && request.headers['content-encoding'] !== 'gzip') {
|
|
38
|
+
throw new HttpError(`Unsupported content encoding`, 415)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const isGzip = request.headers['content-encoding'] === 'gzip'
|
|
42
|
+
const commands = fromBuffer(isGzip ? request.req.pipe(createGunzip()) : request.req)
|
|
43
|
+
|
|
44
|
+
response.status = 200
|
|
45
|
+
response.headers['Content-Type'] = 'application/x-ndjson'
|
|
46
|
+
response.body = Readable.from(toBuffer(this.importExecutor.import(groupContainer, authResult, commands), 0))
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -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
|
+
}
|