How to use @prisma/sdk - 10 common examples

To help you get started, we’ve selected a few @prisma/sdk examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github prisma / prisma2 / cli / introspection / src / introspectionConnector.ts View on Github external
export async function getCredentialsFromExistingDatamodel(): Promise {
  const schemaPath = await getSchemaPath()
  if (schemaPath) {
    const datamodel = readFileSync(schemaPath, 'utf-8')
    const { datasources } = await getConfig({ datamodel })
    // For now just take the first data source
    if (datasources && datasources.length > 1) {
      console.error(
        `There are more than 1 datasources listed in the datamodel ${datasources.map(d => d.name).join(', ')}, taking ${
          datasources[0].name
        }`,
      )
    }
    if (datasources && datasources.length > 0) {
      const uri = datasources[0].url.value
      return uriToCredentials(uri)
    }
  }

  return undefined
}
github prisma / prisma2 / cli / introspection / src / commands / Introspect.ts View on Github external
try {
      const dmmf = await getDMMF({ datamodel: introspectionSchema })

      // add the datasource itself to the schema in case no schema.prisma exists yet
      const datasources: DataSource[] = [
        {
          name: 'db',
          config: {},
          connectorType,
          url: {
            value: url,
            fromEnvVar: null,
          },
        },
      ]
      const schema = await dmmfToDml({
        config: config || {
          datasources,
          generators: [],
        },
        dmmf: dmmf.datamodel,
      })

      log(`Done with introspection in ${chalk.bold(formatms(Date.now() - before))}`)

      if (args['--print']) {
        console.log(schema)
      } else {
        if (schemaPath && fs.existsSync(schemaPath)) {
          const backupPath = path.join(path.dirname(schemaPath), 'schema.backup.prisma')
          fs.renameSync(schemaPath, backupPath)
          log(
github prisma / prisma2 / cli / prisma2 / src / Generate.ts View on Github external
public async parse(argv: string[], minimalOutput = false): Promise {
    const datamodelPath = await getSchemaPath()
    if (!datamodelPath) {
      throw new Error(`Can't find schema.prisma`) // TODO: Add this into a central place in getSchemaPath() as an arg
    }
    const generators = await getGenerators({
      schemaPath: datamodelPath,
      providerAliases: this.aliases,
      printDownloadProgress: true,
      version: pkg.prisma.version,
    })

    if (generators.length === 0) {
      console.log(missingGeneratorMessage)
    }

    // CONTINUE HERE

    for (const generator of generators) {
      const toStr = generator.options!.generator.output! ? chalk.dim(` to ${generator.options!.generator.output}`) : ''
      const name = generator.manifest ? generator.manifest.prettyName : generator.options!.generator.provider
      console.log(`Generating ${chalk.bold(name!)}${toStr}`)
github prisma / prisma2 / cli / introspection / src / commands / Introspect.ts View on Github external
const datasourceString = printDatasources([
      {
        config: {},
        connectorType,
        name: 'db',
        url,
      },
    ])

    introspectionSchema = datasourceString + '\n' + introspectionSchema

    debug('introspectionSchema:')
    debug(introspectionSchema)

    try {
      const dmmf = await getDMMF({ datamodel: introspectionSchema })

      // add the datasource itself to the schema in case no schema.prisma exists yet
      const datasources: DataSource[] = [
        {
          name: 'db',
          config: {},
          connectorType,
          url: {
            value: url,
            fromEnvVar: null,
          },
        },
      ]
      const schema = await dmmfToDml({
        config: config || {
          datasources,
github prisma / lift / src / Lift.ts View on Github external
public async watch(options: WatchOptions = { preview: false, clear: true, providerAliases: {} }): Promise {
    if (!options.clear) {
      options.clear = true
    }

    const datamodel = await this.getDatamodel()

    const generators = await getGenerators({
      schemaPath: getDatamodelPath(this.projectDir),
      printDownloadProgress: false,
      version: packageJson.prisma.version,
      cliVersion: packageJson.version,
    })

    this.studioPort = await getPort({ port: getPort.makeRange(5555, 5600) })

    const datamodelPath = getDatamodelPath(this.projectDir)
    const relativeDatamodelPath = path.relative(process.cwd(), datamodelPath)

    // From here on, we render the dev ui
    const renderer = new DevComponentRenderer({
      port: this.studioPort,
      initialState: {
        studioPort: this.studioPort,
github prisma / lift / src / utils / ensureDatabaseExists.tsx View on Github external
const CreateDatabaseDialog: React.FC = ({ connectionString, action, onDone, schemaDir }) => {
  const [creating, setCreating] = useState(false)
  async function onSelect(shouldCreate: boolean) {
    if (shouldCreate) {
      setCreating(true)
      await createDatabase(connectionString, schemaDir)
      setCreating(false)
      onDone()
    } else {
      process.exit(0)
    }
  }
  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'

  return (
    
      
        {action === 'dev' ? (
github prisma / prisma2 / cli / introspection / src / prompt / screens / Step61Success.tsx View on Github external
const { stopEngine } = useConnector()
  useEffect(() => {
    stopEngine()
    setTimeout(() => {
      process.exit(0)
    }, 5)
  })
  const [state] = useInitState()
  const directoryCreated = state.outputDir !== process.cwd()
  const dirName = directoryCreated ? path.relative(process.cwd(), state.outputDir) : null
  const issuesLink =
    (state.selectedExample && state.selectedExample!.issuesLink) || 'https://github.com/prisma/prisma2/issues/new'

  const connectionString =
    state.dbCredentials &&
    (state.dbCredentials.host || state.dbCredentials.uri || credentialsToUri(state.dbCredentials))

  return (
    
      
        {directoryCreated && (
          
            
               SUCCESS 
            {' '}
            The {dirName} directory was created!
          
        )}
        
          
            
               SUCCESS
github prisma / prisma2 / cli / introspection / src / prompt / utils / replaceDatasource.ts View on Github external
export async function replaceGenerator(datamodel: string, generator: GeneratorConfig): Promise {
  const [dmmf, config] = await Promise.all([getDMMF({ datamodel }), getConfig({ datamodel })])

  config.generators = [generator]

  return dmmfToDml({
    config,
    dmmf: dmmf.datamodel,
  })
}
github prisma / prisma2 / cli / introspection / src / prompt / utils / replaceDatasource.ts View on Github external
export async function replaceDatasource(datamodel: string, datasource: DataSource): Promise {
  const [dmmf, config] = await Promise.all([getDMMF({ datamodel }), getConfig({ datamodel })])

  config.datasources = [datasource]

  return dmmfToDml({
    config,
    dmmf: dmmf.datamodel,
  })
}
github prisma / lift / src / utils / ensureDatabaseExists.tsx View on Github external
export async function ensureDatabaseExists(action: LiftAction, killInk: boolean, forceCreate: boolean = false) {
  const datamodel = await getSchema()
  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 canConnect = await canConnectToDatabase(activeDatasource.url.value)
  if (canConnect === true) {
    return
  }
  const { code, message } = canConnect

  if (code !== 'P1003') {