Giter VIP home page Giter VIP logo

docs's Introduction

Prisma Documentation

PRs Welcome Discord

This repository contains the source code and the content for the Prisma documentation.

Contributing to the docs

New contributors are welcome! Read through the contributing guide to learn how you can contribute to the Prisma documentation.

Run the docs site locally

  1. Clone this repository.
  2. On your computer, open a terminal window in the repository's directory.
  3. Run the following commands:
cd docs
npm install
npm run start

Be sure to also test building the static site:

npm run clean && npm run build
npm run serve

To prettify or format the code, run:

npm run format

Visit http://localhost:3000 to view the app.

Configure

Write MDX files in content folder.

Most frontmatter for the docs are the same as Docusaurus Frontmatter. There are some differences due to legacy frontmatter which are handled here.

When possible, avoid using custom frontmatter fields and use the default ones available via Docusaurus.

Inserting, moving and deleting files

All files/folders in the context are prefixed with a position which indicates the order in which they appear in the sidenav on the docs website. This makes it cumbersome to insert, move and delete files because the positions of a number of other files (if not all) in the same folder might need to be adjusted. Thanks to Luca Steeb, you can perform these operations with a dedicated CLI called mdtool.

Install

First, install wget:

brew install wget

Then use wget to install mdtool:

wget https://gist.githubusercontent.com/steebchen/bd085ebde1fcf4242e3fdd0df4d202a6/raw/c04e3d262eb6a302a9fab98f6428fec9329681e2/mdtool -qO /usr/local/bin/mdtool
chmod +x /usr/local/bin/mdtool

Usage

Overview

mdtool insert 3
mdtool swap A B
mdtool move A B
mdtool remove 4

mdtool insert

Make place for a new file at given index and increment all numbers by one after that index:

$ mdtool insert INDEX

# e.g.:
$ mdtool insert 2

# Result: for files 01-a, 02-b, 03-c, and 04-d; 03-c is renamed to 04-c and 04-d is renamed to 05-d so you can create a new file at index 2

mdtool swap

Swap two files; specify both filenames (prefix numbers get automatically adjusted):

$ mdtool swap FILENAME1 FILENAME2

# e.g.:
$ mdtool swap 03-file1.mdx 07-file2.mdx

# Result: Files are now named: 03-file2.mdx 07-file1.mdx

mdtool move

Move a given file to another given index

$ mdtool move FILENAME INDEX

# e.g.:
$ mdtool move 05-file.mdx 2

# Result: 05-file.mdx is move to 02-file.mdx, plus previous files 02-*, 03-*, 04-* are incremented

mdtool remove

Shift all other items by -1 at a given index:

$ mdtool remove INDEX

# e.g.:
$ mdtool remove 2

# Result: 01-a, 02-b, 03-c, 04-d becomes 01-a, 02-b, 02-c, 03-d; 02-b is supposed to be manually deleted

Thanks Luca

docs's People

Contributors

2color avatar andrew-walford-prisma avatar ankur-arch avatar carlagn avatar chaficnajjar avatar dependabot[bot] avatar hrescak avatar janpio avatar jharrell avatar jolg42 avatar keerlu avatar matthewmueller avatar meletj avatar mhessdev avatar mhwelander avatar molebox avatar nikolasburk avatar nilubava avatar nurul3101 avatar olliechick avatar rahul3v avatar renovate-bot avatar renovate[bot] avatar ruheni avatar ryands17 avatar sabinadams avatar tanberry avatar tasinishmam avatar thebiglabasky avatar zachtil avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

docs's Issues

Document how to locally install the databases we support

Why?

You should be using the same database for development as in production. Sometimes this is not feasible, but for the databases we currently support, it's fortunately very easy to setup. We just need to guide our users how.

For example

Database Mac Windows Linux
Postgres brew install postgres todo todo
MySQL brew install mysql todo todo

Additional Notes

  • We may need to provide instructions on how to install brew or some installable .dmg if available
  • I think we should also optionally provide a way to run these database as a service so they bootup on start. In homebrew that's easy brew services start postgres.

Boilerplate for using Prisma Client JS with Scripts

In order for scripts to disconnect the Photon client, some boilerplate is needed. This should be documented.

import { Photon } from '@generated/photon'

const photon = new Photon()

async function main() {
  const result = await photon.flats.findMany()
  console.log(result)
}

main()
  .catch(e => console.log(e))
  .finally(() => photon.disconnect())

Documentation for Introspection Warnings

prisma introspect recently added Introspection Warning messages to communicate to the user about guardrails that were applied during Introspection. This currently looks like this:

image

We want to document these individually and offer workarounds.
Additionally the error messages itself should be improved and link to the matching documentation.

PRs:

Rendering of Markdown quotes

Is this the expected rendering for Markdown quotes?

image

This is the corresponding Markdown:

> **Note**: The content on this page is focused on **relational databases**.

Selectively add drop-shadow to images

image

Daniel Norman  12:18 PM
Btw, quick tip on window screenshots: disable shadow. Gatsby image processing makes them look really bad
https://www.macobserver.com/tmo/article/how-to-disable-screenshot-shadows-in-yosemite-and-mavericks (edited) 
macobserver.commacobserver.com
How To Disable Screenshot Shadows in Yosemite and Mavericks – The Mac Observer
Today's tip comes from Charles Edge, author and long time Mac admin. If you're looking to forsake the drop shadows in screen shots, you can do so with a simple Terminal command. Kelly breaks it all down for you.

nikolas:expressionless:  12:21 PM
Hmm do you know if that can be fixed on the Gatsby-side? I think having this is actually quite nice but I agree that the current rendering is rather off-putting :thinking_face:

Daniel Norman  12:31 PM
Gatsby’s image optimiser could probably be configured. We can address that at some point
:+1:

Add pagination section to API docs

What

In a similar fashion to how we have a Filtering section, we should add a section on pagination.

Why

  • The API has changed for before and after which now accept *WhereUniqueInput, e.g. UserWhereUniqueInput instead of a string.
  • It can be used to enable pagination based on arbitrary uniques.

Example

Before:

const paginatedPosts3 = await prisma.post.findMany({
  first: 5,
  after: 43834,
})

After:

const paginatedPosts3 = await prisma.post.findMany({
  first: 5,
  after: { id: 43834},
})

Docs for CI/CD workflows

This issues persists a docs requests from Slack:

In Prisma 1 there is not a lot of information about deployment. Specifically for creating a CI/CD workflow. For instance creating a staging and production environments and rolling out incremental updates. I would love to see more information around production best practices with Prisma 2. As well as more options/info about deployments.

Initial Mobile implementation

It always surprises me how many mobile users you get on a launch. Right now we don't do a good job handling them.

image (13)

For now, we can just use a scaled down version of the website. You probably just need to add:

<meta name="viewport" content="width=device-width, initial-scale=1" />

New line in blockquote doesn't work

This text should be rendered with a new line:

> **Note**: In SQL, relations between models are represented via _foreign keys_ in the underlying database. A foreign key is only stored on _one_ side of a relation. As opposed to how relations are modeled in SQL, **Prisma always requires explicit relation fields on _both_ sides of the relation to be set on your Prisma models**.
> 
> This means that one side of the relation represents the _foreign key_ in the underlying database, the other relation field is provided on a Prisma-level (in the case of implicit many-to-many relations, both relation fields are provided on a Prisma-level).

Like so:

Note: In SQL, relations between models are represented via foreign keys in the underlying database. A foreign key is only stored on one side of a relation. As opposed to how relations are modeled in SQL, Prisma always requires explicit relation fields on both sides of the relation to be set on your Prisma models.

This means that one side of the relation represents the foreign key in the underlying database, the other relation field is provided on a Prisma-level (in the case of implicit many-to-many relations, both relation fields are provided on a Prisma-level).

In the doccs it currently gets rendered as:

image

Unclear where to call prisma.disconnect()

I read this section on managing connections in your docs and I found it a bit confusing.

To start, the important note is not very clear… I don’t understand what the scenario is in which the Prisma Client doesn‘t do the right thing. A better explanation and a code snippet showing the problem would be really helpful.

Additionally, the important note simultaneously says that the Prisma Client should just do the right thing but also says that sometimes it won’t. I think it should be one or the other. If the client can be made such that it always does the right thing, then great! If not, don’t even mention it, just clearly explain what someone has to do to protect themselves.

Which leads into the last problem… which is that I don’t know where to call prisma.disconnect(). Right now I’m just peppering disconnects after every query—that’s clearly not right.

I’m using Express, so… would the generally correct thing be to use a middleware to disconnect at the end of the request/response cycle?

import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()

express.use(function(req, res, next) {
  res.on("finish", () => prisma.disconnect())

  next()
})

I took a look at the Prisma Client repo but because of the way it’s built I can’t tell if when I instantiate a new PrismaClient is it returning the same instance (a singleton) or am I getting a new instance? Rather, it’s unclear if calling prisma.disconnect() in this way would actually disconnect all connections, or just the connections that were specifically started with this instance of the client.

We should highlight that using prisma.raw() with parameters is not secure and recommend using prisma.raw``

Problem

Users are using prisma.raw() like

const data = await prisma.raw(
  `SELECT * FROM "ProviderItemAttribute" WHERE "provider_item" = ${root.id} AND "user" = ${auth.user.id} limit 1;`,
);

This example is using prisma.raw() the pure text version so there is no security around parameters.

Only raw`` is secure because it's using https://github.com/blakeembrey/sql-template-tag

Solution

In this case it would be recommended to do

const data = await prisma.raw`
	SELECT * FROM "ProviderItemAttribute" WHERE "provider_item" = ${root.id} AND "user" = ${auth.user.id} limit 1;
`;

This should be highlighted in the docs (and examples?)
We also can think about how to warn users that are using prisma.raw() or even disable it under a flag?

Note prisma.raw`` parameters do not work as of today with PostgreSQL see prisma/prisma-client-js#595

Document binary ENV vars

PRISMA_MIGRATION_ENGINE_BINARY 		// migration-engine
PRISMA_QUERY_ENGINE_BINARY 			// query-engine
PRISMA_INTROSPECTION_ENGINE_BINARY	// introspection-engine

In previous docs these were only documented in context of the generator:
https://github.com/prisma/prisma2/blob/7b254e8e90ec45370de41b5551cc401a710cbd2f/docs/core/generators/prisma-client-js.md#generator-options

Issues like prisma/prisma#1333 show that this is also considered in other contexts like when the automated download of the binaries is not possible (for whatever reason).

In the meantime 1 new var appeared for the prisma-fmt (format):

PRISMA_FMT_BINARY					// prisma-fmt

Redirect from docs.prisma.io to prisma.io/docs/

It's a pretty common "convention" (?) to have this subdomain work, I found myself typing it in multiple times.

I'm also not sure if this is the right place to create the issue, so please move / close if it isn't~

Documentation needed for modelling and querying complex Ternary relations.

Problem

I can not find any documentation for working with ternary relations.
As such, I'm not sure if and how they are supported. The documentation only seems to show very simple queries.

This is a basic task in SQL where many ORM's fall flat which leads developers like myself to keep reaching for SQL.

From your own marketing:
"For database access, developers can use traditional ORMs (e.g. Sequelize for Node.js or GORM for Go). While often beneficial to get a project off the ground, these aren't a good longterm fit as project complexity quickly outgrows the capabilities of traditional ORMs."

But there is no information about how Prisma can actually succeed where other ORM's fail.

A common example is group permissions for users as demonstrated by the following table structures:

Untitled Diagram

There are two common views that people would want for such data. I have given each view for the first and second schema respectively:

User view:

users =  [
{
    user_id: 2;
    groups: [
        {
            group_id: 4;
            permissions: {
                permission_id: 2;
            };
        },
    ];
}
]

users = [
{
    user_id: 2;
    groups: [
        {
            group_id: 4;
            permissions: [
                {
                    permission_id: 2;
                },
            ];
        },
    ];
}
]

Group view:

groups = [
{
    group_id: 2;
    users: [
        {
            user_id: 4;
            permissions: {
                permission_id: 2;
            };
        },
    ];
}
]

groups = [
{
    group_id: 2;
    users: [
        {
            user_id: 4;
            permissions: [
                {
                    permission_id: 2;
                },
            ];
        },
    ];
}
]

As well as viewing this data, it is also important that we can filter and sort by it as we could in SQL. For instance, one may which to answer the following query: 'Find all the groups where user A has permissions B'.

Finally, these relationships should be able to be derived using introspection (assuming that they have foreign key relationships).

Solution

Prisma should clearly state in the documentation (with examples) how introspection and queries work with ternary and other complex relationships. Showing how Prisma can elegantly overcome this issue is important for proving that it worthy of use in production applications and different from "traditional ORMs".

Strategy to avoid duplication in version controlling migrations

Hi. In the microservices setup I have, so far, I have been having the migrations generated and kept along with my service code. But, to have better separation of concerns and have a proper CI/CD pipeline, I want to separate out the service as well as the database migrations to 2 repos.

The only problem I have is that, both the service and the database uses schema.prisma file. Service for running prisma2 generate and DB for running prisma2 migrate and thus, if I change the schema.prisma file, I have to change in 2 places leading to duplication and possible mistakes.

Is there any way to avoid this or any better strategy to separate it? With service in 1 repo and migrations in another repo with their own CI/CD pipelines.

Docs for library authors

Library authors sometimes need access to lower-level functionality of Prisma Client that's not available via the "official" Prisma Client API.

Often this involves access to the private dmmf property of Prisma Client. When documenting this, we have to make sure that it's clear that this is an "unofficial API" that might break in any release and should therefore be used with great care.

Able to connect to multiple records during `create()`?

Documentation only ever shows ability to connect to a single record during create(), e.g.

// Create a new user
const newUser = await photon.users.create({
  data: {
    name: 'Alice',
    email: '[email protected]',
    posts: {
      connect: {
        title: 'hello world'
      }
    }
  },
})

Is it possible to connect a new author to several posts all at once?

Document binary/engines APIs

Prisma internally uses binaries for the query, migration and (soon) introspection engines. Those are used by photon and lift just fine, but it would still be good to have their "external" API documented so this information is made more explicit.

This can either happen in a spec or simple READMEs in the prisma-engine repository next to the code (I prefer the README, as this really is just documentation of an implementation detail. In specs I would expect a more generalized "list of functionality" or similar).

Foreign Key fields in database don't show up on Type

[email protected], binary version: 1b0c271f14ca00606f56c93717e228fe48c5603c
MacOS 10.13.6

Here's my schema.prisma file:

generator photon {
  provider = "photonjs"
}

datasource db {
  provider = "sqlite"
  url      = "file:dev.db"
}

model User {
  id    String  @default(cuid()) @id
  email String  @unique
  name  String?
  post  Post
}

model Post {
  id        String   @default(cuid()) @id
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  published Boolean
  title     String
  content   String?
  author    User?
}

Which generates the following type in index.d.ts:

export declare type User = {
    id: string;
    email: string;
    name: string | null;
};

Despite there being a post field in the database, it doesn't exist in the generated type.

Document how to delete all records from all tables

Sometimes it's helpful to wipe all data records in the DB but keep the tables. This is currently not possible via the Prisma Client API so we should document a workaround.

One potential approach which currently doesn't work because it relies on a private property of PrismaClient is this:

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

function lowerCase(name: string): string {
  return name.substring(0, 1).toLowerCase() + name.substring(1)
}

const promises = prisma.dmmf.datamodel.models.map(model => {
  return new Promise(async resolve => {
    const modelName = lowerCase(model.name)
    const modelMethods = prisma[modelName]

    if (modelMethods) {
      try {
        resolve(await modelMethods.findMany({}))
      } catch (e) {
        resolve(e)
      }
    }
  }

async function main() {                    
  await Promise.all(promises)
}

main()

Alternatively, the following approach (by @nnennajohn) which is based on knex.js can be used:

import camelCase from 'lodash/camelCase';
import { prisma } from '@cpath/universal/shared/db';
import knexClient from './knex';
// Contents of the knexClient import above
// import Knex from 'knex';
// const knexClient: Knex = Knex({
//   client: 'pg',
//   connection: {
//     user: process.env.POSTGRES_USER,
//     password: process.env.POSTGRES_PASSWORD,
//     host: process.env.POSTGRES_HOST,
//     port: Number(process.env.POSTGRES_PORT),
//     database: process.env.POSTGRES_DB,
//   },
// });
// Contents of the prisma import above
// export const prisma = new PrismaClient();
function deleteRecords(tablesList) {
  const validTables = tablesList.filter((tableName) => tableName[0] !== '_');
  console.log('These are the valid tables', validTables);
  const recordsDeletions = validTables.map((table) => {
    return prisma[camelCase(table)].deleteMany({});
  });
  return Promise.all(recordsDeletions);
}
function listTables() {
  const query =
    'SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_catalog = ?';
  const bindings = [knexClient.client.database()];
  return knexClient.raw(query, bindings).then((results) => {
    return results.rows.map((row) => row.table_name);
  });
}
async function main() {
  const tablesList = await listTables();
  console.log('This is the list of knex tables', tablesList);
  if (tablesList && tablesList.length) {
    deleteRecords(tablesList)
      .then((res) => {
        console.log('Successfully deleted table records', res);
      })
      .catch((err) => {
        console.log('Error deleting table records', err);
      });
  }
}
main()
  .catch((e) => console.error(e))
  .finally();

We should also document a workaround that allows to do this without an external dependency like knex.js.

Docker on Monorepo

Hello, I'm working on a monorepo with yarn workspaces and I would like to use Docker for alternate with dev and prod mode and it feels a little bit complicated.

image

This is the architecture of the project. And I was telling me that it would be great to have an example to make this working because a lot of people could be interested.

Thanks

Generator: `output` is relative to `./prisma`

If you have a generator in your schema.prisma like this:

generator testutils {
  provider = "./node_modules/prisma-test-utils/dist/generator.js"
  output = "./node_modules/@generated/prisma-test-utils"
}

The output is actually generated in ./prisma/node_modules/@generated/prisma-test-utils:

✔ Generated Prisma Test Utils to .\prisma\node_modules\@generated\prisma-test-utils in 3.95s

That was unexpected to me.

Changing output to use ../node_modules... fixes the problem.

(Could potentially also be the fault of the generator I am trying to use.)

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.