Skip to content
This repository has been archived by the owner on Sep 2, 2022. It is now read-only.

Commit

Permalink
Merge branch 'alpha' into beta
Browse files Browse the repository at this point in the history
  • Loading branch information
mavilein committed Mar 5, 2019
2 parents 93b5af5 + e541203 commit 574c453
Show file tree
Hide file tree
Showing 114 changed files with 7,025 additions and 1,643 deletions.
4 changes: 4 additions & 0 deletions cli/packages/prisma-cli-core/src/commands/delete/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ export default class Delete extends Command {
description: 'Path to .env file to inject env vars',
char: 'e',
}),
['project']: flags.string({
description: 'Path to Prisma definition file',
char: 'p',
}),
}
async run() {
const { force } = this.flags
Expand Down
4 changes: 4 additions & 0 deletions cli/packages/prisma-cli-core/src/commands/deploy/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ ${chalk.gray(
description: 'Path to .env file to inject env vars',
char: 'e',
}),
['project']: flags.string({
description: 'Path to Prisma definition file',
char: 'p',
}),
}
private deploying: boolean = false
private showedHooks: boolean = false
Expand Down
4 changes: 4 additions & 0 deletions cli/packages/prisma-cli-core/src/commands/export/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ export default class Export extends Command {
description: 'Path to .env file to inject env vars',
char: 'e',
}),
['project']: flags.string({
description: 'Path to Prisma definition file',
char: 'p',
}),
}
async run() {
let exportPath =
Expand Down
17 changes: 13 additions & 4 deletions cli/packages/prisma-cli-core/src/commands/generate/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ export default class GenereateCommand extends Command {
description: 'Path to .env file to inject env vars',
char: 'e',
}),
['project']: flags.string({
description: 'Path to Prisma definition file',
char: 'p',
}),
['endpoint']: flags.boolean({
description:
'Use a specific endpoint for schema generation or pick endpoint from prisma.yml',
Expand Down Expand Up @@ -99,11 +103,16 @@ export default class GenereateCommand extends Command {
const resolvedOutput = output.startsWith('/')
? output
: path.join(this.config.definitionDir, output)

fs.mkdirpSync(resolvedOutput)


if (generator === 'graphql-schema') {
if (!resolvedOutput.endsWith('.graphql')) {
throw new Error(`Error: ${chalk.bold('output')} for generator ${chalk.bold('graphql-schema')} should be a ${chalk.green(chalk.bold('.graphql'))}-file. Please change the ${chalk.bold('output')} property for this generator in ${chalk.green(chalk.bold('prisma.yml'))}`)
}

fs.mkdirpSync(path.resolve(resolvedOutput, '../'))
await this.generateSchema(resolvedOutput, schemaString)
} else {
fs.mkdirpSync(resolvedOutput)
}

const isMongo =
Expand Down Expand Up @@ -158,7 +167,7 @@ export default class GenereateCommand extends Command {
}

async generateSchema(output: string, schemaString: string) {
fs.writeFileSync(path.join(output, 'prisma.graphql'), schemaString)
fs.writeFileSync(output, schemaString)

this.out.log(`Saving Prisma GraphQL schema (SDL) at ${output}`)
}
Expand Down
4 changes: 4 additions & 0 deletions cli/packages/prisma-cli-core/src/commands/import/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ export default class Import extends Command {
description: 'Path to .env file to inject env vars',
char: 'e',
}),
['project']: flags.string({
description: 'Path to Prisma definition file',
char: 'p',
}),
}
async run() {
const { data } = this.flags
Expand Down
4 changes: 4 additions & 0 deletions cli/packages/prisma-cli-core/src/commands/info/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export default class InfoCommand extends Command {
description: 'Path to .env file to inject env vars',
char: 'e',
}),
['project']: flags.string({
description: 'Path to Prisma definition file',
char: 'p',
}),
}
async run() {
const { json, secret } = this.flags
Expand Down
49 changes: 38 additions & 11 deletions cli/packages/prisma-cli-core/src/commands/introspect/introspect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import {
ConnectorData,
getConnectorWithDatabase,
IntermediateConnectorData,
populateMongoDatabase,
sanitizeMongoUri,
} from './util'

export default class IntrospectCommand extends Command {
Expand All @@ -26,6 +28,16 @@ export default class IntrospectCommand extends Command {
char: 'i',
description: 'Interactive mode',
}),

['env-file']: flags.string({
description: 'Path to .env file to inject env vars',
char: 'e',
}),
['project']: flags.string({
description: 'Path to Prisma definition file',
char: 'p',
}),

/**
* Postgres Params
*/
Expand Down Expand Up @@ -164,7 +176,7 @@ ${chalk.bold(
const introspection = await connector.introspect(databaseName)
const sdl = existingDatamodel
? await introspection.getNormalizedDatamodel(existingDatamodel)
: await introspection.getDatamodel()
: await introspection.getNormalizedDatamodel()

const renderer = DefaultRenderer.create(
introspection.databaseType,
Expand Down Expand Up @@ -244,7 +256,12 @@ ${chalk.bold(

async getConnector(): Promise<IntermediateConnectorData> {
const hasExecuteRaw = await this.hasExecuteRaw()
const credentials = await this.getCredentials(hasExecuteRaw)
let credentials = this.getCredentialsByFlags()
let interactive = false
if (!credentials) {
credentials = await this.getCredentialsInteractively(hasExecuteRaw)
interactive = true
}
if (credentials) {
const {
connector,
Expand All @@ -255,6 +272,7 @@ ${chalk.bold(
disconnect,
databaseType: credentials.type,
databaseName: credentials.schema,
interactive,
}
}

Expand Down Expand Up @@ -282,12 +300,11 @@ ${chalk.bold(
disconnect,
databaseType: client.databaseType,
databaseName,
interactive: false,
}
}

async getCredentials(
hasExecuteRaw: boolean,
): Promise<DatabaseCredentials | null> {
getCredentialsByFlags(): DatabaseCredentials | null {
const requiredPostgresFlags = ['pg-host', 'pg-user', 'pg-password', 'pg-db']
const requiredMysqlFlags = ['mysql-host', 'mysql-user', 'mysql-password']

Expand Down Expand Up @@ -321,7 +338,7 @@ ${chalk.bold(

if (mysqlFlags.length >= requiredMysqlFlags.length) {
return {
host: flags['myqsl-host'],
host: flags['mysql-host'],
port: parseInt(flags['mysql-port'], 10),
user: flags['mysql-user'],
password: flags['mysql-password'],
Expand All @@ -335,22 +352,31 @@ ${chalk.bold(
host: flags['pg-host'],
user: flags['pg-user'],
password: flags['pg-password'],
database: flags['pg-database'],
database: flags['pg-db'],
port: parseInt(flags['pg-port'], 10),
schema: flags['pg-schema'], // this is optional and can be undefined
type: DatabaseType.postgres,
}
}

if (flags['mongo-uri']) {
const uri = flags['mongo-uri']
const database = flags['mongo-db'] // this is optional and can be undefined
const credentials = populateMongoDatabase({ uri, database })
return {
uri: flags['mongo-uri'],
schema: flags['mongo-db'], // this is optional and can be undefined
uri: sanitizeMongoUri(credentials.uri),
schema: credentials.database,
type: DatabaseType.mongo,
}
}

if (flags.interactive || !hasExecuteRaw) {
return null
}

async getCredentialsInteractively(
hasExecuteRaw: boolean,
): Promise<DatabaseCredentials | null> {
if (this.flags.interactive || !hasExecuteRaw) {
const endpointDialog = new EndpointDialog({
out: this.out,
client: this.client,
Expand All @@ -359,11 +385,12 @@ ${chalk.bold(
definition: this.definition,
shouldAskForGenerator: false,
})
return await endpointDialog.getDatabase(true)
return endpointDialog.getDatabase(true)
}

return null
}

handleMissingArgs(
requiredArgs: string[],
providedArgs: string[],
Expand Down
73 changes: 73 additions & 0 deletions cli/packages/prisma-cli-core/src/commands/introspect/util.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { sanitizeMongoUri, populateMongoDatabase } from './util'

test('sanitizeMongoUri', () => {
expect(sanitizeMongoUri('mongodb://localhost')).toBe(
'mongodb://localhost/admin',
)
expect(sanitizeMongoUri('mongodb://localhost/')).toBe(
'mongodb://localhost/admin',
)
expect(sanitizeMongoUri('mongodb://localhost:27017')).toBe(
'mongodb://localhost:27017/admin',
)
expect(sanitizeMongoUri('mongodb://localhost:27017/')).toBe(
'mongodb://localhost:27017/admin',
)
expect(sanitizeMongoUri('mongodb://localhost:27017/prisma')).toBe(
'mongodb://localhost:27017/prisma',
)
expect(
sanitizeMongoUri(
'mongodb+srv://prisma:[email protected]/test?retryWrites=true',
),
).toBe(
'mongodb+srv://prisma:[email protected]/test?retryWrites=true',
)
})

test('populateMongoDatabase', () => {
expect(populateMongoDatabase({ uri: 'mongodb://localhost:27017/prisma' }))
.toMatchInlineSnapshot(`
Object {
"database": "prisma",
"uri": "mongodb://localhost:27017/prisma",
}
`)
expect(
populateMongoDatabase({
uri: 'mongodb://localhost:27017/prisma',
database: 'another-db',
}),
).toMatchInlineSnapshot(`
Object {
"database": "another-db",
"uri": "mongodb://localhost:27017/prisma",
}
`)
expect(
populateMongoDatabase({
uri: 'mongodb://localhost:27017/prisma?authSource=admin',
}),
).toMatchInlineSnapshot(`
Object {
"database": "prisma",
"uri": "mongodb://localhost:27017/prisma?authSource=admin",
}
`)
expect(
populateMongoDatabase({
uri: 'mongodb://localhost:27017/',
database: 'database',
}),
).toMatchInlineSnapshot(`
Object {
"database": "database",
"uri": "mongodb://localhost:27017/",
}
`)
expect(() =>
populateMongoDatabase({
uri: 'mongodb://localhost:27017/',
}),
).toThrow()
})
52 changes: 51 additions & 1 deletion cli/packages/prisma-cli-core/src/commands/introspect/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { omit } from 'lodash'
import { Connectors } from 'prisma-db-introspection'
import { DatabaseType } from 'prisma-datamodel'
import { IConnector } from 'prisma-db-introspection/dist/common/connector'
import { URL } from 'url'

function replaceLocalDockerHost(credentials: DatabaseCredentials) {
if (credentials.host) {
Expand Down Expand Up @@ -53,6 +54,7 @@ export interface ConnectorData extends ConnectorAndDisconnect {
export interface IntermediateConnectorData extends ConnectorAndDisconnect {
databaseType: DatabaseType
databaseName?: string
interactive: boolean
}

export async function getConnectedConnectorFromCredentials(
Expand Down Expand Up @@ -88,7 +90,13 @@ export async function getConnectorWithDatabase(
connectorData: IntermediateConnectorData,
endpointDialog: EndpointDialog,
): Promise<ConnectorData> {
const { connector, disconnect, databaseType, ...result } = connectorData
const {
connector,
disconnect,
databaseType,
interactive,
...result
} = connectorData
let { databaseName } = result

let schemas: string[]
Expand All @@ -98,9 +106,14 @@ export async function getConnectorWithDatabase(
throw new Error(`Could not connect to database. ${e.message}`)
}

if (!databaseName && !interactive) {
throw new Error(`Please provide a database name`)
}

if (databaseName && !schemas.includes(databaseName)) {
const schemaWord =
databaseType === DatabaseType.postgres ? 'schema' : 'database'

throw new Error(
`The provided ${schemaWord} "${databaseName}" does not exist. The following are available: ${schemas.join(
', ',
Expand Down Expand Up @@ -171,3 +184,40 @@ function getConnectedMongoClient(
)
})
}

export function sanitizeMongoUri(mongoUri: string) {
const url = new URL(mongoUri)
if (url.pathname === '/' || url.pathname.length === 0) {
url.pathname = 'admin'
}

return url.toString()
}

export function populateMongoDatabase({
uri,
database,
}: {
uri: string
database?: string
}): { uri: string; database: string } {
const url = new URL(uri)
if ((url.pathname === '/' || url.pathname.length === 0) && !database) {
throw new Error(
`Please provide a Mongo database in your connection string.\nRead more here https://docs.mongodb.com/manual/reference/connection-string/`,
)
}

if (!database) {
database = url.pathname.slice(1)
}

return {
uri,
database,
}
}

export function hasAuthSource(uri: string): boolean {
return new URL(uri).searchParams.has('authSource')
}
4 changes: 4 additions & 0 deletions cli/packages/prisma-cli-core/src/commands/playground/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export default class Playground extends Command {
description: 'Path to .env file to inject env vars',
char: 'e',
}),
['project']: flags.string({
description: 'Path to Prisma definition file',
char: 'p',
}),
'server-only': flags.boolean({
char: 's',
description: 'Run only the server',
Expand Down
Loading

0 comments on commit 574c453

Please sign in to comment.