Skip to content

Commit

Permalink
fix(migrate): replace ink by prompts select
Browse files Browse the repository at this point in the history
  • Loading branch information
Jolg42 committed Jul 3, 2020
1 parent 34d8972 commit 2d6f7d0
Show file tree
Hide file tree
Showing 7 changed files with 129 additions and 247 deletions.
2 changes: 1 addition & 1 deletion src/packages/migrate/src/commands/MigrateDown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export class MigrateDown implements Command {
}
}

await ensureDatabaseExists('unapply', true, undefined, args['--schema'])
await ensureDatabaseExists('unapply', undefined, args['--schema'])

const result = await migrate.down(options)
migrate.stop()
Expand Down
7 changes: 1 addition & 6 deletions src/packages/migrate/src/commands/MigrateSave.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,7 @@ export class MigrateSave implements Command {
}

const preview = args['--preview'] || false
await ensureDatabaseExists(
'create',
true,
args['--create-db'],
args['--schema'],
)
await ensureDatabaseExists('create', args['--create-db'], args['--schema'])

const migrate = new Migrate(args['--schema'])

Expand Down
2 changes: 1 addition & 1 deletion src/packages/migrate/src/commands/MigrateTmpPrepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export class MigrateTmpPrepare implements Command {

const migrate = new Migrate()
debug('initialized migrate')
await ensureDatabaseExists('dev', false, true)
await ensureDatabaseExists('dev', true)

await migrate.up({
short: true,
Expand Down
7 changes: 1 addition & 6 deletions src/packages/migrate/src/commands/MigrateUp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,7 @@ export class MigrateUp implements Command {
}
}

await ensureDatabaseExists(
'apply',
true,
args['--create-db'],
args['--schema'],
)
await ensureDatabaseExists('apply', args['--create-db'], args['--schema'])

const result = await migrate.up(options)
migrate.stop()
Expand Down
125 changes: 125 additions & 0 deletions src/packages/migrate/src/utils/ensureDatabaseExists.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { getSchema, getSchemaDir } from '@prisma/sdk'
import { getConfig } from '@prisma/sdk'
import chalk from 'chalk'
import { createDatabase } from '..'
import { canConnectToDatabase } from '../MigrateEngineCommands'
import { DatabaseCredentials, uriToCredentials } from '@prisma/sdk'
import prompt from 'prompts'

export type MigrateAction = 'create' | 'apply' | 'unapply' | 'dev'

export async function ensureDatabaseExists(
action: MigrateAction,
forceCreate: boolean = false,
schemaPath?: string,
) {
const datamodel = await getSchema(schemaPath)
const config = await getConfig({ datamodel })
const activeDatasource =
config.datasources.length === 1
? config.datasources[0]
: config.datasources.find((d) => d.config.enabled === 'true') ||
config.datasources[0]

if (!activeDatasource) {
throw new Error(`Couldn't find a datasource in the schema.prisma file`)
}

const schemaDir = (await getSchemaDir(schemaPath))!

const canConnect = await canConnectToDatabase(
activeDatasource.url.value,
schemaDir,
)
if (canConnect === true) {
return
}
const { code, message } = canConnect

if (code !== 'P1003') {
throw new Error(`${code}: ${message}`)
}

// last case: status === 'DatabaseDoesNotExist'

if (!schemaDir) {
throw new Error(`Could not locate ${schemaPath || 'schema.prisma'}`)
}
if (forceCreate) {
await createDatabase(activeDatasource.url.value, schemaDir)
} else {
await interactivelyCreateDatabase(
activeDatasource.url.value,
action,
schemaDir,
)
}
}

export async function interactivelyCreateDatabase(
connectionString: string,
action: MigrateAction,
schemaDir: string,
): Promise<void> {
await askToCreateDb(connectionString, action, schemaDir)
}

export async function askToCreateDb(
connectionString: string,
action: MigrateAction,
schemaDir: string,
): Promise<void> {
const credentials = uriToCredentials(connectionString)
const dbName = credentials.database
const dbType =
credentials.type === 'mysql'
? 'MySQL'
: credentials.type === 'postgresql'
? 'PostgreSQL'
: credentials.type === 'sqlite'
? 'Sqlite'
: credentials.type

const schemaWord = 'database'

const message = `You are trying to ${action} a migration for ${dbType} ${schemaWord} ${chalk.bold(
dbName,
)}.\nA ${schemaWord} with that name doesn't exist at ${chalk.bold(
getDbLocation(credentials),
)}\n`

// empty line
console.log()
const response = await prompt({
type: 'select',
name: 'value',
message: message,
initial: 0,
choices: [
{
title: 'Yes',
value: true,
description: `Create new ${dbType} ${schemaWord} ${chalk.bold(dbName)}`,
},
{
title: 'No',
value: false,
description: `Don't create the ${schemaWord}`,
},
],
})

if (response.value) {
await createDatabase(connectionString, schemaDir)
} else {
process.exit(0)
}
}

function getDbLocation(credentials: DatabaseCredentials): string {
if (credentials.type === 'sqlite') {
return credentials.uri!
}

return `${credentials.host}:${credentials.port}`
}

0 comments on commit 2d6f7d0

Please sign in to comment.