GithubHelp home page GithubHelp logo

baitcenter / prisma-client-js Goto Github PK

View Code? Open in Web Editor NEW

This project forked from prisma/prisma-client-js

0.0 1.0 0.0 72.22 MB

Type-safe database client for TypeScript & Node.js (ORM replacement)

License: Apache License 2.0

TypeScript 96.76% JavaScript 3.15% Shell 0.09%

prisma-client-js's Introduction


Prisma

Type-safe database client for TypeScript & Node.js (ORM replacement)

Get startedFeaturesDocsAPIWorkflowSupported databases


Prisma Client JS is an auto-generated database client that enables type-safe database access and reduces boilerplate. You can use it as an alternative to traditional ORMs such as Sequelize, TypeORM or Knex.js.

It is part of the Prisma 2 ecosystem. Prisma 2 provides database tools for data access, declarative data modeling, schema migrations and visual data management. Learn more in the Prisma 2 announcement.

Note that Prisma Client JS is currently running in Preview. A productionn-ready release is planned for Q1 2020.


Docs

Getting started

The easiest way to get started with Prisma Client JS is by installing the Prisma 2 CLI and running the init command:

npm install -g prisma2
mkdir my-prisma-project && cd my-prisma-project
prisma2 init

Learn more about the prisma2 init flow here.

Features

  • Auto-generated database client
  • Fully type-safe data access API (even for JavaScript), including:
    • Field selection, lazy/eager loading
    • Fluent API to traverse relations
    • Transactional nested writes and batching API
    • Relation filters (filter on JOINed tables)
    • Powerful methods for filtering, sorting and (cursor) pagination
  • Declarative data modelling and migrations with Prisma Migrate
  • Connection pooling
  • Works with existing databases using schema introspection
  • CLI to support all major workflows
  • Integrates seamlessly in your npm projects (without npm install)

Docs

You can find comprehensive documentation for Prisma Client JS in the Prisma 2 docs.

API examples

Here are few example API calls:

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  await prisma.connect()

  const userById = await prisma.users.findOne({ where: { id: 1 } })
  const userByEmail = await prisma.users.findOne({ where: { email: "[email protected]" }})

  const userWithPosts = await prisma.users.findOne({
    where: { email: "[email protected]" },
    include: { posts: { first: 10 } },
  })

  const newUser = await prisma.users.create({ data: {
    name: "Alice",
    email: "[email protected]",
  }})

  const newUserWithPosts = await prisma.users.create({ data: {
    email: "[email protected]",
    posts: {
      create: [
        { title: "Join us for Prisma Day. June 19, Berlin!" },
        { title: "Follow Prisma on Twitter!" },
      ]
    }
  }})

  const updatedUser = await prisma.users.update({
    where: { email: "[email protected]" },
    data: { role: "ADMIN" },
  })
}

main().catch(e => {
  console.error(e)
}).finally(async () => {
  await prisma.disconnect()
})
Expand to the view the data model based on which the above Prisma Client JS API was generated
datasource ds {
  // some data source config, e.g. SQLite, PostgreSQL, ...
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id         Int       @id @default(autoincrement())
  email      String    @unique
  name       String
  posts      Post[]
}

model Post {
  id          Int       @id  @default(autoincrement())
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt
  draft       Boolean   @default(true)
  author      User
}

Learn more about the data model in the docs.

You can learn more about Prisma Client's API features in the API reference.

The Prisma Client JS workflow

1. Configure data source

Specify the connection details for your database as a data source in your Prisma schema file. The connection details might differ per database, but most commonly you'll provide the following:

  • Host: The IP address or domain name of the machine where your database server is running.
  • Port: The port on which your database server is listening.
  • User & password: Credentials for your database server.

Here is an example schema file that connects to a local PostgreSQL database:

// schema.prisma

datasource postgres {
  url      = "postgresql://user:password@localhost:5432/mydb"
  provider = "postgresql"
}

generator client {
  provider = "prisma-client-js"
}

2. Define initial data model

The data model definition is a declarative and human-readable representation of your database schema. Here is the schema file from above extended with a sample data model:

// schema.prisma

datasource postgres {
  url      = "postgresql://user:password@localhost:5432"
  provider = "postgres"
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  email     String   @unique
  name      String?
  role      Role     @default(USER)
  posts     Post[]
}

model Post {
  id         Int        @id @default(autoincrement())
  createdAt  DateTime   @default(now())
  updatedAt  DateTime   @updatedAt
  title      String
  published  Boolean    @default(false)
  author     User
}

enum Role {
  USER
  ADMIN
}

Read below to learn how you obtain it for your project.

Option A: Starting with an existing database (brownfield)

If you want to use Prisma Client JS with an existing database, you can introspect your database schema using the Prisma 2 CLI. This generates a data model which is the foundation for the generated Prisma Client JS API.

Option B: Start from scratch (greenfield)

When starting from scratch, you can simply write your own data model definition inside your schema file. You can then use Prisma Migrate to migrate your database (Prisma Migrate maps your data model definition to the schema of the underlying database).

3. Generate Prisma Client JS

Generate your version of Prisma Client JS using the Prisma 2 CLI:

prisma2 generate

Prisma Client JS is generated based on the data model definition and provides a type-safe API with the following features:

  • CRUD
  • Filter, sorting and (cursor) pagination
  • Field selection and eager loading
  • Relations and transactions
  • Raw database access

Prisma Client JS gets generated into your node_modules folder so you can import it directly from '@prisma/client'. There's no need to install any additional dependencies or database drivers.

4. Build an app

Similar to traditional ORMs, Prisma Client JS can be used with any of your Node.js or TypeScript applications. For example to implement REST, GraphQL or gRPC APIs. You can find reference examples for these use cases in the prisma-examples repository.

5. Evolve your database and Prisma Client JS

As you build your app, you'll likely migrate your database to implement new features. Depending on how you obtained your initial data model and whether or not you're using Prisma Migrate, there might be two ways for evolving your application going forward.

Option A: Without Prisma Migrate

If you're not using Prisma Migrate, you need to re-introspect your database (to update the generated datamodel) and re-generate Prisma Client JS after each schema migration:

prisma2 introspect
prisma2 generate

Option B: With Prisma Migrate

When using Prisma Migrate, you need to re-generate Prisma Client JS immediately after you performed a schema migration:

# adjust data model definition in schema.prisma
prisma2 migrate save --experimental
prisma2 migrate up --experimental
prisma2 generate

Supported databases

Prisma Client JS can be used with the following databases:

  • SQLite
  • MySQL
  • PostgreSQL
  • MongoDB (coming very soon)

More databases that will be supported in the future are:

  • MS SQL
  • Oracle
  • Neo4J
  • FaunaDB
  • ...

Contributing

Read more about how to contribute to Prisma Client JS here

Build status

prisma-client-js's People

Contributors

0xflotus avatar aliedp avatar colinyoung avatar ctrlplusb avatar deadcoder0904 avatar ejoebstl avatar errorname avatar ghashtag avatar gihrig avatar idkjs avatar janpio avatar jolg42 avatar kripod avatar kuldar avatar leonardopliski avatar matthewmueller avatar mfix22 avatar murajun1978 avatar nikolasburk avatar prisma-bot avatar rafaelkr avatar schickling avatar sdnts avatar steebchen avatar timsuchanek avatar tnunes avatar tomitrescak avatar trufa avatar wardpeet avatar weakky avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.