From 3edb5f339d3fdd5d045def5a08086f934bc03e35 Mon Sep 17 00:00:00 2001 From: carlagn Date: Mon, 1 Apr 2024 14:41:32 +0100 Subject: [PATCH] Docusaurus: Feat/da 139 finish tech switcher (#5762) * add more techswitcher pages * add mongodb switcher * fix: Continuing ui fixes (#5757) * update box for subsections update search page colors * update carets * update spacing between icons * update in this section * update hide toc * fix kappa icon * update font size * Docusaurus: more random things (#5759) * Add back prism.css file. Resolves DA-147 * fix some broken tables * make baseUrl /docs * remove docusaurus template stuff. Resolves DA-148 * update sidenavs + use _category_.json + move custom props to frontMatter. Resolves DA-151 * add techswithcer pages * update index for relational databases * update start-from-scratch/mongodb * finish all techswitchers * fix image path for tech switcher * update space taker for no toc --------- Co-authored-by: Jon Harrell <4829245+jharrell@users.noreply.github.com> --- ...-relational-databases-node-cockroachdb.mdx | 63 + .../110-relational-databases-node-mysql.mdx | 87 ++ ...-relational-databases-node-planetscale.mdx | 79 + ...0-relational-databases-node-postgresql.mdx | 86 ++ ...10-relational-databases-node-sqlserver.mdx | 89 ++ ...ional-databases-typescript-cockroachdb.mdx | 91 ++ ...-relational-databases-typescript-mysql.mdx | 92 ++ ...ional-databases-typescript-planetscale.mdx | 98 ++ ...tional-databases-typescript-postgresql.mdx | 91 ++ ...ational-databases-typescript-sqlserver.mdx | 94 ++ ...connect-your-database-node-cockroachdb.mdx | 2 +- ...t-your-database-typescript-cockroachdb.mdx | 2 +- ...-using-prisma-migrate-node-cockroachdb.mdx | 87 ++ .../150-using-prisma-migrate-node-mysql.mdx | 86 ++ ...-using-prisma-migrate-node-planetscale.mdx | 84 ++ ...0-using-prisma-migrate-node-postgresql.mdx | 87 ++ ...50-using-prisma-migrate-node-sqlserver.mdx | 85 ++ ...-prisma-migrate-typescript-cockroachdb.mdx | 87 ++ ...-using-prisma-migrate-typescript-mysql.mdx | 85 ++ ...-prisma-migrate-typescript-planetscale.mdx | 84 ++ ...g-prisma-migrate-typescript-postgresql.mdx | 86 ++ ...ng-prisma-migrate-typescript-sqlserver.mdx | 85 ++ .../150-using-prisma-migrate.mdx | 845 ----------- ...install-prisma-client-node-cockroachdb.mdx | 52 + .../200-install-prisma-client-node-mysql.mdx | 52 + ...install-prisma-client-node-planetscale.mdx | 53 + ...-install-prisma-client-node-postgresql.mdx | 53 + ...0-install-prisma-client-node-sqlserver.mdx | 53 + ...l-prisma-client-typescript-cockroachdb.mdx | 53 + ...install-prisma-client-typescript-mysql.mdx | 53 + ...l-prisma-client-typescript-planetscale.mdx | 53 + ...ll-prisma-client-typescript-postgresql.mdx | 52 + ...all-prisma-client-typescript-sqlserver.mdx | 53 + .../200-install-prisma-client.mdx | 282 ---- ...querying-the-database-node-cockroachdb.mdx | 224 +++ .../250-querying-the-database-node-mysql.mdx | 220 +++ ...querying-the-database-node-planetscale.mdx | 226 +++ ...-querying-the-database-node-postgresql.mdx | 226 +++ ...0-querying-the-database-node-sqlserver.mdx | 225 +++ ...g-the-database-typescript-cockroachdb.mdx} | 357 +---- ...querying-the-database-typescript-mysql.mdx | 241 +++ ...ng-the-database-typescript-planetscale.mdx | 264 ++++ ...ing-the-database-typescript-postgresql.mdx | 240 +++ ...ying-the-database-typescript-sqlserver.mdx | 264 ++++ .../110-relational-databases/index.mdx | 300 ---- .../120-mongodb-node-mongodb.mdx | 86 ++ ...mdx => 120-mongodb-typescript-mongodb.mdx} | 45 +- ...100-connect-your-database-node-mongodb.mdx | 71 + ...nect-your-database-typescript-mongodb.mdx} | 37 +- ...reating-the-prisma-schema-node-mongodb.mdx | 93 ++ ...-the-prisma-schema-typescript-mongodb.mdx} | 37 +- ...200-install-prisma-client-node-mongodb.mdx | 52 + ...tall-prisma-client-typescript-mongodb.mdx} | 37 +- ...250-querying-the-database-node-mongodb.mdx | 232 +++ ...rying-the-database-typescript-mongodb.mdx} | 187 +-- ...-relational-databases-node-cockroachdb.mdx | 89 ++ .../110-relational-databases-node-mysql.mdx | 90 ++ ...-relational-databases-node-planetscale.mdx | 88 ++ ...0-relational-databases-node-postgresql.mdx | 89 ++ ...10-relational-databases-node-sqlserver.mdx | 83 + ...ional-databases-typescript-cockroachdb.mdx | 90 ++ ...-relational-databases-typescript-mysql.mdx | 88 ++ ...ional-databases-typescript-planetscale.mdx | 88 ++ ...tional-databases-typescript-postgresql.mdx | 88 ++ ...ational-databases-typescript-sqlserver.mdx | 89 ++ ...connect-your-database-node-cockroachdb.mdx | 93 ++ .../100-connect-your-database-node-mysql.mdx | 88 ++ ...connect-your-database-node-planetscale.mdx | 118 ++ ...-connect-your-database-node-postgresql.mdx | 81 + ...0-connect-your-database-node-sqlserver.mdx | 59 + ...t-your-database-typescript-cockroachdb.mdx | 92 ++ ...connect-your-database-typescript-mysql.mdx | 94 ++ ...t-your-database-typescript-planetscale.mdx | 118 ++ ...ct-your-database-typescript-postgresql.mdx | 80 + ...ect-your-database-typescript-sqlserver.mdx | 60 + .../100-connect-your-database.mdx | 520 ------- .../150-introspection-node-cockroachdb.mdx | 240 +++ .../150-introspection-node-mysql.mdx | 242 +++ .../150-introspection-node-planetscale.mdx | 258 ++++ .../150-introspection-node-postgresql.mdx | 239 +++ .../150-introspection-node-sqlserver.mdx | 246 +++ ...0-introspection-typescript-cockroachdb.mdx | 239 +++ .../150-introspection-typescript-mysql.mdx | 242 +++ ...0-introspection-typescript-planetscale.mdx | 258 ++++ ...50-introspection-typescript-postgresql.mdx | 238 +++ ...150-introspection-typescript-sqlserver.mdx | 246 +++ .../150-introspection.mdx | 1329 ----------------- ...aseline-your-database-node-cockroachdb.mdx | 110 ++ .../170-baseline-your-database-node-mysql.mdx | 126 ++ ...baseline-your-database-node-postgresql.mdx | 129 ++ ...-baseline-your-database-node-sqlserver.mdx | 118 ++ ...e-your-database-typescript-cockroachdb.mdx | 99 ++ ...aseline-your-database-typescript-mysql.mdx | 127 ++ ...ne-your-database-typescript-postgresql.mdx | 128 ++ ...ine-your-database-typescript-sqlserver.mdx | 118 ++ .../170-baseline-your-database.mdx | 421 ------ ...install-prisma-client-node-cockroachdb.mdx | 62 + .../200-install-prisma-client-node-mysql.mdx | 62 + ...install-prisma-client-node-planetscale.mdx | 62 + ...-install-prisma-client-node-postgresql.mdx | 62 + ...0-install-prisma-client-node-sqlserver.mdx | 62 + ...l-prisma-client-typescript-cockroachdb.mdx | 62 + ...install-prisma-client-typescript-mysql.mdx | 62 + ...l-prisma-client-typescript-planetscale.mdx | 62 + ...ll-prisma-client-typescript-postgresql.mdx | 61 + ...all-prisma-client-typescript-sqlserver.mdx | 62 + .../200-install-prisma-client.mdx | 290 ---- ...querying-the-database-node-cockroachdb.mdx | 148 ++ .../250-querying-the-database-node-mysql.mdx | 150 ++ ...querying-the-database-node-planetscale.mdx | 162 ++ ...-querying-the-database-node-postgresql.mdx | 149 ++ ...0-querying-the-database-node-sqlserver.mdx | 157 ++ ...ng-the-database-typescript-cockroachdb.mdx | 163 ++ ...querying-the-database-typescript-mysql.mdx | 163 ++ ...ng-the-database-typescript-planetscale.mdx | 164 ++ ...ing-the-database-typescript-postgresql.mdx | 162 ++ ...ying-the-database-typescript-sqlserver.mdx | 163 ++ .../250-querying-the-database.mdx | 641 -------- ...75-evolve-your-schema-node-cockroachdb.mdx | 128 ++ .../275-evolve-your-schema-node-mysql.mdx | 125 ++ ...275-evolve-your-schema-node-postgresql.mdx | 130 ++ .../275-evolve-your-schema-node-sqlserver.mdx | 130 ++ ...lve-your-schema-typescript-cockroachdb.mdx | 130 ++ ...75-evolve-your-schema-typescript-mysql.mdx | 130 ++ ...olve-your-schema-typescript-postgresql.mdx | 131 ++ ...volve-your-schema-typescript-sqlserver.mdx | 130 ++ .../275-evolve-your-schema.mdx | 402 ----- .../300-next-steps.mdx | 2 - .../110-relational-databases/index.mdx | 276 ---- .../120-mongodb-node-mongodb.mdx | 86 ++ ...mdx => 120-mongodb-typescript-mongodb.mdx} | 28 +- ...100-connect-your-database-node-mongodb.mdx | 73 + ...nect-your-database-typescript-mongodb.mdx} | 39 +- .../125-introspection-node-mongodb.mdx | 153 ++ ... 125-introspection-typescript-mongodb.mdx} | 37 +- ...200-install-prisma-client-node-mongodb.mdx | 53 + ...tall-prisma-client-typescript-mongodb.mdx} | 37 +- ...250-querying-the-database-node-mongodb.mdx | 237 +++ ...rying-the-database-typescript-mongodb.mdx} | 188 +-- .../200-prisma-client/450-testing/index.mdx | 1 + .../02-schema-incompatibilities-mysql.mdx | 767 ++++++++++ ...2-schema-incompatibilities-postgresql.mdx} | 104 +- .../03-upgrading-the-prisma-layer-mysql.mdx | 1315 ++++++++++++++++ ...upgrading-the-prisma-layer-postgresql.mdx} | 309 +--- docs/index.mdx | 10 + docusaurus.config.ts | 2 +- sidebars.ts | 373 ++++- src/components/shortcodes/switcherBlock.tsx | 11 +- src/components/shortcodes/techSwitcher.tsx | 30 +- src/css/custom.css | 4 +- src/theme/DocSidebarItem/Link/index.tsx | 28 +- 151 files changed, 16508 insertions(+), 6708 deletions(-) create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-sqlserver.mdx delete mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx delete mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-sqlserver.mdx rename docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/{250-querying-the-database.mdx => 250-querying-the-database-typescript-cockroachdb.mdx} (55%) create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx delete mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/index.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-node-mongodb.mdx rename docs/100-getting-started/02-setup-prisma/100-start-from-scratch/{120-mongodb/index.mdx => 120-mongodb-typescript-mongodb.mdx} (80%) create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-node-mongodb.mdx rename docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/{100-connect-your-database.mdx => 100-connect-your-database-typescript-mongodb.mdx} (81%) create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-node-mongodb.mdx rename docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/{125-creating-the-prisma-schema.mdx => 125-creating-the-prisma-schema-typescript-mongodb.mdx} (80%) create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-node-mongodb.mdx rename docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/{200-install-prisma-client.mdx => 200-install-prisma-client-typescript-mongodb.mdx} (70%) create mode 100644 docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-node-mongodb.mdx rename docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/{250-querying-the-database.mdx => 250-querying-the-database-typescript-mongodb.mdx} (68%) create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-sqlserver.mdx delete mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-sqlserver.mdx delete mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-sqlserver.mdx delete mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx delete mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx delete mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-sqlserver.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-cockroachdb.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-mysql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-postgresql.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-sqlserver.mdx delete mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema.mdx delete mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/index.mdx create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx rename docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/{120-mongodb/index.mdx => 120-mongodb-typescript-mongodb.mdx} (89%) create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-node-mongodb.mdx rename docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/{100-connect-your-database.mdx => 100-connect-your-database-typescript-mongodb.mdx} (81%) create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-node-mongodb.mdx rename docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/{125-introspection.mdx => 125-introspection-typescript-mongodb.mdx} (88%) create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-node-mongodb.mdx rename docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/{200-install-prisma-client.mdx => 200-install-prisma-client-typescript-mongodb.mdx} (72%) create mode 100644 docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-node-mongodb.mdx rename docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/{250-querying-the-database.mdx => 250-querying-the-database-typescript-mongodb.mdx} (71%) create mode 100644 docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/02-schema-incompatibilities-mysql.mdx rename docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/{02-schema-incompatibilities.mdx => 02-schema-incompatibilities-postgresql.mdx} (89%) create mode 100644 docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer-mysql.mdx rename docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/{03-upgrading-the-prisma-layer.mdx => 03-upgrading-the-prisma-layer-postgresql.mdx} (82%) create mode 100644 docs/index.mdx diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-cockroachdb.mdx new file mode 100644 index 0000000000..9fd1567094 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-cockroachdb.mdx @@ -0,0 +1,63 @@ +--- +title: 'Relational databases' +metaTitle: 'Start from scratch with relational databases (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [CockroachDB](https://www.cockroachlabs.com/) database server running + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Create project setup + +As a first step, create a project directory and navigate into it: + +```terminal copy +mkdir hello-prisma +cd hello-prisma +``` + +Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma --save-dev +``` + +This creates a `package.json` with an initial setup for a Node.js app. + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-mysql.mdx new file mode 100644 index 0000000000..93fe032b5b --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-mysql.mdx @@ -0,0 +1,87 @@ +--- +title: 'Relational databases' +metaTitle: 'Start from scratch with relational databases (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [MySQL](https://www.mysql.com/) database server running + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Create project setup + +As a first step, create a project directory and navigate into it: + +```terminal copy +mkdir hello-prisma +cd hello-prisma +``` + +Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma --save-dev +``` + +This creates a `package.json` with an initial setup for a Node.js app. + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. + + + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-planetscale.mdx new file mode 100644 index 0000000000..5feae9a54c --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-planetscale.mdx @@ -0,0 +1,79 @@ +--- +title: 'Relational databases' +metaTitle: 'Start from scratch with relational databases (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [PlanetScale](https://www.planetscale.com/) database server running + + + +This tutorial will also assume that you can push to the `main` branch of your database. Do not do this if your `main` branch has been promoted to production. + + + +Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma --save-dev +``` + +This creates a `package.json` with an initial setup for a Node.js app. + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. + + + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-postgresql.mdx new file mode 100644 index 0000000000..96dfc41be9 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-postgresql.mdx @@ -0,0 +1,86 @@ +--- +title: 'Relational databases' +metaTitle: 'Start from scratch with relational databases (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [PostgreSQL](https://www.postgresql.org/) database server running + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Create project setup + +As a first step, create a project directory and navigate into it: + +```terminal copy +mkdir hello-prisma +cd hello-prisma +``` + +Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma --save-dev +``` + +This creates a `package.json` with an initial setup for a Node.js app. + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. + + + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-sqlserver.mdx new file mode 100644 index 0000000000..a876febb18 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-sqlserver.mdx @@ -0,0 +1,89 @@ +--- +title: 'Relational databases' +metaTitle: 'Start from scratch with relational databases (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- A [Microsoft SQL Server](https://docs.microsoft.com/en-us/sql/?view=sql-server-ver15) database + - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) + - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) + + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Create project setup + +As a first step, create a project directory and navigate into it: + +```terminal copy +mkdir hello-prisma +cd hello-prisma +``` + +Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma --save-dev +``` + +This creates a `package.json` with an initial setup for a Node.js app. + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. + + + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-cockroachdb.mdx new file mode 100644 index 0000000000..d76043c7c6 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-cockroachdb.mdx @@ -0,0 +1,91 @@ +--- +title: 'Relational databases' +metaTitle: 'Start from scratch with relational databases (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [CockroachDB](https://www.cockroachlabs.com/) database server running + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Create project setup + +As a first step, create a project directory and navigate into it: + +```terminal copy +mkdir hello-prisma +cd hello-prisma +``` + +Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma typescript ts-node @types/node --save-dev +``` + +This creates a `package.json` with an initial setup for your TypeScript app. + +Next, initialize TypeScript: + +```terminal copy +npx tsc --init +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. + + + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-mysql.mdx new file mode 100644 index 0000000000..b97506b3c0 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-mysql.mdx @@ -0,0 +1,92 @@ +--- +title: 'Relational databases' +metaTitle: 'Start from scratch with relational databases (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [MySQL](https://www.mysql.com/) database server running + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Create project setup + +As a first step, create a project directory and navigate into it: + +```terminal copy +mkdir hello-prisma +cd hello-prisma +``` + +Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma typescript ts-node @types/node --save-dev +``` + +This creates a `package.json` with an initial setup for your TypeScript app. + +Next, initialize TypeScript: + +```terminal copy +npx tsc --init +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. + + + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-planetscale.mdx new file mode 100644 index 0000000000..78fecdc4e8 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-planetscale.mdx @@ -0,0 +1,98 @@ +--- +title: 'Relational databases' +metaTitle: 'Start from scratch with relational databases (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [PlanetScale](https://www.planetscale.com/) database server running + + + +This tutorial will also assume that you can push to the `main` branch of your database. Do not do this if your `main` branch has been promoted to production. + + + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Create project setup + +As a first step, create a project directory and navigate into it: + +```terminal copy +mkdir hello-prisma +cd hello-prisma +``` + +Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma typescript ts-node @types/node --save-dev +``` + +This creates a `package.json` with an initial setup for your TypeScript app. + +Next, initialize TypeScript: + +```terminal copy +npx tsc --init +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. + + + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-postgresql.mdx new file mode 100644 index 0000000000..a28820e5b1 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-postgresql.mdx @@ -0,0 +1,91 @@ +--- +title: 'Relational databases' +metaTitle: 'Start from scratch with relational databases (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [PostgreSQL](https://www.postgresql.org/) database server running + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Create project setup + +As a first step, create a project directory and navigate into it: + +```terminal copy +mkdir hello-prisma +cd hello-prisma +``` + +Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma typescript ts-node @types/node --save-dev +``` + +This creates a `package.json` with an initial setup for your TypeScript app. + +Next, initialize TypeScript: + +```terminal copy +npx tsc --init +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. + + + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-sqlserver.mdx new file mode 100644 index 0000000000..ad8013e4d1 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-sqlserver.mdx @@ -0,0 +1,94 @@ +--- +title: 'Relational databases' +metaTitle: 'Start from scratch with relational databases (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- A [Microsoft SQL Server](https://docs.microsoft.com/en-us/sql/?view=sql-server-ver15) database + - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) + - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Create project setup + +As a first step, create a project directory and navigate into it: + +```terminal copy +mkdir hello-prisma +cd hello-prisma +``` + +Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma typescript ts-node @types/node --save-dev +``` + +This creates a `package.json` with an initial setup for your TypeScript app. + +Next, initialize TypeScript: + +```terminal copy +npx tsc --init +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. + + + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx index 65c26ddd2e..1244478034 100644 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx @@ -4,8 +4,8 @@ metaTitle: 'Connect your database' metaDescription: 'Connect your database to your project' langSwitcher: ['typescript', 'node'] dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar hide_table_of_contents: true +sidebar_class_name: hidden-sidebar --- diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx index 6c7fa80769..c903f90245 100644 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx @@ -4,7 +4,7 @@ metaTitle: 'Connect your database' metaDescription: 'Connect your database to your project' langSwitcher: ['typescript', 'node'] dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar +sidebar_class_name: 'hidden-sidebar tech-switch' hide_table_of_contents: true --- diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-cockroachdb.mdx new file mode 100644 index 0000000000..d5711a0872 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-cockroachdb.mdx @@ -0,0 +1,87 @@ +--- +title: 'Using Prisma Migrate' +metaTitle: 'Using Prisma Migrate' +metaDescription: 'Create database tables with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Creating the database schema + +In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: + +```prisma file=prisma/schema.prisma copy +model Post { + id BigInt @id @default(sequence()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId BigInt +} + +model Profile { + id BigInt @id @default(sequence()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId BigInt @unique +} + +model User { + id BigInt @id @default(sequence()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: + +```terminal +npx prisma migrate dev --name init +``` + +This command does two things: + +1. It creates a new SQL migration file for this migration +1. It runs the SQL migration file against the database + +:::note +`generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. +::: + +Great, you now created three tables in your database with Prisma Migrate 🚀 + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-mysql.mdx new file mode 100644 index 0000000000..0588233863 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-mysql.mdx @@ -0,0 +1,86 @@ +--- +title: 'Using Prisma Migrate' +metaTitle: 'Using Prisma Migrate' +metaDescription: 'Create database tables with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Creating the database schema + + +In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: + +```prisma file=prisma/schema.prisma copy +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: + +```terminal +npx prisma migrate dev --name init +``` + +This command does two things: + +1. It creates a new SQL migration file for this migration +1. It runs the SQL migration file against the database + +> **Note**: `generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. + +Great, you now created three tables in your database with Prisma Migrate 🚀 + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-planetscale.mdx new file mode 100644 index 0000000000..3bd03d0134 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-planetscale.mdx @@ -0,0 +1,84 @@ +--- +title: 'Using Prisma Migrate' +metaTitle: 'Using Prisma Migrate' +metaDescription: 'Create database tables with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Creating the database schema + +In this guide, you'll use Prisma's [`db push` command](/orm/prisma-migrate/workflows/prototyping-your-schema) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: + +```prisma file=prisma/schema.prisma copy +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int + + @@index(authorId) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique + + @@index(userId) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +You are now ready to push your new schema to your database. Connect to your `main` branch using the instructions in [Connect your database](/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale). + +Now use the `db push` CLI command to push to the `main` branch: + +```terminal +npx prisma db push +``` + +Great, you now created three tables in your database with Prisma's `db push` command 🚀 + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-postgresql.mdx new file mode 100644 index 0000000000..56f99eea11 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-postgresql.mdx @@ -0,0 +1,87 @@ +--- +title: 'Using Prisma Migrate' +metaTitle: 'Using Prisma Migrate' +metaDescription: 'Create database tables with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Creating the database schema + +In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following data model to your [Prisma schema](/orm/prisma-schema) in `prisma/schema.prisma`: + +```prisma file=prisma/schema.prisma +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: + +```terminal +npx prisma migrate dev --name init +``` + +This command does two things: + +1. It creates a new SQL migration file for this migration +1. It runs the SQL migration file against the database + +:::note +`generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. +::: + +Great, you now created three tables in your database with Prisma Migrate 🚀 + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-sqlserver.mdx new file mode 100644 index 0000000000..bc1d17b459 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-sqlserver.mdx @@ -0,0 +1,85 @@ +--- +title: 'Using Prisma Migrate' +metaTitle: 'Using Prisma Migrate' +metaDescription: 'Create database tables with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Creating the database schema + +In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: + +```prisma file=prisma/schema.prisma copy +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: + +```terminal +npx prisma migrate dev --name init +``` + +This command does two things: + +1. It creates a new SQL migration file for this migration +1. It runs the SQL migration file against the database + +> **Note**: `generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. + +Great, you now created three tables in your database with Prisma Migrate 🚀 + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-cockroachdb.mdx new file mode 100644 index 0000000000..8c5ae07948 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-cockroachdb.mdx @@ -0,0 +1,87 @@ +--- +title: 'Using Prisma Migrate' +metaTitle: 'Using Prisma Migrate' +metaDescription: 'Create database tables with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Creating the database schema + +In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: + +```prisma file=prisma/schema.prisma copy +model Post { + id BigInt @id @default(sequence()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId BigInt +} + +model Profile { + id BigInt @id @default(sequence()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId BigInt @unique +} + +model User { + id BigInt @id @default(sequence()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: + +```terminal +npx prisma migrate dev --name init +``` + +This command does two things: + +1. It creates a new SQL migration file for this migration +1. It runs the SQL migration file against the database + +:::note +`generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. +::: + +Great, you now created three tables in your database with Prisma Migrate 🚀 + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-mysql.mdx new file mode 100644 index 0000000000..9548227fd6 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-mysql.mdx @@ -0,0 +1,85 @@ +--- +title: 'Using Prisma Migrate' +metaTitle: 'Using Prisma Migrate' +metaDescription: 'Create database tables with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Creating the database schema + +In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: + +```prisma file=prisma/schema.prisma copy +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: + +```terminal +npx prisma migrate dev --name init +``` + +This command does two things: + +1. It creates a new SQL migration file for this migration +1. It runs the SQL migration file against the database + +> **Note**: `generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. + +Great, you now created three tables in your database with Prisma Migrate 🚀 + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-planetscale.mdx new file mode 100644 index 0000000000..a08eb11ed0 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-planetscale.mdx @@ -0,0 +1,84 @@ +--- +title: 'Using Prisma Migrate' +metaTitle: 'Using Prisma Migrate' +metaDescription: 'Create database tables with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Creating the database schema + +In this guide, you'll use Prisma's [`db push` command](/orm/prisma-migrate/workflows/prototyping-your-schema) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: + +```prisma file=prisma/schema.prisma copy +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int + + @@index(authorId) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique + + @@index(userId) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +You are now ready to push your new schema to your database. Connect to your `main` branch using the instructions in [Connect your database](/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale). + +Now use the `db push` CLI command to push to the `main` branch: + +```terminal +npx prisma db push +``` + +Great, you now created three tables in your database with Prisma's `db push` command 🚀 + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-postgresql.mdx new file mode 100644 index 0000000000..376f749e00 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-postgresql.mdx @@ -0,0 +1,86 @@ +--- +title: 'Using Prisma Migrate' +metaTitle: 'Using Prisma Migrate' +metaDescription: 'Create database tables with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Creating the database schema + +In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following data model to your [Prisma schema](/orm/prisma-schema) in `prisma/schema.prisma`: + +```prisma file=prisma/schema.prisma +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: + +```terminal +npx prisma migrate dev --name init +``` + +This command does two things: + +1. It creates a new SQL migration file for this migration +1. It runs the SQL migration file against the database + +:::note +`generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. +::: + +Great, you now created three tables in your database with Prisma Migrate 🚀 + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-sqlserver.mdx new file mode 100644 index 0000000000..4a13065e29 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-sqlserver.mdx @@ -0,0 +1,85 @@ +--- +title: 'Using Prisma Migrate' +metaTitle: 'Using Prisma Migrate' +metaDescription: 'Create database tables with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Creating the database schema + +In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: + +```prisma file=prisma/schema.prisma copy +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: + +```terminal +npx prisma migrate dev --name init +``` + +This command does two things: + +1. It creates a new SQL migration file for this migration +1. It runs the SQL migration file against the database + +> **Note**: `generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. + +Great, you now created three tables in your database with Prisma Migrate 🚀 + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate.mdx deleted file mode 100644 index 76c32c8128..0000000000 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate.mdx +++ /dev/null @@ -1,845 +0,0 @@ ---- -title: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate' -metaDescription: 'Create database tables with Prisma Migrate' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true ---- - -## Creating the database schema - - - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following data model to your [Prisma schema](/orm/prisma-schema) in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -:::note -`generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. -::: - -Great, you now created three tables in your database with Prisma Migrate 🚀 - - - - - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -> **Note**: `generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. - -Great, you now created three tables in your database with Prisma Migrate 🚀 - - - - - -In this guide, you'll use Prisma's [`db push` command](/orm/prisma-migrate/workflows/prototyping-your-schema) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int - - @@index(authorId) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique - - @@index(userId) -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -You are now ready to push your new schema to your database. Connect to your `main` branch using the instructions in [Connect your database](/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale). - -Now use the `db push` CLI command to push to the `main` branch: - -```terminal -npx prisma db push -``` - -Great, you now created three tables in your database with Prisma's `db push` command 🚀 - - - - - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -> **Note**: `generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. - -Great, you now created three tables in your database with Prisma Migrate 🚀 - - - - - - - - - -```sql -CREATE TABLE "Post" ( - "id" SERIAL, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - "title" VARCHAR(255) NOT NULL, - "content" TEXT, - "published" BOOLEAN NOT NULL DEFAULT false, - "authorId" INTEGER NOT NULL, - PRIMARY KEY ("id") -); - -CREATE TABLE "Profile" ( - "id" SERIAL, - "bio" TEXT, - "userId" INTEGER NOT NULL, - PRIMARY KEY ("id") -); - -CREATE TABLE "User" ( - "id" SERIAL, - "email" TEXT NOT NULL, - "name" TEXT, - PRIMARY KEY ("id") -); - -CREATE UNIQUE INDEX "Profile.userId_unique" ON "Profile"("userId"); -CREATE UNIQUE INDEX "User.email_unique" ON "User"("email"); -ALTER TABLE "Post" ADD FOREIGN KEY("authorId")REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; -ALTER TABLE "Profile" ADD FOREIGN KEY("userId")REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; -``` - - - - - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `TEXT` | No | No | No | - | -| `email` | `TEXT` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | -| `updatedAt` | `TIMESTAMP` | No | No | **✔️** | | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `TEXT` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INTEGER` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `TEXT` | No | No | No | - | -| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | - - - - - - - - - - - - - -```sql -CREATE TABLE "Post" ( - "id" SERIAL, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - "title" TEXT NOT NULL, - "content" TEXT, - "published" BOOLEAN NOT NULL DEFAULT false, - "authorId" INTEGER NOT NULL, - PRIMARY KEY ("id") -); - -CREATE TABLE "Profile" ( - "id" SERIAL, - "bio" TEXT, - "userId" INTEGER NOT NULL, - PRIMARY KEY ("id") -); - -CREATE TABLE "User" ( - "id" SERIAL, - "email" TEXT NOT NULL, - "name" TEXT, - PRIMARY KEY ("id") -); - -CREATE UNIQUE INDEX "Profile.userId_unique" ON "Profile"("userId"); -CREATE UNIQUE INDEX "User.email_unique" ON "User"("email"); -ALTER TABLE "Post" ADD FOREIGN KEY("authorId")REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; -ALTER TABLE "Profile" ADD FOREIGN KEY("userId")REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; -``` - - - - - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `TEXT` | No | No | No | - | -| `email` | `TEXT` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | -| `updatedAt` | `TIMESTAMP` | No | No | **✔️** | | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `TEXT` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INTEGER` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `TEXT` | No | No | No | - | -| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | - - - - - - - - - - - - - -```sql -CREATE TABLE `Post` ( - `id` int NOT NULL AUTO_INCREMENT, - `createdAt` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), - `updatedAt` datetime(3) NOT NULL, - `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, - `content` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - `published` tinyint(1) NOT NULL DEFAULT '0', - `authorId` int NOT NULL, - PRIMARY KEY (`id`), - KEY `Post_authorId_idx` (`authorId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - -CREATE TABLE `Profile` ( - `id` int NOT NULL AUTO_INCREMENT, - `bio` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - `userId` int NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `Profile_userId_key` (`userId`), - KEY `Profile_userId_idx` (`userId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - -CREATE TABLE `User` ( - `id` int NOT NULL AUTO_INCREMENT, - `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, - `name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `User_email_key` (`email`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - -``` - - - - - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `varchar(191)` | No | No | No | - | -| `email` | `varchar(191)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `datetime(3)` | No | No | **✔️** | `now()` | -| `updatedAt` | `datetime(3)` | No | No | **✔️** | | -| `title` | `varchar(255)` | No | No | **✔️** | - | -| `content` | `varchar(191)` | No | No | No | - | -| `published` | `tinyint(1)` | No | No | **✔️** | `false` | -| `authorId` | `int` | No | No | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `varchar(191)` | No | No | No | - | -| `userId` | `int` | No | No | **✔️** | - | - - - - - - - - - - - - - -```sql -BEGIN TRY - -BEGIN TRAN; - --- CreateTable -CREATE TABLE [dbo].[Post] ( - [id] INT NOT NULL IDENTITY(1,1), - [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, - [updatedAt] DATETIME2 NOT NULL, - [title] VARCHAR(255) NOT NULL, - [content] NVARCHAR(1000), - [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, - [authorId] INT NOT NULL, - CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) -); - --- CreateTable -CREATE TABLE [dbo].[Profile] ( - [id] INT NOT NULL IDENTITY(1,1), - [bio] NVARCHAR(1000), - [userId] INT NOT NULL, - CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), - CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) -); - --- CreateTable -CREATE TABLE [dbo].[User] ( - [id] INT NOT NULL IDENTITY(1,1), - [email] NVARCHAR(1000) NOT NULL, - [name] NVARCHAR(1000), - CONSTRAINT [User_pkey] PRIMARY KEY ([id]), - CONSTRAINT [User_email_key] UNIQUE ([email]) -); - --- AddForeignKey -ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; - -COMMIT TRAN; - -END TRY -BEGIN CATCH - -IF @@TRANCOUNT > 0 -BEGIN - ROLLBACK TRAN; -END; -THROW - -END CATCH -``` - - - - - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `NVARCHAR(1000)` | No | No | No | - | -| `email` | `NVARCHAR(1000)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `DATETIME2` | No | No | **✔️** | `now()` | -| `updatedAt` | `DATETIME2` | No | No | **✔️** | | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `NVARCHAR(1000)` | No | No | No | - | -| `published` | `BIT` | No | No | **✔️** | `false` | -| `authorId` | `INT` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `NVARCHAR(1000)` | No | No | No | - | -| `userId` | `INT` | No | **✔️** | **✔️** | - | - - - - - - - - - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy -model Post { - id BigInt @id @default(sequence()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId BigInt -} - -model Profile { - id BigInt @id @default(sequence()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId BigInt @unique -} - -model User { - id BigInt @id @default(sequence()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -:::note -`generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. -::: - -Great, you now created three tables in your database with Prisma Migrate 🚀 - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx new file mode 100644 index 0000000000..53d79d878e --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx @@ -0,0 +1,52 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +hide_table_of_contents: true +--- + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. + + + + + Using Prisma Migrate + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-mysql.mdx new file mode 100644 index 0000000000..4625d1f607 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-mysql.mdx @@ -0,0 +1,52 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +hide_table_of_contents: true +--- + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. + + + + + Using Prisma Migrate + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-planetscale.mdx new file mode 100644 index 0000000000..c6be65e583 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-planetscale.mdx @@ -0,0 +1,53 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +hide_table_of_contents: true +--- + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. + + + + + Using Prisma Migrate + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-postgresql.mdx new file mode 100644 index 0000000000..cbc98d4d4f --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-postgresql.mdx @@ -0,0 +1,53 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +hide_table_of_contents: true +--- + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. + + + + + Using Prisma Migrate + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx new file mode 100644 index 0000000000..168a34e2ee --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx @@ -0,0 +1,53 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +hide_table_of_contents: true +--- + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. + + + + + Using Prisma Migrate + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx new file mode 100644 index 0000000000..eaeff89901 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx @@ -0,0 +1,53 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +hide_table_of_contents: true +--- + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. + + + + + Using Prisma Migrate + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx new file mode 100644 index 0000000000..d053c99190 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx @@ -0,0 +1,53 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +hide_table_of_contents: true +--- + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. + + + + + Using Prisma Migrate + + + + Querying the database + + + \ No newline at end of file diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx new file mode 100644 index 0000000000..e6b66bba25 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx @@ -0,0 +1,53 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +hide_table_of_contents: true +--- + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. + + + + + Creating the database schema + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx new file mode 100644 index 0000000000..16d165acdb --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx @@ -0,0 +1,52 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. + + + + + Using Prisma Migrate + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx new file mode 100644 index 0000000000..3ec47a83a8 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx @@ -0,0 +1,53 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +hide_table_of_contents: true +--- + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. + + + + + Using Prisma Migrate + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client.mdx deleted file mode 100644 index 02b5761ada..0000000000 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client.mdx +++ /dev/null @@ -1,282 +0,0 @@ ---- -title: 'Install Prisma Client' -metaTitle: 'Install Prisma Client' -metaDescription: 'Install and generate Prisma Client in your project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true ---- - -## Install and generate Prisma Client - -To get started with Prisma Client, you need to install the `@prisma/client` package: - -```terminal copy -npm install @prisma/client -``` - -The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. - -![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) - -Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. The commands will also regenerate Prisma Client. - - - - - - - Using Prisma Migrate - - - - Querying the database - - - - - - - - - - - - Using Prisma Migrate - - - - Querying the database - - - - - - - - - - - - Using Prisma Migrate - - - - Querying the database - - - - - - - - - - - - Using Prisma Migrate - - - - Querying the database - - - - - - - - - - - - Using Prisma Migrate - - - - Querying the database - - - - - - - - - - - - Using Prisma Migrate - - - - Querying the database - - - - - - - - - - - - Using Prisma Migrate - - - - Querying the database - - - - - - - - - - - - Creating the database schema - - - - Querying the database - - - - - - - - - - - - Using Prisma Migrate - - - - Querying the database - - - - - - - - - - - - Using Prisma Migrate - - - - Querying the database - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx new file mode 100644 index 0000000000..057890e33c --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx @@ -0,0 +1,224 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +--- + + + +## Write your first query with Prisma Client + +Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js copy +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```js file=index.js highlight=2;delete|3,4;add +async function main() { + // ... you will write your Prisma Client queries here + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +This should print an empty array because there are no `User` records in the database yet: + +```json no-lines +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js highlight=2-21;add copy +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +The output should look similar to this: + +```js no-lines +[ + { + email: 'alice@prisma.io', + id: 1, + name: 'Alice', + posts: [ + { + content: null, + createdAt: 2020-03-21T16:45:01.246Z, + updatedAt: 2020-03-21T16:45:01.246Z, + id: 1, + published: false, + title: 'Hello World', + authorId: 1, + } + ], + profile: { + bio: 'I like turtles', + id: 1, + userId: 1, + } + } +] +``` + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"alice@prisma.io"` | `"Alice"` | + +**Post** + +| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | +| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | + +**Profile** + +| **id** | **bio** | **userId** | +| :----- | :----------------- | :--------- | +| `1` | `"I like turtles"` | `1` | + +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js copy +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + +You will see the following output: + +```js no-lines +{ + id: 1, + title: 'Hello World', + content: null, + published: true, + authorId: 1 +} +``` + +The `Post` record with an `id` of `1` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **authorId** | +| :----- | :-------------- | :---------- | :------------ | :----------- | +| `1` | `"Hello World"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-mysql.mdx new file mode 100644 index 0000000000..3954ea8c76 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-mysql.mdx @@ -0,0 +1,220 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Write your first query with Prisma Client + +Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js copy +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```js file=index.js highlight=2;delete|3,4;add +async function main() { + // ... you will write your Prisma Client queries here + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +This should print an empty array because there are no `User` records in the database yet: + +```json no-lines +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js highlight=2-21;add copy +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +The output should look similar to this: + +```js no-lines +[ + { + email: 'alice@prisma.io', + id: 1, + name: 'Alice', + posts: [ + { + content: null, + createdAt: 2020-03-21T16:45:01.246Z, + updatedAt: 2020-03-21T16:45:01.246Z, + id: 1, + published: false, + title: 'Hello World', + authorId: 1, + } + ], + profile: { + bio: 'I like turtles', + id: 1, + userId: 1, + } + } +] +``` + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"alice@prisma.io"` | `"Alice"` | + +**Post** + +| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | +| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | + +**Profile** + +| **id** | **bio** | **userId** | +| :----- | :----------------- | :--------- | +| `1` | `"I like turtles"` | `1` | + +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js copy +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + +You will see the following output: + +```js no-lines +{ + id: 1, + title: 'Hello World', + content: null, + published: true, + authorId: 1 +} +``` + +The `Post` record with an `id` of `1` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **authorId** | +| :----- | :-------------- | :---------- | :------------ | :----------- | +| `1` | `"Hello World"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-planetscale.mdx new file mode 100644 index 0000000000..5178863001 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-planetscale.mdx @@ -0,0 +1,226 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Write your first query with Prisma Client + +Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js copy +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```js file=index.js highlight=2;delete|3,4;add +async function main() { + // ... you will write your Prisma Client queries here + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +This should print an empty array because there are no `User` records in the database yet: + +```json no-lines +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js highlight=2-21;add copy +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +The output should look similar to this: + +```js no-lines +[ + { + email: 'alice@prisma.io', + id: 1, + name: 'Alice', + posts: [ + { + content: null, + createdAt: 2020-03-21T16:45:01.246Z, + updatedAt: 2020-03-21T16:45:01.246Z, + id: 1, + published: false, + title: 'Hello World', + authorId: 1, + } + ], + profile: { + bio: 'I like turtles', + id: 1, + userId: 1, + } + } +] +``` + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"alice@prisma.io"` | `"Alice"` | + +**Post** + +| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | +| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | + +**Profile** + +| **id** | **bio** | **userId** | +| :----- | :----------------- | :--------- | +| `1` | `"I like turtles"` | `1` | + +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + + +```js file=index.js copy +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + +You will see the following output: + +```js no-lines +{ + id: 1, + title: 'Hello World', + content: null, + published: true, + authorId: 1 +} +``` + +The `Post` record with an `id` of `1` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **authorId** | +| :----- | :-------------- | :---------- | :------------ | :----------- | +| `1` | `"Hello World"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-postgresql.mdx new file mode 100644 index 0000000000..6304bb96c9 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-postgresql.mdx @@ -0,0 +1,226 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Write your first query with Prisma Client + +Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js copy +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + + +```js file=index.js highlight=2;delete|3,4;add +async function main() { + // ... you will write your Prisma Client queries here + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +This should print an empty array because there are no `User` records in the database yet: + +```json no-lines +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js highlight=2-21;add copy +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +The output should look similar to this: + +```js no-lines +[ + { + email: 'alice@prisma.io', + id: 1, + name: 'Alice', + posts: [ + { + content: null, + createdAt: 2020-03-21T16:45:01.246Z, + updatedAt: 2020-03-21T16:45:01.246Z, + id: 1, + published: false, + title: 'Hello World', + authorId: 1, + } + ], + profile: { + bio: 'I like turtles', + id: 1, + userId: 1, + } + } +] +``` + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"alice@prisma.io"` | `"Alice"` | + +**Post** + +| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | +| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | + +**Profile** + +| **id** | **bio** | **userId** | +| :----- | :----------------- | :--------- | +| `1` | `"I like turtles"` | `1` | + +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js copy +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + +You will see the following output: + +```js no-lines +{ + id: 1, + title: 'Hello World', + content: null, + published: true, + authorId: 1 +} +``` + +The `Post` record with an `id` of `1` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **authorId** | +| :----- | :-------------- | :---------- | :------------ | :----------- | +| `1` | `"Hello World"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-sqlserver.mdx new file mode 100644 index 0000000000..bff87e9dbd --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-sqlserver.mdx @@ -0,0 +1,225 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Write your first query with Prisma Client + +Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js copy +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```js file=index.js highlight=2;delete|3,4;add +async function main() { + // ... you will write your Prisma Client queries here + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +This should print an empty array because there are no `User` records in the database yet: + +```json no-lines +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js highlight=2-21;add copy +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +The output should look similar to this: + +```js no-lines +[ + { + email: 'alice@prisma.io', + id: 1, + name: 'Alice', + posts: [ + { + content: null, + createdAt: 2020-03-21T16:45:01.246Z, + updatedAt: 2020-03-21T16:45:01.246Z, + id: 1, + published: false, + title: 'Hello World', + authorId: 1, + } + ], + profile: { + bio: 'I like turtles', + id: 1, + userId: 1, + } + } +] +``` + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"alice@prisma.io"` | `"Alice"` | + +**Post** + +| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | +| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | + +**Profile** + +| **id** | **bio** | **userId** | +| :----- | :----------------- | :--------- | +| `1` | `"I like turtles"` | `1` | + +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js copy +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + +You will see the following output: + +```js no-lines +{ + id: 1, + title: 'Hello World', + content: null, + published: true, + authorId: 1 +} +``` + +The `Post` record with an `id` of `1` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **authorId** | +| :----- | :-------------- | :---------- | :------------ | :----------- | +| `1` | `"Hello World"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx similarity index 55% rename from docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database.mdx rename to docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx index 64dab0f138..6fe0a86bf9 100644 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database.mdx +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx @@ -5,14 +5,20 @@ metaDescription: 'Write data to and query the database' langSwitcher: ['typescript', 'node'] dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] hide_table_of_contents: true +sidebar_class_name: hidden-sidebar --- + + ## Write your first query with Prisma Client Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - - Create a new file named `index.ts` and add the following code to it: ```js file=index.ts copy @@ -35,34 +41,6 @@ main() }) ``` - - - - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js copy -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - - - Here's a quick overview of the different parts of the code snippet: 1. Import the `PrismaClient` constructor from the `@prisma/client` node module @@ -73,8 +51,6 @@ Here's a quick overview of the different parts of the code snippet: Inside the `main` function, add the following query to read all `User` records from the database and print the result: - - ```ts file=index.ts highlight=3,4;add async function main() { // ... you will write your Prisma Client queries here @@ -83,38 +59,12 @@ async function main() { } ``` - - - - -```js file=index.js highlight=2;delete|3,4;add -async function main() { - // ... you will write your Prisma Client queries here - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - - - Now run the code with this command: - - ```terminal copy npx ts-node index.ts ``` - - - - -```terminal copy -node index.js -``` - - - This should print an empty array because there are no `User` records in the database yet: ```json no-lines @@ -127,8 +77,6 @@ The `findMany` query you used in the previous section only _reads_ data from the Adjust the `main` function to send a `create` query to the database: - - ```ts file=index.ts highlight=2-21;add copy async function main() { await prisma.user.create({ @@ -154,59 +102,16 @@ async function main() { } ``` - - - - -```js file=index.js highlight=2-21;add copy -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - - - This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. Run the code with this command: - - ```terminal copy npx ts-node index.ts ``` - - - - -```terminal copy -node index.js -``` - - - The output should look similar to this: ```js no-lines @@ -235,8 +140,6 @@ The output should look similar to this: ] ``` - - Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: ```ts no-lines @@ -253,8 +156,6 @@ export type Post = { } ``` - - The query added new records to the `User` and the `Post` tables: **User** @@ -279,8 +180,6 @@ The query added new records to the `User` and the `Post` tables: Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - - ```ts file=index.ts copy async function main() { const post = await prisma.post.update({ @@ -291,42 +190,12 @@ async function main() { } ``` - - - - -```js file=index.js copy -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - Now run the code using the same command as before: ```terminal copy npx ts-node index.ts ``` - - - - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - - - You will see the following output: ```js no-lines @@ -349,7 +218,6 @@ The `Post` record with an `id` of `1` now got updated in the database: Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 - @@ -373,213 +241,6 @@ Fantastic, you just wrote new data into your database for the first time using P - - - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-mysql.mdx new file mode 100644 index 0000000000..27ab54ad25 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-mysql.mdx @@ -0,0 +1,241 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Write your first query with Prisma Client + +Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +Create a new file named `index.ts` and add the following code to it: + +```js file=index.ts copy +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```ts file=index.ts highlight=3,4;add +async function main() { + // ... you will write your Prisma Client queries here + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +npx ts-node index.ts +``` + +This should print an empty array because there are no `User` records in the database yet: + +```json no-lines +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```ts file=index.ts highlight=2-21;add copy +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +npx ts-node index.ts +``` + +The output should look similar to this: + +```js no-lines +[ + { + email: 'alice@prisma.io', + id: 1, + name: 'Alice', + posts: [ + { + content: null, + createdAt: 2020-03-21T16:45:01.246Z, + updatedAt: 2020-03-21T16:45:01.246Z, + id: 1, + published: false, + title: 'Hello World', + authorId: 1, + } + ], + profile: { + bio: 'I like turtles', + id: 1, + userId: 1, + } + } +] +``` + +Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: + +```ts no-lines +const allUsers: (User & { + posts: Post[] +})[] + +export type Post = { + id: number + title: string + content: string | null + published: boolean + authorId: number | null +} +``` + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"alice@prisma.io"` | `"Alice"` | + +**Post** + +| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | +| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | + +**Profile** + +| **id** | **bio** | **userId** | +| :----- | :----------------- | :--------- | +| `1` | `"I like turtles"` | `1` | + +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```ts file=index.ts copy +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +npx ts-node index.ts +``` + +You will see the following output: + +```js no-lines +{ + id: 1, + title: 'Hello World', + content: null, + published: true, + authorId: 1 +} +``` + +The `Post` record with an `id` of `1` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **authorId** | +| :----- | :-------------- | :---------- | :------------ | :----------- | +| `1` | `"Hello World"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx new file mode 100644 index 0000000000..f88187a30b --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx @@ -0,0 +1,264 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Write your first query with Prisma Client + +Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +Create a new file named `index.ts` and add the following code to it: + +```js file=index.ts copy +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```ts file=index.ts highlight=3,4;add +async function main() { + // ... you will write your Prisma Client queries here + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +npx ts-node index.ts +``` + +This should print an empty array because there are no `User` records in the database yet: + +```json no-lines +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```ts file=index.ts highlight=2-21;add copy +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +npx ts-node index.ts +``` + +The output should look similar to this: + +```js no-lines +[ + { + email: 'alice@prisma.io', + id: 1, + name: 'Alice', + posts: [ + { + content: null, + createdAt: 2020-03-21T16:45:01.246Z, + updatedAt: 2020-03-21T16:45:01.246Z, + id: 1, + published: false, + title: 'Hello World', + authorId: 1, + } + ], + profile: { + bio: 'I like turtles', + id: 1, + userId: 1, + } + } +] +``` + +Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: + +```ts no-lines +const allUsers: (User & { + posts: Post[] +})[] + +export type Post = { + id: number + title: string + content: string | null + published: boolean + authorId: number | null +} +``` + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"alice@prisma.io"` | `"Alice"` | + +**Post** + +| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | +| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | + +**Profile** + +| **id** | **bio** | **userId** | +| :----- | :----------------- | :--------- | +| `1` | `"I like turtles"` | `1` | + +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```ts file=index.ts copy +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +npx ts-node index.ts +``` + +You will see the following output: + +```js no-lines +{ + id: 1, + title: 'Hello World', + content: null, + published: true, + authorId: 1 +} +``` + +The `Post` record with an `id` of `1` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **authorId** | +| :----- | :-------------- | :---------- | :------------ | :----------- | +| `1` | `"Hello World"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + + Install Prisma Client + + + + Next Steps + + + + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx new file mode 100644 index 0000000000..94d22ff858 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx @@ -0,0 +1,240 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Write your first query with Prisma Client + +Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +Create a new file named `index.ts` and add the following code to it: + +```js file=index.ts copy +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```ts file=index.ts highlight=3,4;add +async function main() { + // ... you will write your Prisma Client queries here + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +npx ts-node index.ts +``` + +This should print an empty array because there are no `User` records in the database yet: + +```json no-lines +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```ts file=index.ts highlight=2-21;add copy +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +npx ts-node index.ts +``` + +The output should look similar to this: + +```js no-lines +[ + { + email: 'alice@prisma.io', + id: 1, + name: 'Alice', + posts: [ + { + content: null, + createdAt: 2020-03-21T16:45:01.246Z, + updatedAt: 2020-03-21T16:45:01.246Z, + id: 1, + published: false, + title: 'Hello World', + authorId: 1, + } + ], + profile: { + bio: 'I like turtles', + id: 1, + userId: 1, + } + } +] +``` + +Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: + +```ts no-lines +const allUsers: (User & { + posts: Post[] +})[] + +export type Post = { + id: number + title: string + content: string | null + published: boolean + authorId: number | null +} +``` + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"alice@prisma.io"` | `"Alice"` | + +**Post** + +| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | +| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | + +**Profile** + +| **id** | **bio** | **userId** | +| :----- | :----------------- | :--------- | +| `1` | `"I like turtles"` | `1` | + +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```ts file=index.ts copy +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +npx ts-node index.ts +``` + +You will see the following output: + +```js no-lines +{ + id: 1, + title: 'Hello World', + content: null, + published: true, + authorId: 1 +} +``` + +The `Post` record with an `id` of `1` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **authorId** | +| :----- | :-------------- | :---------- | :------------ | :----------- | +| `1` | `"Hello World"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx new file mode 100644 index 0000000000..2ab7cbbb03 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx @@ -0,0 +1,264 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Write your first query with Prisma Client + +Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +Create a new file named `index.ts` and add the following code to it: + +```js file=index.ts copy +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```ts file=index.ts highlight=3,4;add +async function main() { + // ... you will write your Prisma Client queries here + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +npx ts-node index.ts +``` + +This should print an empty array because there are no `User` records in the database yet: + +```json no-lines +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```ts file=index.ts highlight=2-21;add copy +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +npx ts-node index.ts +``` + +The output should look similar to this: + +```js no-lines +[ + { + email: 'alice@prisma.io', + id: 1, + name: 'Alice', + posts: [ + { + content: null, + createdAt: 2020-03-21T16:45:01.246Z, + updatedAt: 2020-03-21T16:45:01.246Z, + id: 1, + published: false, + title: 'Hello World', + authorId: 1, + } + ], + profile: { + bio: 'I like turtles', + id: 1, + userId: 1, + } + } +] +``` + +Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: + +```ts no-lines +const allUsers: (User & { + posts: Post[] +})[] + +export type Post = { + id: number + title: string + content: string | null + published: boolean + authorId: number | null +} +``` + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"alice@prisma.io"` | `"Alice"` | + +**Post** + +| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | +| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | + +**Profile** + +| **id** | **bio** | **userId** | +| :----- | :----------------- | :--------- | +| `1` | `"I like turtles"` | `1` | + +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```ts file=index.ts copy +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +npx ts-node index.ts +``` + +You will see the following output: + +```js no-lines +{ + id: 1, + title: 'Hello World', + content: null, + published: true, + authorId: 1 +} +``` + +The `Post` record with an `id` of `1` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **authorId** | +| :----- | :-------------- | :---------- | :------------ | :----------- | +| `1` | `"Hello World"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + + Install Prisma Client + + + + Next Steps + + + + + + + + Install Prisma Client + + + + Next Steps + + + \ No newline at end of file diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/index.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/index.mdx deleted file mode 100644 index c836e2ca2b..0000000000 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/index.mdx +++ /dev/null @@ -1,300 +0,0 @@ ---- -title: 'Relational databases' -metaTitle: 'Start from scratch with relational databases (15 min)' -metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } ---- - - - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - - - -- [Node.js](https://nodejs.org/en/) installed on your machine -- a [PostgreSQL](https://www.postgresql.org/) database server running - - - - - -- [Node.js](https://nodejs.org/en/) installed on your machine -- a [CockroachDB](https://www.cockroachlabs.com/) database server running - - - - - -- [Node.js](https://nodejs.org/en/) installed on your machine -- a [MySQL](https://www.mysql.com/) database server running - - - - - -- [Node.js](https://nodejs.org/en/) installed on your machine -- a [PlanetScale](https://www.planetscale.com/) database server running - - - -This tutorial will also assume that you can push to the `main` branch of your database. Do not do this if your `main` branch has been promoted to production. - - - - - - - -- [Node.js](https://nodejs.org/en/) installed on your machine -- A [Microsoft SQL Server](https://docs.microsoft.com/en-us/sql/?view=sql-server-ver15) database - - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) - - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) - - - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - - - -Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma typescript ts-node @types/node --save-dev -``` - -This creates a `package.json` with an initial setup for your TypeScript app. - -Next, initialize TypeScript: - -```terminal copy -npx tsc --init -``` - - - - - -Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma --save-dev -``` - -This creates a `package.json` with an initial setup for a Node.js app. - - - - - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - - - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```terminal -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: - -```terminal copy -npx prisma init -``` - -This command does two things: - -- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models -- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-node-mongodb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-node-mongodb.mdx new file mode 100644 index 0000000000..51a7726808 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-node-mongodb.mdx @@ -0,0 +1,86 @@ +--- +title: 'MongoDB' +metaTitle: 'Start from scratch with MongoDB (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your MongoDB database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['mongodb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your MongoDB database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli) and [Prisma Client](/orm/prisma-client). + + + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- Access to a MongoDB 4.2+ server with a replica set deployment. We recommend using [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). + + + + The MongoDB database connector uses transactions to support nested writes. Transactions **require** a [replica set](https://docs.mongodb.com/manual/tutorial/deploy-replica-set/) deployment. The easiest way to deploy a replica set is with [Atlas](https://docs.atlas.mongodb.com/getting-started/). It's free to get started. + + + +Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +## Create project setup + +As a first step, create a project directory and navigate into it: + +```terminal copy +mkdir hello-prisma +cd hello-prisma +``` + +Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: + +```terminal copy +npm init -y +npm install prisma --save-dev +``` + +This creates a `package.json` with an initial setup for a Node.js app. + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/index.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-typescript-mongodb.mdx similarity index 80% rename from docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/index.mdx rename to docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-typescript-mongodb.mdx index 49a9f6e357..743620fb22 100644 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/index.mdx +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-typescript-mongodb.mdx @@ -8,7 +8,12 @@ dbSwitcher: ['mongodb'] sidebar_custom_props: { badge: '15 min' } --- - + Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your MongoDB database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli) and [Prisma Client](/orm/prisma-client). @@ -40,8 +45,6 @@ mkdir hello-prisma cd hello-prisma ``` - - Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: ```terminal copy @@ -57,21 +60,6 @@ Next, initialize TypeScript: npx tsc --init ``` - - - - -Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma --save-dev -``` - -This creates a `package.json` with an initial setup for a Node.js app. - - - You can now invoke the Prisma CLI by prefixing it with `npx`: ```terminal @@ -89,25 +77,6 @@ This command does two things: - creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models - creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) - - - - - - Connect your database - - - - - - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-node-mongodb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-node-mongodb.mdx new file mode 100644 index 0000000000..b02094d62f --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-node-mongodb.mdx @@ -0,0 +1,71 @@ +--- +title: 'Connect your database (MongoDB)' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['mongodb'] +toc: false +--- + + + +## Connect your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "mongodb" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env` (the example uses a [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) URL): + +```bash file=.env +DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase" +``` + +You now need to adjust the connection URL to point to your own database. + +The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For MongoDB, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +```no-lines +mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- `USERNAME`: The name of your database user +- `PASSWORD`: The password for your database user +- `HOST`: The host where a [`mongod`](https://docs.mongodb.com/manual/reference/program/mongod/#mongodb-binary-bin.mongod) (or [`mongos`](https://docs.mongodb.com/manual/reference/program/mongos/#mongodb-binary-bin.mongos)) instance is running +- `PORT`: The port where your database server is running (typically `27017` for MongoDB) +- `DATABASE`: The name of the database + + + + + Installation + + + + Creating the Prisma schema + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-typescript-mongodb.mdx similarity index 81% rename from docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database.mdx rename to docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-typescript-mongodb.mdx index 49483c2a22..1ad2bec2ab 100644 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database.mdx +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-typescript-mongodb.mdx @@ -7,6 +7,13 @@ dbSwitcher: ['mongodb'] hide_table_of_contents: true --- + + ## Connect your database To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): @@ -40,34 +47,6 @@ Here's a short explanation of each component: - `PORT`: The port where your database server is running (typically `27017` for MongoDB) - `DATABASE`: The name of the database - - - - - - Installation - - - - Creating the Prisma schema - - - - - - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-node-mongodb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-node-mongodb.mdx new file mode 100644 index 0000000000..0abac65eb4 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-node-mongodb.mdx @@ -0,0 +1,93 @@ +--- +title: 'Creating the Prisma schema' +metaTitle: 'Creating the Prisma schema' +metaDescription: 'Update the Prisma schema for MongoDB' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['mongodb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Update the Prisma schema + +Open the `prisma/schema.prisma` file and replace the default contents with the following: + +```prisma file=prisma/schema.prisma +datasource db { + provider = "mongodb" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} + +model Post { + id String @id @default(auto()) @map("_id") @db.ObjectId + slug String @unique + title String + body String + author User @relation(fields: [authorId], references: [id]) + authorId String @db.ObjectId + comments Comment[] +} + +model User { + id String @id @default(auto()) @map("_id") @db.ObjectId + email String @unique + name String? + address Address? + posts Post[] +} + +model Comment { + id String @id @default(auto()) @map("_id") @db.ObjectId + comment String + post Post @relation(fields: [postId], references: [id]) + postId String @db.ObjectId +} + +// Address is an embedded document +type Address { + street String + city String + state String + zip String +} +``` + +There are also a number of subtle differences in how the schema is setup when compared to relational databases like PostgreSQL. + +For example, the underlying `ID` field name is always `_id` and must be mapped with `@map("_id")`. + +For more information check out the [MongoDB schema reference](/orm/reference/prisma-schema-reference#mongodb-2). + + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-typescript-mongodb.mdx similarity index 80% rename from docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema.mdx rename to docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-typescript-mongodb.mdx index 3a6ee18154..bdd70d9108 100644 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema.mdx +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-typescript-mongodb.mdx @@ -7,6 +7,13 @@ dbSwitcher: ['mongodb'] hide_table_of_contents: true --- + + ## Update the Prisma schema Open the `prisma/schema.prisma` file and replace the default contents with the following: @@ -61,34 +68,6 @@ For example, the underlying `ID` field name is always `_id` and must be mapped w For more information check out the [MongoDB schema reference](/orm/reference/prisma-schema-reference#mongodb-2). - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-node-mongodb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-node-mongodb.mdx new file mode 100644 index 0000000000..f103c6b78b --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-node-mongodb.mdx @@ -0,0 +1,52 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['mongodb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you update your Prisma schema, you will need to run the `prisma db push` command to create new indexes and regenerate Prisma Client. + + + + + Creating the Prisma schema + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx similarity index 70% rename from docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client.mdx rename to docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx index 8647406b7c..16d0cb66c7 100644 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client.mdx +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx @@ -7,6 +7,13 @@ dbSwitcher: ['mongodb'] hide_table_of_contents: true --- + + ## Install and generate Prisma Client To get started with Prisma Client, you need to install the `@prisma/client` package: @@ -21,34 +28,6 @@ The install command invokes `prisma generate` for you which reads your Prisma sc Whenever you update your Prisma schema, you will need to run the `prisma db push` command to create new indexes and regenerate Prisma Client. - - - - - - Creating the Prisma schema - - - - Querying the database - - - - - - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-node-mongodb.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-node-mongodb.mdx new file mode 100644 index 0000000000..2488c0eb8e --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-node-mongodb.mdx @@ -0,0 +1,232 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['mongodb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js copy +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Connect to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```js file=index.js +async function main() { +- // ... you will write your Prisma Client queries here ++ const allUsers = await prisma.user.findMany() ++ console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +This should print an empty array because there are no `User` records in the database yet: + +```json no-lines +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post`, `User` and `Comment` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js highlight=2-21;add copy +async function main() { + await prisma.user.create({ + data: { + name: 'Rich', + email: 'hello@prisma.com', + posts: { + create: { + title: 'My first post', + body: 'Lots of really interesting stuff', + slug: 'my-first-post', + }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with a new `Post` using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the other one via the `Post.author` ↔ `User.posts` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +The output should look similar to this: + +```json5 no-lines +[ + { + id: '60cc9b0e001e3bfd00a6eddf', + email: 'hello@prisma.com', + name: 'Rich', + address: null, + posts: [ + { + id: '60cc9bad005059d6007f45dd', + slug: 'my-first-post', + title: 'My first post', + body: 'Lots of really interesting stuff', + userId: '60cc9b0e001e3bfd00a6eddf', + }, + ], + }, +] +``` + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :------------------------- | :------------------- | :------- | +| `60cc9b0e001e3bfd00a6eddf` | `"hello@prisma.com"` | `"Rich"` | + +**Post** + +| **id** | **createdAt** | **title** | **content** | **published** | **authorId** | +| :------------------------- | :------------------------- | :---------------- | :--------------------------------- | :------------ | :------------------------- | +| `60cc9bad005059d6007f45dd` | `2020-03-21T16:45:01.246Z` | `"My first post"` | `Lots of really interesting stuff` | `false` | `60cc9b0e001e3bfd00a6eddf` | + +> **Note**: The unique IDs in the `authorId` column on `Post` reference the `id` column of the `User` table, meaning the `id` value `60cc9b0e001e3bfd00a6eddf` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll add a couple of comments to the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js copy +async function main() { + await prisma.post.update({ + where: { + slug: 'my-first-post', + }, + data: { + comments: { + createMany: { + data: [ + { comment: 'Great post!' }, + { comment: "Can't wait to read more!" }, + ], + }, + }, + }, + }) + const posts = await prisma.post.findMany({ + include: { + comments: true, + }, + }) + + console.dir(posts, { depth: Infinity }) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + +You will see the following output: + +```json5 no-lines +[ + { + id: '60cc9bad005059d6007f45dd', + slug: 'my-first-post', + title: 'My first post', + body: 'Lots of really interesting stuff', + userId: '60cc9b0e001e3bfd00a6eddf', + comments: [ + { + id: '60cca420008a21d800578793', + postId: '60cca40300af8bf000f6ca99', + comment: 'Great post!', + }, + { + id: '60cca420008a21d800578794', + postId: '60cca40300af8bf000f6ca99', + comment: "Can't wait to try this!", + }, + ], + }, +] +``` + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database.mdx b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-typescript-mongodb.mdx similarity index 68% rename from docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database.mdx rename to docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-typescript-mongodb.mdx index a34b10722b..d4867dde63 100644 --- a/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database.mdx +++ b/docs/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-typescript-mongodb.mdx @@ -7,12 +7,17 @@ dbSwitcher: ['mongodb'] hide_table_of_contents: true --- + + ## Write your first query with Prisma Client Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - - Create a new file named `index.ts` and add the following code to it: ```js file=index.ts copy @@ -34,34 +39,6 @@ main() }) ``` - - - - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js copy -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - - - Here's a quick overview of the different parts of the code snippet: 1. Import the `PrismaClient` constructor from the `@prisma/client` node module @@ -73,8 +50,6 @@ Here's a quick overview of the different parts of the code snippet: Inside the `main` function, add the following query to read all `User` records from the database and print the result: - - ```ts file=index.ts async function main() { // ... you will write your Prisma Client queries here @@ -83,38 +58,13 @@ async function main() { } ``` - - - - -```js file=index.js -async function main() { -- // ... you will write your Prisma Client queries here -+ const allUsers = await prisma.user.findMany() -+ console.log(allUsers) -} -``` - - Now run the code with this command: - - ```terminal copy npx ts-node index.ts ``` - - - - -```terminal copy -node index.js -``` - - - This should print an empty array because there are no `User` records in the database yet: ```json no-lines @@ -127,8 +77,6 @@ The `findMany` query you used in the previous section only _reads_ data from the Adjust the `main` function to send a `create` query to the database: - - ```ts file=index.ts highlight=2-21;add copy async function main() { await prisma.user.create({ @@ -154,59 +102,16 @@ async function main() { } ``` - - - - -```js file=index.js highlight=2-21;add copy -async function main() { - await prisma.user.create({ - data: { - name: 'Rich', - email: 'hello@prisma.com', - posts: { - create: { - title: 'My first post', - body: 'Lots of really interesting stuff', - slug: 'my-first-post', - }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - - - This code creates a new `User` record together with a new `Post` using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the other one via the `Post.author` ↔ `User.posts` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` relations on the returned `User` objects. Run the code with this command: - - ```terminal copy npx ts-node index.ts ``` - - - - -```terminal copy -node index.js -``` - - - The output should look similar to this: ```json5 no-lines @@ -229,8 +134,6 @@ The output should look similar to this: ] ``` - - Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: ```ts no-lines @@ -247,8 +150,6 @@ export type Post = { } ``` - - The query added new records to the `User` and the `Post` tables: **User** @@ -267,8 +168,6 @@ The query added new records to the `User` and the `Post` tables: Before moving on to the next section, you'll add a couple of comments to the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - - ```ts file=index.ts copy async function main() { await prisma.post.update({ @@ -296,59 +195,12 @@ async function main() { } ``` - - - - -```js file=index.js copy -async function main() { - await prisma.post.update({ - where: { - slug: 'my-first-post', - }, - data: { - comments: { - createMany: { - data: [ - { comment: 'Great post!' }, - { comment: "Can't wait to read more!" }, - ], - }, - }, - }, - }) - const posts = await prisma.post.findMany({ - include: { - comments: true, - }, - }) - - console.dir(posts, { depth: Infinity }) -} -``` - - - - - Now run the code using the same command as before: ```terminal copy npx ts-node index.ts ``` - - - - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - - - You will see the following output: ```json5 no-lines @@ -377,29 +229,6 @@ You will see the following output: Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx new file mode 100644 index 0000000000..9183184abe --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx @@ -0,0 +1,89 @@ +--- +title: 'Relational databases' +metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- an existing Node.js project with a `package.json` +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [CockroachDB](https://www.cockroachlabs.com) database server running and a database with at least one table + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Set up Prisma ORM + +As a first step, navigate into your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. + + + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx new file mode 100644 index 0000000000..178ec56926 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx @@ -0,0 +1,90 @@ +--- +title: 'Relational databases' +metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- an existing Node.js project with a `package.json` +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [MySQL](https://www.mysql.com/) database server running and a database with at least one table + + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Set up Prisma ORM + +As a first step, navigate into your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. + + + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx new file mode 100644 index 0000000000..17c8c869f6 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx @@ -0,0 +1,88 @@ +--- +title: 'Relational databases' +metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- an existing Node.js project with a `package.json` +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [PlanetScale](https://www.planetscale.com/) database server running and a database with at least one table + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Set up Prisma ORM + +As a first step, navigate into your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. + + + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx new file mode 100644 index 0000000000..767bd325c0 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx @@ -0,0 +1,89 @@ +--- +title: 'Relational databases' +metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- an existing Node.js project with a `package.json` +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [PostgreSQL](https://www.postgresql.org/) database server running and a database with at least one table + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Set up Prisma ORM + +As a first step, navigate into your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. + + + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx new file mode 100644 index 0000000000..be4954667d --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx @@ -0,0 +1,83 @@ +--- +title: 'Relational databases' +metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +--- + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- A [Microsoft SQL Server](https://docs.microsoft.com/en-us/sql/?view=sql-server-ver15) database + - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) + - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Set up Prisma ORM + +As a first step, navigate into your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. + + + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx new file mode 100644 index 0000000000..9b921f5bd2 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx @@ -0,0 +1,90 @@ +--- +title: 'Relational databases' +metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- an existing Node.js project with a `package.json` +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [CockroachDB](https://www.cockroachlabs.com) database server running and a database with at least one table + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Set up Prisma ORM + +As a first step, navigate into your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. + + + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx new file mode 100644 index 0000000000..fd6237c087 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx @@ -0,0 +1,88 @@ +--- +title: 'Relational databases' +metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- an existing Node.js project with a `package.json` +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [MySQL](https://www.mysql.com/) database server running and a database with at least one table + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Set up Prisma ORM + +As a first step, navigate into your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. + + + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx new file mode 100644 index 0000000000..75bfc8db12 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx @@ -0,0 +1,88 @@ +--- +title: 'Relational databases' +metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- an existing Node.js project with a `package.json` +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [PlanetScale](https://www.planetscale.com/) database server running and a database with at least one table + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Set up Prisma ORM + +As a first step, navigate into your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. + + + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx new file mode 100644 index 0000000000..49405bd3f4 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx @@ -0,0 +1,88 @@ +--- +title: 'Relational databases' +metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- an existing Node.js project with a `package.json` +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [PostgreSQL](https://www.postgresql.org/) database server running and a database with at least one table + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Set up Prisma ORM + +As a first step, navigate into your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. + + + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx new file mode 100644 index 0000000000..4cd240b6a2 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx @@ -0,0 +1,89 @@ +--- +title: 'Relational databases' +metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' +hide_table_of_contents: true +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- A [Microsoft SQL Server](https://docs.microsoft.com/en-us/sql/?view=sql-server-ver15) database + - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) + - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +## Set up Prisma ORM + +As a first step, navigate into your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + + + +See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. + + + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx new file mode 100644 index 0000000000..2af4c721ea --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx @@ -0,0 +1,93 @@ +--- +title: 'Connect your database' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +toc: false +sidebar_class_name: hidden-sidebar +--- + + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Note that the default schema created by `prisma init` uses PostgreSQL as the `provider`. For CockroachDB, you need to edit the `datasource` block to use the `cockroachdb` provider instead: + +```prisma file=prisma/schema.prisma highlight=2;edit +datasource db { + provider = "cockroachdb" + url = env("DATABASE_URL") +} +``` + +The `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`. You now need to adjust the connection URL to point to your own database. + +

Connection URL

+ +The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. CockroachDB uses the PostgreSQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +```no-lines +postgresql://USER:PASSWORD@HOST:PORT/DATABASE?PARAMETERS +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password for your database user +- `PORT`: The port where your database server is running. The default for CockroachDB is `26257`. +- `DATABASE`: The name of the database +- `PARAMETERS`: Any additional connection parameters. See the CockroachDB documentation [here](https://www.cockroachlabs.com/docs/stable/connection-parameters.html#additional-connection-parameters). + +For a [CockroachDB Serverless](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart.html) or [Cockroach Dedicated](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart-trial-cluster) database hosted on [CockroachDB Cloud](https://www.cockroachlabs.com/get-started-cockroachdb/), the [connection URL](/orm/reference/connection-urls) looks similar to this: + +```bash file=.env +DATABASE_URL="postgresql://:@..cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=$HOME/.postgresql/root.crt&options=--" +``` + +To find your connection string on CockroachDB Cloud, click the 'Connect' button on the overview page for your database cluster, and select the 'Connection string' tab. + +For a [CockroachDB database hosted locally](https://www.cockroachlabs.com/docs/stable/secure-a-cluster.html), the [connection URL](/orm/reference/connection-urls) looks similar to this: + +```bash file=.env +DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable" +``` + +Your connection string is displayed as part of the welcome text when starting CockroachDB from the command line. + + + + + Installation + + + + Introspection + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-mysql.mdx new file mode 100644 index 0000000000..f589298506 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-mysql.mdx @@ -0,0 +1,88 @@ +--- +title: 'Connect your database' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +toc: false +--- + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Note that the default schema created by `prisma init` uses PostgreSQL, so you first need to switch the `provider` to `mysql`: + +```prisma file=prisma/schema.prisma highlight=2;edit +datasource db { + provider = "mysql" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: + +```bash file=.env +DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" +``` + +You now need to adjust the connection URL to point to your own database. + +

Connection URL

+ +The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +```no-lines +mysql://USER:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password for your database user +- `PORT`: The port where your database server is running (typically `3306` for MySQL) +- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) + +As an example, for a MySQL database hosted on AWS RDS, the [connection URL](/orm/reference/connection-urls) might look similar to this: + +```bash file=.env +DATABASE_URL="mysql://johndoe:XXX@mysql–instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb" +``` + +When running MySQL locally, your connection URL typically looks similar to this: + +```bash file=.env +DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" +``` + + + + + Installation + + + + Introspection + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-planetscale.mdx new file mode 100644 index 0000000000..49a4a95260 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-planetscale.mdx @@ -0,0 +1,118 @@ +--- +title: 'Connect your database' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +toc: false +--- + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Note that the default schema created by `prisma init` uses PostgreSQL as the `provider`. For PlanetScale, you need to edit the `datasource` block to use the `mysql` provider instead: + +```prisma file=prisma/schema.prisma highlight=2;edit +datasource db { + provider = "mysql" + url = env("DATABASE_URL") +} +``` + +You will also need to [set the relation mode type to `prisma`](/orm/prisma-schema/data-model/relations/relation-mode#emulate-relations-in-prisma-orm-with-the-prisma-relation-mode) in the `datasource` block: + +```prisma file=schema.prisma highlight=4;add +datasource db { + provider = "mysql" + url = env("DATABASE_URL") + relationMode = "prisma" +} +``` + +The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: + +```bash file=.env +DATABASE_URL="mysql://janedoe:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" +``` + +You now need to adjust the connection URL to point to your own database. + +

Connection URL

+ +The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. PlanetScale uses the MySQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +```no-lines +mysql://USER:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password for your database user +- `PORT`: The port where your database server is running (typically `3306` for MySQL) +- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) + +For a database hosted with PlanetScale, the [connection URL](/orm/reference/connection-urls) looks similar to this: + +```bash file=.env +DATABASE_URL="mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" +``` + +The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' to get the Prisma format for the connection URL. + +
+Alternative method: connecting using the PlanetScale CLI + +Alternatively, you can connect to your PlanetScale database server using the [PlanetScale CLI](https://docs.planetscale.com/reference/planetscale-environment-setup), and use a local connection URL. In this case the connection URL will look like this: + +```bash file=.env +DATABASE_URL="mysql://root@localhost:PORT/mydb" +``` + +To connect to your branch, use the following command: + +```terminal +pscale connect prisma-test branchname --port PORT +``` + +The `--port` flag can be omitted if you are using the default port `3306`. + +
+ + + + + Installation + + + + Introspection + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-postgresql.mdx new file mode 100644 index 0000000000..a398090ca2 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-postgresql.mdx @@ -0,0 +1,81 @@ +--- +title: 'Connect your database' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +toc: false +--- + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`: + +```bash file=.env +DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" +``` + +You now need to adjust the connection URL to point to your own database. + +

Connection URL

+ +The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +```no-lines +postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA +``` + +> **Note**: In most cases, you can use the [`postgres://` and `postgresql:// URI scheme designators interchangeably`](https://www.postgresql.org/docs/10/libpq-connect.html#id-1.7.3.8.3.6) - however, depending on how your database is hosted, you might need to be specific. + +If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. + +As an example, for a PostgreSQL database hosted on Heroku, the connection URL might look similar to this: + +```bash file=.env +DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" +``` + +When running PostgreSQL locally on macOS, your user and password as well as the database name _typically_ correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: + +```bash file=.env +DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" +``` + + + + + Installation + + + + Introspection + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-sqlserver.mdx new file mode 100644 index 0000000000..ab6c38a69a --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-sqlserver.mdx @@ -0,0 +1,59 @@ +--- +title: 'Connect your database' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +toc: false +--- + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "sqlserver" + url = env("DATABASE_URL") +} +``` + +The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema), the following example connection URL [uses SQL authentication](/orm/overview/databases/sql-server), but there are [other ways to format your connection URL](/orm/overview/databases/sql-server) + +```bash file=.env +DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=r@ndomP@$$w0rd;trustServerCertificate=true" +``` + +Adjust the connection URL to match your setup - see [Microsoft SQL Server connection URL](/orm/overview/databases/sql-server) for more information. + +> Make sure TCP/IP connections are enabled via [SQL Server Configuration Manager](https://docs.microsoft.com/en-us/sql/relational-databases/sql-server-configuration-manager) to avoid `No connection could be made because the target machine actively refused it. (os error 10061)` + + + + + Installation + + + + Introspection + + + \ No newline at end of file diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx new file mode 100644 index 0000000000..ef34ef13da --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx @@ -0,0 +1,92 @@ +--- +title: 'Connect your database' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: 'hidden-sidebar tech-switch' +toc: false +--- + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Note that the default schema created by `prisma init` uses PostgreSQL as the `provider`. For CockroachDB, you need to edit the `datasource` block to use the `cockroachdb` provider instead: + +```prisma file=prisma/schema.prisma highlight=2;edit +datasource db { + provider = "cockroachdb" + url = env("DATABASE_URL") +} +``` + +The `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`. You now need to adjust the connection URL to point to your own database. + +

Connection URL

+ +The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. CockroachDB uses the PostgreSQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +```no-lines +postgresql://USER:PASSWORD@HOST:PORT/DATABASE?PARAMETERS +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password for your database user +- `PORT`: The port where your database server is running. The default for CockroachDB is `26257`. +- `DATABASE`: The name of the database +- `PARAMETERS`: Any additional connection parameters. See the CockroachDB documentation [here](https://www.cockroachlabs.com/docs/stable/connection-parameters.html#additional-connection-parameters). + +For a [CockroachDB Serverless](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart.html) or [Cockroach Dedicated](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart-trial-cluster) database hosted on [CockroachDB Cloud](https://www.cockroachlabs.com/get-started-cockroachdb/), the [connection URL](/orm/reference/connection-urls) looks similar to this: + +```bash file=.env +DATABASE_URL="postgresql://:@..cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=$HOME/.postgresql/root.crt&options=--" +``` + +To find your connection string on CockroachDB Cloud, click the 'Connect' button on the overview page for your database cluster, and select the 'Connection string' tab. + +For a [CockroachDB database hosted locally](https://www.cockroachlabs.com/docs/stable/secure-a-cluster.html), the [connection URL](/orm/reference/connection-urls) looks similar to this: + +```bash file=.env +DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable" +``` + +Your connection string is displayed as part of the welcome text when starting CockroachDB from the command line. + + + + + Installation + + + + Introspection + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-mysql.mdx new file mode 100644 index 0000000000..17336c8a89 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-mysql.mdx @@ -0,0 +1,94 @@ +--- +title: 'Connect your database' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +toc: false +--- + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Note that the default schema created by `prisma init` uses PostgreSQL, so you first need to switch the `provider` to `mysql`: + +```prisma file=prisma/schema.prisma highlight=2;edit +datasource db { + provider = "mysql" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: + +```bash file=.env +DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" +``` + +You now need to adjust the connection URL to point to your own database. + +

Connection URL

+ +The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +```no-lines +mysql://USER:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password for your database user +- `PORT`: The port where your database server is running (typically `3306` for MySQL) +- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) + +As an example, for a MySQL database hosted on AWS RDS, the [connection URL](/orm/reference/connection-urls) might look similar to this: + +```bash file=.env +DATABASE_URL="mysql://johndoe:XXX@mysql–instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb" +``` + +When running MySQL locally, your connection URL typically looks similar to this: + +```bash file=.env +DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" +``` + + + + + + Installation + + + + Introspection + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-planetscale.mdx new file mode 100644 index 0000000000..678c70707d --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-planetscale.mdx @@ -0,0 +1,118 @@ +--- +title: 'Connect your database' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +sidebar_class_name: hidden-sidebar +toc: false +--- + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Note that the default schema created by `prisma init` uses PostgreSQL as the `provider`. For PlanetScale, you need to edit the `datasource` block to use the `mysql` provider instead: + +```prisma file=prisma/schema.prisma highlight=2;edit +datasource db { + provider = "mysql" + url = env("DATABASE_URL") +} +``` + +You will also need to [set the relation mode type to `prisma`](/orm/prisma-schema/data-model/relations/relation-mode#emulate-relations-in-prisma-orm-with-the-prisma-relation-mode) in the `datasource` block: + +```prisma file=schema.prisma highlight=4;add +datasource db { + provider = "mysql" + url = env("DATABASE_URL") + relationMode = "prisma" +} +``` + +The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: + +```bash file=.env +DATABASE_URL="mysql://janedoe:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" +``` + +You now need to adjust the connection URL to point to your own database. + +

Connection URL

+ +The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. PlanetScale uses the MySQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +```no-lines +mysql://USER:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password for your database user +- `PORT`: The port where your database server is running (typically `3306` for MySQL) +- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) + +For a database hosted with PlanetScale, the [connection URL](/orm/reference/connection-urls) looks similar to this: + +```bash file=.env +DATABASE_URL="mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" +``` + +The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' to get the Prisma format for the connection URL. + +
+Alternative method: connecting using the PlanetScale CLI + +Alternatively, you can connect to your PlanetScale database server using the [PlanetScale CLI](https://docs.planetscale.com/reference/planetscale-environment-setup), and use a local connection URL. In this case the connection URL will look like this: + +```bash file=.env +DATABASE_URL="mysql://root@localhost:PORT/mydb" +``` + +To connect to your branch, use the following command: + +```terminal +pscale connect prisma-test branchname --port PORT +``` + +The `--port` flag can be omitted if you are using the default port `3306`. + +
+ + + + + Installation + + + + Introspection + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-postgresql.mdx new file mode 100644 index 0000000000..9cc106b071 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-postgresql.mdx @@ -0,0 +1,80 @@ +--- +title: 'Connect your database' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +toc: false +--- + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`: + +```bash file=.env +DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" +``` + +You now need to adjust the connection URL to point to your own database. + +

Connection URL

+ +The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +```no-lines +postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA +``` + +> **Note**: In most cases, you can use the [`postgres://` and `postgresql:// URI scheme designators interchangeably`](https://www.postgresql.org/docs/10/libpq-connect.html#id-1.7.3.8.3.6) - however, depending on how your database is hosted, you might need to be specific. + +If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. + +As an example, for a PostgreSQL database hosted on Heroku, the connection URL might look similar to this: + +```bash file=.env +DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" +``` + +When running PostgreSQL locally on macOS, your user and password as well as the database name _typically_ correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: + +```bash file=.env +DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" +``` + + + + + Installation + + + + Introspection + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-sqlserver.mdx new file mode 100644 index 0000000000..98cab3a40a --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-sqlserver.mdx @@ -0,0 +1,60 @@ +--- +title: 'Connect your database' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +toc: false +sidebar_class_name: hidden-sidebar +--- + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + + +```prisma file=prisma/schema.prisma +datasource db { + provider = "sqlserver" + url = env("DATABASE_URL") +} +``` + +The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema), the following example connection URL [uses SQL authentication](/orm/overview/databases/sql-server), but there are [other ways to format your connection URL](/orm/overview/databases/sql-server) + +```bash file=.env +DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=r@ndomP@$$w0rd;trustServerCertificate=true" +``` + +Adjust the connection URL to match your setup - see [Microsoft SQL Server connection URL](/orm/overview/databases/sql-server) for more information. + +> Make sure TCP/IP connections are enabled via [SQL Server Configuration Manager](https://docs.microsoft.com/en-us/sql/relational-databases/sql-server-configuration-manager) to avoid `No connection could be made because the target machine actively refused it. (os error 10061)` + + + + + Installation + + + + Introspection + + + \ No newline at end of file diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database.mdx deleted file mode 100644 index c1e807a2a2..0000000000 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database.mdx +++ /dev/null @@ -1,520 +0,0 @@ ---- -title: 'Connect your database' -metaTitle: 'Connect your database' -metaDescription: 'Connect your database to your project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - - - -```prisma file=prisma/schema.prisma -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" -``` - -You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA -``` - -> **Note**: In most cases, you can use the [`postgres://` and `postgresql:// URI scheme designators interchangeably`](https://www.postgresql.org/docs/10/libpq-connect.html#id-1.7.3.8.3.6) - however, depending on how your database is hosted, you might need to be specific. - -If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. - -As an example, for a PostgreSQL database hosted on Heroku, the connection URL might look similar to this: - -```bash file=.env -DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" -``` - -When running PostgreSQL locally on macOS, your user and password as well as the database name _typically_ correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: - -```bash file=.env -DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" -``` - -
- - - -```prisma file=prisma/schema.prisma -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -Note that the default schema created by `prisma init` uses PostgreSQL, so you first need to switch the `provider` to `mysql`: - -```prisma file=prisma/schema.prisma highlight=2;edit -datasource db { - provider = "mysql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" -``` - -You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) - -As an example, for a MySQL database hosted on AWS RDS, the [connection URL](/orm/reference/connection-urls) might look similar to this: - -```bash file=.env -DATABASE_URL="mysql://johndoe:XXX@mysql–instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb" -``` - -When running MySQL locally, your connection URL typically looks similar to this: - -```bash file=.env -DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" -``` - -
- - - -```prisma file=prisma/schema.prisma -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -Note that the default schema created by `prisma init` uses PostgreSQL as the `provider`. For PlanetScale, you need to edit the `datasource` block to use the `mysql` provider instead: - -```prisma file=prisma/schema.prisma highlight=2;edit -datasource db { - provider = "mysql" - url = env("DATABASE_URL") -} -``` - -You will also need to [set the relation mode type to `prisma`](/orm/prisma-schema/data-model/relations/relation-mode#emulate-relations-in-prisma-orm-with-the-prisma-relation-mode) in the `datasource` block: - -```prisma file=schema.prisma highlight=4;add -datasource db { - provider = "mysql" - url = env("DATABASE_URL") - relationMode = "prisma" -} -``` - -The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="mysql://janedoe:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" -``` - -You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. PlanetScale uses the MySQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) - -For a database hosted with PlanetScale, the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" -``` - -The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' to get the Prisma format for the connection URL. - -
-Alternative method: connecting using the PlanetScale CLI - -Alternatively, you can connect to your PlanetScale database server using the [PlanetScale CLI](https://docs.planetscale.com/reference/planetscale-environment-setup), and use a local connection URL. In this case the connection URL will look like this: - -```bash file=.env -DATABASE_URL="mysql://root@localhost:PORT/mydb" -``` - -To connect to your branch, use the following command: - -```terminal -pscale connect prisma-test branchname --port PORT -``` - -The `--port` flag can be omitted if you are using the default port `3306`. - -
- -
- - - -```prisma file=prisma/schema.prisma -datasource db { - provider = "sqlserver" - url = env("DATABASE_URL") -} -``` - -The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema), the following example connection URL [uses SQL authentication](/orm/overview/databases/sql-server), but there are [other ways to format your connection URL](/orm/overview/databases/sql-server) - -```bash file=.env -DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=r@ndomP@$$w0rd;trustServerCertificate=true" -``` - -Adjust the connection URL to match your setup - see [Microsoft SQL Server connection URL](/orm/overview/databases/sql-server) for more information. - -> Make sure TCP/IP connections are enabled via [SQL Server Configuration Manager](https://docs.microsoft.com/en-us/sql/relational-databases/sql-server-configuration-manager) to avoid `No connection could be made because the target machine actively refused it. (os error 10061)` - - - - - -```prisma file=prisma/schema.prisma -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -Note that the default schema created by `prisma init` uses PostgreSQL as the `provider`. For CockroachDB, you need to edit the `datasource` block to use the `cockroachdb` provider instead: - -```prisma file=prisma/schema.prisma highlight=2;edit -datasource db { - provider = "cockroachdb" - url = env("DATABASE_URL") -} -``` - -The `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`. You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. CockroachDB uses the PostgreSQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?PARAMETERS -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running. The default for CockroachDB is `26257`. -- `DATABASE`: The name of the database -- `PARAMETERS`: Any additional connection parameters. See the CockroachDB documentation [here](https://www.cockroachlabs.com/docs/stable/connection-parameters.html#additional-connection-parameters). - -For a [CockroachDB Serverless](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart.html) or [Cockroach Dedicated](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart-trial-cluster) database hosted on [CockroachDB Cloud](https://www.cockroachlabs.com/get-started-cockroachdb/), the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="postgresql://:@..cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=$HOME/.postgresql/root.crt&options=--" -``` - -To find your connection string on CockroachDB Cloud, click the 'Connect' button on the overview page for your database cluster, and select the 'Connection string' tab. - -For a [CockroachDB database hosted locally](https://www.cockroachlabs.com/docs/stable/secure-a-cluster.html), the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable" -``` - -Your connection string is displayed as part of the welcome text when starting CockroachDB from the command line. - -
- - - - - - - Installation - - - - Introspection - - - - - - - - - - - - Installation - - - - Introspection - - - - - - - - - - - - Installation - - - - Introspection - - - - - - - - - - - - Installation - - - - Introspection - - - - - - - - - - - - Installation - - - - Introspection - - - - - - - - - - - - Installation - - - - Introspection - - - - - - - - - - - - Installation - - - - Introspection - - - - - - - - - - - - Installation - - - - Introspection - - - - - - - - - - - - Installation - - - - Introspection - - - - - - - - - - - - Installation - - - - Introspection - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-cockroachdb.mdx new file mode 100644 index 0000000000..632a929c10 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-cockroachdb.mdx @@ -0,0 +1,240 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Introspect your database with Prisma ORM + +For the purpose of this guide, we'll use a demo SQL schema with three tables: + +```sql no-lines +CREATE TABLE "User" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + name STRING(255), + email STRING(255) UNIQUE NOT NULL +); + +CREATE TABLE "Post" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + title STRING(255) UNIQUE NOT NULL, + "createdAt" TIMESTAMP NOT NULL DEFAULT now(), + content STRING, + published BOOLEAN NOT NULL DEFAULT false, + "authorId" INT8 NOT NULL, + FOREIGN KEY ("authorId") REFERENCES "User"(id) +); + +CREATE TABLE "Profile" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + bio STRING, + "userId" INT8 UNIQUE NOT NULL, + FOREIGN KEY ("userId") REFERENCES "User"(id) +); +``` + +> **Note**: Some fields are written in double quotes to ensure CockroachDB uses proper casing. If no double-quotes were used, CockroachDB would just read everything as _lowercase_ characters. + +
+Expand for a graphical overview of the tables + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------ | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | +| `name` | `STRING(255)` | No | No | No | - | +| `email` | `STRING(255)` | No | No | **✔️** | - | + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------ | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | +| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | +| `title` | `STRING(255)` | No | No | **✔️** | - | +| `content` | `STRING` | No | No | No | - | +| `published` | `BOOLEAN` | No | No | **✔️** | `false` | +| `authorId` | `INT8` | No | **✔️** | **✔️** | - | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | +| `bio` | `STRING` | No | No | No | - | +| `userId` | `INT8` | No | **✔️** | **✔️** | - | + +
+ + +As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. + +Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This commands reads the environment variable used to define the `url` in your `schema.prisma`, `DATABASE_URL`, that in our case is set in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. + +After the introspection is complete, your Prisma schema file was updated: + +![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) + +The data model now looks similar to this: + +```prisma file=prisma/schema.prisma +model Post { + id BigInt @id @default(autoincrement()) + title String @unique @db.String(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId BigInt + User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model Profile { + id BigInt @id @default(autoincrement()) + bio String? + userId BigInt @unique + User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model User { + id BigInt @id @default(autoincrement()) + name String? @db.String(255) + email String @unique @db.String(255) + Post Post[] + Profile Profile? +} +``` + +Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. + +Right now, there's a few minor "issues" with the data model: + +- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. +- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. + +These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). + +Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: + +```prisma file=prisma/schema.prisma highlight=8,15,22,23;edit +model Post { + id BigInt @id @default(autoincrement()) + title String @unique @db.String(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId BigInt + author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model Profile { + id BigInt @id @default(autoincrement()) + bio String? + userId BigInt @unique + user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model User { + id BigInt @id @default(autoincrement()) + name String? @db.String(255) + email String @unique @db.String(255) + posts Post[] + profile Profile? +} +``` + +In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. + +
+ Using custom model and field names + +Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. + +Assume you obtained the following model from introspection that's based on _snake_case_ notation: + +```prisma no-lines +model my_user { + user_id Int @id @default(sequence()) + first_name String? + last_name String @unique +} +``` + +If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: + +```ts no-lines +const user = await prisma.my_user.create({ + data: { + first_name: 'Alice', + last_name: 'Smith', + }, +}) +``` + +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): + +```prisma no-lines +model MyUser { + userId Int @id @default(sequence()) @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") + + @@map("my_user") +} +``` + +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts no-lines +const user = await prisma.myUser.create({ + data: { + firstName: 'Alice', + lastName: 'Smith', + }, +}) +``` + +Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. + +
+ + + + + Connect your database + + + + Baseline your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-mysql.mdx new file mode 100644 index 0000000000..b4c09083a0 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-mysql.mdx @@ -0,0 +1,242 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Introspect your database with Prisma ORM + +For the purpose of this guide, we'll use a demo SQL schema with three tables: + +```sql no-lines +CREATE TABLE User ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + name VARCHAR(255), + email VARCHAR(255) UNIQUE NOT NULL +); + +CREATE TABLE Post ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + title VARCHAR(255) NOT NULL, + createdAt TIMESTAMP NOT NULL DEFAULT now(), + content TEXT, + published BOOLEAN NOT NULL DEFAULT false, + authorId INTEGER NOT NULL, + FOREIGN KEY (authorId) REFERENCES User(id) +); + +CREATE TABLE Profile ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + bio TEXT, + userId INTEGER UNIQUE NOT NULL, + FOREIGN KEY (userId) REFERENCES User(id) +); +``` + +
+Expand for a graphical overview of the tables + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | +| `name` | `VARCHAR(255)` | No | No | No | - | +| `email` | `VARCHAR(255)` | No | No | **✔️** | - | + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | +| `createdAt` | `DATETIME(3)` | No | No | **✔️** | `now()` | +| `title` | `VARCHAR(255)` | No | No | **✔️** | - | +| `content` | `TEXT` | No | No | No | - | +| `published` | `BOOLEAN` | No | No | **✔️** | `false` | +| `authorId` | `INTEGER` | No | **✔️** | **✔️** | `false` | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | +| `bio` | `TEXT` | No | No | No | - | +| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | + +
+ +As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. + +Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. + +After the introspection is complete, your Prisma schema file was updated: + +![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) + +The data model now looks similar to this (note that the fields on the models have been reordered for better readability): + +```prisma file=prisma/schema.prisma +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(0) + content String? @db.Text + published Boolean @default(false) + authorId Int + User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Post_ibfk_1") + + @@index([authorId], map: "authorId") +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? @db.Text + userId Int @unique(map: "userId") + User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Profile_ibfk_1") +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique(map: "email") @db.VarChar(255) + Post Post[] + Profile Profile? +} +``` + + + +Refer to the [Prisma schema reference](/orm/reference/prisma-schema-reference) for detailed information about the schema definition. + + + +Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. + +Right now, there's a few minor "issues" with the data model: + +- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. +- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. + +These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). + +Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: + +```prisma file=prisma/schema.prisma highlight=8,17,24,25;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(0) + content String? @db.Text + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Post_ibfk_1") + + @@index([authorId], map: "authorId") +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? @db.Text + userId Int @unique(map: "userId") + user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Profile_ibfk_1") +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique(map: "email") @db.VarChar(255) + posts Post[] + profile Profile? +} +``` + +In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. + +Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. + +Assume you obtained the following model from introspection that's based on _snake_case_ notation: + +```prisma no-lines +model my_user { + user_id Int @id @default(autoincrement()) + first_name String? + last_name String @unique +} +``` + +If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: + +```ts no-lines +const user = await prisma.my_user.create({ + data: { + first_name: 'Alice', + last_name: 'Smith', + }, +}) +``` + +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): + +```prisma no-lines +model MyUser { + userId Int @id @default(autoincrement()) @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") + + @@map("my_user") +} +``` + +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts no-lines +const user = await prisma.myUser.create({ + data: { + firstName: 'Alice', + lastName: 'Smith', + }, +}) +``` + +Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. + + + + + Connect your database + + + + Baseline your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-planetscale.mdx new file mode 100644 index 0000000000..556b3a2b6e --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-planetscale.mdx @@ -0,0 +1,258 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Introspect your database with Prisma ORM + +For the purpose of this guide, we'll use a demo SQL schema with three tables: + +```sql no-lines +CREATE TABLE `Post` ( + `id` int NOT NULL AUTO_INCREMENT, + `createdAt` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updatedAt` datetime(3) NOT NULL, + `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, + `content` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `published` tinyint(1) NOT NULL DEFAULT '0', + `authorId` int NOT NULL, + PRIMARY KEY (`id`), + KEY `Post_authorId_idx` (`authorId`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE `Profile` ( + `id` int NOT NULL AUTO_INCREMENT, + `bio` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `userId` int NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `Profile_userId_key` (`userId`), + KEY `Profile_userId_idx` (`userId`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE `User` ( + `id` int NOT NULL AUTO_INCREMENT, + `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, + `name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `User_email_key` (`email`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +``` + +
+Expand for a graphical overview of the tables + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | +| `createdAt` | `datetime(3)` | No | No | **✔️** | `now()` | +| `updatedAt` | `datetime(3)` | No | No | **✔️** | | +| `title` | `varchar(255)` | No | No | **✔️** | - | +| `content` | `varchar(191)` | No | No | No | - | +| `published` | `tinyint(1)` | No | No | **✔️** | `false` | +| `authorId` | `int` | No | No | **✔️** | - | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | +| `bio` | `varchar(191)` | No | No | No | - | +| `userId` | `int` | No | No | **✔️** | - | + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | +| `name` | `varchar(191)` | No | No | No | - | +| `email` | `varchar(191)` | No | No | **✔️** | - | + +
+ +As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. + +Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. + +After the introspection is complete, your Prisma schema file was updated: + +![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) + +The data model now looks similar to this: + +```prisma file=prisma/schema.prisma +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime + title String @db.VarChar(255) + content String? + published Boolean @default(false) + authorId Int + + @@index([authorId]) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + + @@index([userId]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? +} +``` + + + +Refer to the [Prisma schema reference](/orm/reference/prisma-schema-reference) for detailed information about the schema definition. + + + +Prisma's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. + +You will then need to add in any missing relations between your data using [relation fields](/orm/prisma-schema/data-model/relations#relation-fields): + +```prisma file=prisma/schema.prisma highlight=8,17,27,28;add +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int + + @@index([authorId]) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique + + @@index([userId]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +After this, run introspection on your database for a second time: + +```terminal copy +npx prisma db pull +``` + +Prisma Migrate will now keep the manually added relation fields. + +Because relation fields are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database. + +In this example, the database schema follows the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models. This optimizes the ergonomics of the generated Prisma Client API. + +
+ Using custom model and field names + +Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. + +Assume you obtained the following model from introspection that's based on _snake_case_ notation: + +```prisma no-lines +model my_user { + user_id Int @id @default(autoincrement()) + first_name String? + last_name String @unique +} +``` + +If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: + +```ts no-lines +const user = await prisma.my_user.create({ + data: { + first_name: 'Alice', + last_name: 'Smith', + }, +}) +``` + +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): + +```prisma no-lines +model MyUser { + userId Int @id @default(autoincrement()) @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") + + @@map("my_user") +} +``` + +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts no-lines +const user = await prisma.myUser.create({ + data: { + firstName: 'Alice', + lastName: 'Smith', + }, +}) +``` + +Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. + +
+ + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-postgresql.mdx new file mode 100644 index 0000000000..f7916b2955 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-postgresql.mdx @@ -0,0 +1,239 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Introspect your database with Prisma ORM + +For the purpose of this guide, we'll use a demo SQL schema with three tables: + +```sql no-lines +CREATE TABLE "public"."User" ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(255), + email VARCHAR(255) UNIQUE NOT NULL +); + +CREATE TABLE "public"."Post" ( + id SERIAL PRIMARY KEY NOT NULL, + title VARCHAR(255) NOT NULL, + "createdAt" TIMESTAMP NOT NULL DEFAULT now(), + content TEXT, + published BOOLEAN NOT NULL DEFAULT false, + "authorId" INTEGER NOT NULL, + FOREIGN KEY ("authorId") REFERENCES "public"."User"(id) +); + +CREATE TABLE "public"."Profile" ( + id SERIAL PRIMARY KEY NOT NULL, + bio TEXT, + "userId" INTEGER UNIQUE NOT NULL, + FOREIGN KEY ("userId") REFERENCES "public"."User"(id) +); +``` + +> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes were used, PostgreSQL would just read everything as _lowercase_ characters. + +
+Expand for a graphical overview of the tables + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | +| `name` | `VARCHAR(255)` | No | No | No | - | +| `email` | `VARCHAR(255)` | No | No | **✔️** | - | + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | +| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | +| `title` | `VARCHAR(255)` | No | No | **✔️** | - | +| `content` | `TEXT` | No | No | No | - | +| `published` | `BOOLEAN` | No | No | **✔️** | `false` | +| `authorId` | `INTEGER` | No | **✔️** | **✔️** | - | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | +| `bio` | `TEXT` | No | No | No | - | +| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | + +
+ +As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. + +Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a data model in your Prisma schema. + +After the introspection is complete, your Prisma schema file was updated: + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +The data model now looks similar to this (note that the fields on the models have been reordered for better readability): + +```prisma file=prisma/schema.prisma +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + Post Post[] + Profile Profile? +} +``` + +Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. + +Right now, there's a few minor "issues" with the data model: + +- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. +- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. + +These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). + +Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: + +```prisma file=prisma/schema.prisma highlight=8,15,22,23;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + posts Post[] + profile Profile? +} +``` + +In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. + +
+ Using custom model and field names + +Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. + +Assume you obtained the following model from introspection that's based on _snake_case_ notation: + +```prisma no-lines +model my_user { + user_id Int @id @default(autoincrement()) + first_name String? + last_name String @unique +} +``` + +If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: + +```ts no-lines +const user = await prisma.my_user.create({ + data: { + first_name: 'Alice', + last_name: 'Smith', + }, +}) +``` + +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): + +```prisma no-lines +model MyUser { + userId Int @id @default(autoincrement()) @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") + + @@map("my_user") +} +``` + +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts no-lines +const user = await prisma.myUser.create({ + data: { + firstName: 'Alice', + lastName: 'Smith', + }, +}) +``` + +Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. + +
+ + + + + Connect your database + + + + Baseline your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-sqlserver.mdx new file mode 100644 index 0000000000..ffa176a8c8 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-sqlserver.mdx @@ -0,0 +1,246 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Introspect your database with Prisma ORM + +For the purpose of this guide, we'll use a demo SQL schema with three tables: + +```sql no-lines +CREATE TABLE [dbo].[Post] ( + [id] INT NOT NULL IDENTITY(1,1), + [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, + [updatedAt] DATETIME2 NOT NULL, + [title] VARCHAR(255) NOT NULL, + [content] NVARCHAR(1000), + [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, + [authorId] INT NOT NULL, + CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) +); + +CREATE TABLE [dbo].[Profile] ( + [id] INT NOT NULL IDENTITY(1,1), + [bio] NVARCHAR(1000), + [userId] INT NOT NULL, + CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), + CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) +); + +CREATE TABLE [dbo].[User] ( + [id] INT NOT NULL IDENTITY(1,1), + [email] NVARCHAR(1000) NOT NULL, + [name] NVARCHAR(1000), + CONSTRAINT [User_pkey] PRIMARY KEY ([id]), + CONSTRAINT [User_email_key] UNIQUE ([email]) +); + +ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; + +ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; +``` + +
+Expand for a graphical overview of the tables + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | +| `name` | `NVARCHAR(1000)` | No | No | No | - | +| `email` | `NVARCHAR(1000)` | No | No | **✔️** | - | + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | +| `createdAt` | `DATETIME2` | No | No | **✔️** | `now()` | +| `updatedAt` | `DATETIME2` | No | No | **✔️** | | +| `title` | `VARCHAR(255)` | No | No | **✔️** | - | +| `content` | `NVARCHAR(1000)` | No | No | No | - | +| `published` | `BIT` | No | No | **✔️** | `false` | +| `authorId` | `INT` | No | **✔️** | **✔️** | - | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | +| `bio` | `NVARCHAR(1000)` | No | No | No | - | +| `userId` | `INT` | No | **✔️** | **✔️** | - | + +
+ +As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. + +Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. + +After the introspection is complete, your Prisma schema file was updated: + +![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) + +The data model now looks similar to this (note that the fields on the models have been reordered for better readability): + +```prisma file=prisma/schema.prisma +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + User User @relation(fields: [authorId], references: [id]) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + User User @relation(fields: [userId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + Post Post[] + Profile Profile? +} +``` + +Prisma's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. + +Right now, there's a few minor "issues" with the data model: + +- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. +- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. + +These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). + +Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: + +```prisma file=prisma/schema.prisma highlight=7,14,22,23;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique +} + +model User { + id Int @id @default(autoincrement()) + email String @unique @db.VarChar(255) + name String? @db.VarChar(255) + posts Post[] + profile Profile? +} +``` + +In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. + +
+ Using custom model and field names + +Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. + +Assume you obtained the following model from introspection that's based on _snake_case_ notation: + +```prisma no-lines +model my_user { + user_id Int @id @default(autoincrement()) + first_name String? + last_name String @unique +} +``` + +If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: + +```ts no-lines +const user = await prisma.my_user.create({ + data: { + first_name: 'Alice', + last_name: 'Smith', + }, +}) +``` + +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): + +```prisma no-lines +model MyUser { + userId Int @id @default(autoincrement()) @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") + + @@map("my_user") +} +``` + +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts no-lines +const user = await prisma.myUser.create({ + data: { + firstName: 'Alice', + lastName: 'Smith', + }, +}) +``` + +Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. + +
+ + + + + Connect your database + + + + Baseline your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-cockroachdb.mdx new file mode 100644 index 0000000000..5bb0e99878 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-cockroachdb.mdx @@ -0,0 +1,239 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Introspect your database with Prisma ORM + +For the purpose of this guide, we'll use a demo SQL schema with three tables: + +```sql no-lines +CREATE TABLE "User" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + name STRING(255), + email STRING(255) UNIQUE NOT NULL +); + +CREATE TABLE "Post" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + title STRING(255) UNIQUE NOT NULL, + "createdAt" TIMESTAMP NOT NULL DEFAULT now(), + content STRING, + published BOOLEAN NOT NULL DEFAULT false, + "authorId" INT8 NOT NULL, + FOREIGN KEY ("authorId") REFERENCES "User"(id) +); + +CREATE TABLE "Profile" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + bio STRING, + "userId" INT8 UNIQUE NOT NULL, + FOREIGN KEY ("userId") REFERENCES "User"(id) +); +``` + +> **Note**: Some fields are written in double quotes to ensure CockroachDB uses proper casing. If no double-quotes were used, CockroachDB would just read everything as _lowercase_ characters. + +
+Expand for a graphical overview of the tables + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------ | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | +| `name` | `STRING(255)` | No | No | No | - | +| `email` | `STRING(255)` | No | No | **✔️** | - | + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------ | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | +| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | +| `title` | `STRING(255)` | No | No | **✔️** | - | +| `content` | `STRING` | No | No | No | - | +| `published` | `BOOLEAN` | No | No | **✔️** | `false` | +| `authorId` | `INT8` | No | **✔️** | **✔️** | - | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | +| `bio` | `STRING` | No | No | No | - | +| `userId` | `INT8` | No | **✔️** | **✔️** | - | + +
+ +As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. + +Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This commands reads the environment variable used to define the `url` in your `schema.prisma`, `DATABASE_URL`, that in our case is set in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. + +After the introspection is complete, your Prisma schema file was updated: + +![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) + +The data model now looks similar to this: + +```prisma file=prisma/schema.prisma +model Post { + id BigInt @id @default(autoincrement()) + title String @unique @db.String(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId BigInt + User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model Profile { + id BigInt @id @default(autoincrement()) + bio String? + userId BigInt @unique + User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model User { + id BigInt @id @default(autoincrement()) + name String? @db.String(255) + email String @unique @db.String(255) + Post Post[] + Profile Profile? +} +``` + +Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. + +Right now, there's a few minor "issues" with the data model: + +- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. +- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. + +These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). + +Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: + +```prisma file=prisma/schema.prisma highlight=8,15,22,23;edit +model Post { + id BigInt @id @default(autoincrement()) + title String @unique @db.String(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId BigInt + author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model Profile { + id BigInt @id @default(autoincrement()) + bio String? + userId BigInt @unique + user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model User { + id BigInt @id @default(autoincrement()) + name String? @db.String(255) + email String @unique @db.String(255) + posts Post[] + profile Profile? +} +``` + +In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. + +
+ Using custom model and field names + +Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. + +Assume you obtained the following model from introspection that's based on _snake_case_ notation: + +```prisma no-lines +model my_user { + user_id Int @id @default(sequence()) + first_name String? + last_name String @unique +} +``` + +If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: + +```ts no-lines +const user = await prisma.my_user.create({ + data: { + first_name: 'Alice', + last_name: 'Smith', + }, +}) +``` + +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): + +```prisma no-lines +model MyUser { + userId Int @id @default(sequence()) @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") + + @@map("my_user") +} +``` + +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts no-lines +const user = await prisma.myUser.create({ + data: { + firstName: 'Alice', + lastName: 'Smith', + }, +}) +``` + +Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. + +
+ + + + + Connect your database + + + + Baseline your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-mysql.mdx new file mode 100644 index 0000000000..f68a39e2cd --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-mysql.mdx @@ -0,0 +1,242 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Introspect your database with Prisma ORM + +For the purpose of this guide, we'll use a demo SQL schema with three tables: + +```sql no-lines +CREATE TABLE User ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + name VARCHAR(255), + email VARCHAR(255) UNIQUE NOT NULL +); + +CREATE TABLE Post ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + title VARCHAR(255) NOT NULL, + createdAt TIMESTAMP NOT NULL DEFAULT now(), + content TEXT, + published BOOLEAN NOT NULL DEFAULT false, + authorId INTEGER NOT NULL, + FOREIGN KEY (authorId) REFERENCES User(id) +); + +CREATE TABLE Profile ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + bio TEXT, + userId INTEGER UNIQUE NOT NULL, + FOREIGN KEY (userId) REFERENCES User(id) +); +``` + +
+Expand for a graphical overview of the tables + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | +| `name` | `VARCHAR(255)` | No | No | No | - | +| `email` | `VARCHAR(255)` | No | No | **✔️** | - | + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | +| `createdAt` | `DATETIME(3)` | No | No | **✔️** | `now()` | +| `title` | `VARCHAR(255)` | No | No | **✔️** | - | +| `content` | `TEXT` | No | No | No | - | +| `published` | `BOOLEAN` | No | No | **✔️** | `false` | +| `authorId` | `INTEGER` | No | **✔️** | **✔️** | `false` | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | +| `bio` | `TEXT` | No | No | No | - | +| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | + +
+ +As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. + +Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. + +After the introspection is complete, your Prisma schema file was updated: + +![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) + +The data model now looks similar to this (note that the fields on the models have been reordered for better readability): + +```prisma file=prisma/schema.prisma +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(0) + content String? @db.Text + published Boolean @default(false) + authorId Int + User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Post_ibfk_1") + + @@index([authorId], map: "authorId") +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? @db.Text + userId Int @unique(map: "userId") + User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Profile_ibfk_1") +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique(map: "email") @db.VarChar(255) + Post Post[] + Profile Profile? +} +``` + + + +Refer to the [Prisma schema reference](/orm/reference/prisma-schema-reference) for detailed information about the schema definition. + + + +Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. + +Right now, there's a few minor "issues" with the data model: + +- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. +- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. + +These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). + +Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: + +```prisma file=prisma/schema.prisma highlight=8,17,24,25;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(0) + content String? @db.Text + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Post_ibfk_1") + + @@index([authorId], map: "authorId") +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? @db.Text + userId Int @unique(map: "userId") + user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Profile_ibfk_1") +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique(map: "email") @db.VarChar(255) + posts Post[] + profile Profile? +} +``` + +In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. + +Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. + +Assume you obtained the following model from introspection that's based on _snake_case_ notation: + +```prisma no-lines +model my_user { + user_id Int @id @default(autoincrement()) + first_name String? + last_name String @unique +} +``` + +If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: + +```ts no-lines +const user = await prisma.my_user.create({ + data: { + first_name: 'Alice', + last_name: 'Smith', + }, +}) +``` + +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): + +```prisma no-lines +model MyUser { + userId Int @id @default(autoincrement()) @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") + + @@map("my_user") +} +``` + +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts no-lines +const user = await prisma.myUser.create({ + data: { + firstName: 'Alice', + lastName: 'Smith', + }, +}) +``` + +Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. + + + + + Connect your database + + + + Baseline your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-planetscale.mdx new file mode 100644 index 0000000000..e372ec576a --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-planetscale.mdx @@ -0,0 +1,258 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Introspect your database with Prisma ORM + +For the purpose of this guide, we'll use a demo SQL schema with three tables: + +```sql no-lines +CREATE TABLE `Post` ( + `id` int NOT NULL AUTO_INCREMENT, + `createdAt` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updatedAt` datetime(3) NOT NULL, + `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, + `content` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `published` tinyint(1) NOT NULL DEFAULT '0', + `authorId` int NOT NULL, + PRIMARY KEY (`id`), + KEY `Post_authorId_idx` (`authorId`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE `Profile` ( + `id` int NOT NULL AUTO_INCREMENT, + `bio` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `userId` int NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `Profile_userId_key` (`userId`), + KEY `Profile_userId_idx` (`userId`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE `User` ( + `id` int NOT NULL AUTO_INCREMENT, + `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, + `name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `User_email_key` (`email`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +``` + +
+Expand for a graphical overview of the tables + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | +| `createdAt` | `datetime(3)` | No | No | **✔️** | `now()` | +| `updatedAt` | `datetime(3)` | No | No | **✔️** | | +| `title` | `varchar(255)` | No | No | **✔️** | - | +| `content` | `varchar(191)` | No | No | No | - | +| `published` | `tinyint(1)` | No | No | **✔️** | `false` | +| `authorId` | `int` | No | No | **✔️** | - | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | +| `bio` | `varchar(191)` | No | No | No | - | +| `userId` | `int` | No | No | **✔️** | - | + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | +| `name` | `varchar(191)` | No | No | No | - | +| `email` | `varchar(191)` | No | No | **✔️** | - | + +
+ +As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. + +Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. + +After the introspection is complete, your Prisma schema file was updated: + +![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) + +The data model now looks similar to this: + +```prisma file=prisma/schema.prisma +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime + title String @db.VarChar(255) + content String? + published Boolean @default(false) + authorId Int + + @@index([authorId]) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + + @@index([userId]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? +} +``` + + + +Refer to the [Prisma schema reference](/orm/reference/prisma-schema-reference) for detailed information about the schema definition. + + + +Prisma's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. + +You will then need to add in any missing relations between your data using [relation fields](/orm/prisma-schema/data-model/relations#relation-fields): + +```prisma file=prisma/schema.prisma highlight=8,17,27,28;add +model Post { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime + title String @db.VarChar(255) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int + + @@index([authorId]) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique + + @@index([userId]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} +``` + +After this, run introspection on your database for a second time: + +```terminal copy +npx prisma db pull +``` + +Prisma Migrate will now keep the manually added relation fields. + +Because relation fields are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database. + +In this example, the database schema follows the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models. This optimizes the ergonomics of the generated Prisma Client API. + +
+ Using custom model and field names + +Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. + +Assume you obtained the following model from introspection that's based on _snake_case_ notation: + +```prisma no-lines +model my_user { + user_id Int @id @default(autoincrement()) + first_name String? + last_name String @unique +} +``` + +If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: + +```ts no-lines +const user = await prisma.my_user.create({ + data: { + first_name: 'Alice', + last_name: 'Smith', + }, +}) +``` + +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): + +```prisma no-lines +model MyUser { + userId Int @id @default(autoincrement()) @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") + + @@map("my_user") +} +``` + +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts no-lines +const user = await prisma.myUser.create({ + data: { + firstName: 'Alice', + lastName: 'Smith', + }, +}) +``` + +Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. + +
+ + + + + Connect your database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-postgresql.mdx new file mode 100644 index 0000000000..5a5ab2b957 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-postgresql.mdx @@ -0,0 +1,238 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + + +## Introspect your database with Prisma ORM + +For the purpose of this guide, we'll use a demo SQL schema with three tables: + +```sql no-lines +CREATE TABLE "public"."User" ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(255), + email VARCHAR(255) UNIQUE NOT NULL +); + +CREATE TABLE "public"."Post" ( + id SERIAL PRIMARY KEY NOT NULL, + title VARCHAR(255) NOT NULL, + "createdAt" TIMESTAMP NOT NULL DEFAULT now(), + content TEXT, + published BOOLEAN NOT NULL DEFAULT false, + "authorId" INTEGER NOT NULL, + FOREIGN KEY ("authorId") REFERENCES "public"."User"(id) +); + +CREATE TABLE "public"."Profile" ( + id SERIAL PRIMARY KEY NOT NULL, + bio TEXT, + "userId" INTEGER UNIQUE NOT NULL, + FOREIGN KEY ("userId") REFERENCES "public"."User"(id) +); +``` + +> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes were used, PostgreSQL would just read everything as _lowercase_ characters. + +
+Expand for a graphical overview of the tables + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | +| `name` | `VARCHAR(255)` | No | No | No | - | +| `email` | `VARCHAR(255)` | No | No | **✔️** | - | + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | +| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | +| `title` | `VARCHAR(255)` | No | No | **✔️** | - | +| `content` | `TEXT` | No | No | No | - | +| `published` | `BOOLEAN` | No | No | **✔️** | `false` | +| `authorId` | `INTEGER` | No | **✔️** | **✔️** | - | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | +| `bio` | `TEXT` | No | No | No | - | +| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | + +
+ +As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. + +Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a data model in your Prisma schema. + +After the introspection is complete, your Prisma schema file was updated: + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +The data model now looks similar to this (note that the fields on the models have been reordered for better readability): + +```prisma file=prisma/schema.prisma +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + Post Post[] + Profile Profile? +} +``` + +Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. + +Right now, there's a few minor "issues" with the data model: + +- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. +- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. + +These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). + +Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: + +```prisma file=prisma/schema.prisma highlight=8,15,22,23;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + posts Post[] + profile Profile? +} +``` + +In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. + +
+ Using custom model and field names + +Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. + +Assume you obtained the following model from introspection that's based on _snake_case_ notation: + +```prisma no-lines +model my_user { + user_id Int @id @default(autoincrement()) + first_name String? + last_name String @unique +} +``` + +If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: + +```ts no-lines +const user = await prisma.my_user.create({ + data: { + first_name: 'Alice', + last_name: 'Smith', + }, +}) +``` + +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): + +```prisma no-lines +model MyUser { + userId Int @id @default(autoincrement()) @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") + + @@map("my_user") +} +``` + +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts no-lines +const user = await prisma.myUser.create({ + data: { + firstName: 'Alice', + lastName: 'Smith', + }, +}) +``` + +Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. + +
+ + + + + Connect your database + + + + Baseline your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-sqlserver.mdx new file mode 100644 index 0000000000..fd1561d7df --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-sqlserver.mdx @@ -0,0 +1,246 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Introspect your database with Prisma ORM + +For the purpose of this guide, we'll use a demo SQL schema with three tables: + +```sql no-lines +CREATE TABLE [dbo].[Post] ( + [id] INT NOT NULL IDENTITY(1,1), + [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, + [updatedAt] DATETIME2 NOT NULL, + [title] VARCHAR(255) NOT NULL, + [content] NVARCHAR(1000), + [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, + [authorId] INT NOT NULL, + CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) +); + +CREATE TABLE [dbo].[Profile] ( + [id] INT NOT NULL IDENTITY(1,1), + [bio] NVARCHAR(1000), + [userId] INT NOT NULL, + CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), + CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) +); + +CREATE TABLE [dbo].[User] ( + [id] INT NOT NULL IDENTITY(1,1), + [email] NVARCHAR(1000) NOT NULL, + [name] NVARCHAR(1000), + CONSTRAINT [User_pkey] PRIMARY KEY ([id]), + CONSTRAINT [User_email_key] UNIQUE ([email]) +); + +ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; + +ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; +``` + +
+Expand for a graphical overview of the tables + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | +| `name` | `NVARCHAR(1000)` | No | No | No | - | +| `email` | `NVARCHAR(1000)` | No | No | **✔️** | - | + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | +| `createdAt` | `DATETIME2` | No | No | **✔️** | `now()` | +| `updatedAt` | `DATETIME2` | No | No | **✔️** | | +| `title` | `VARCHAR(255)` | No | No | **✔️** | - | +| `content` | `NVARCHAR(1000)` | No | No | No | - | +| `published` | `BIT` | No | No | **✔️** | `false` | +| `authorId` | `INT` | No | **✔️** | **✔️** | - | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | +| `bio` | `NVARCHAR(1000)` | No | No | No | - | +| `userId` | `INT` | No | **✔️** | **✔️** | - | + +
+ +As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. + +Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. + +After the introspection is complete, your Prisma schema file was updated: + +![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) + +The data model now looks similar to this (note that the fields on the models have been reordered for better readability): + +```prisma file=prisma/schema.prisma +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + User User @relation(fields: [authorId], references: [id]) +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + User User @relation(fields: [userId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + Post Post[] + Profile Profile? +} +``` + +Prisma's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. + +Right now, there's a few minor "issues" with the data model: + +- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. +- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. + +These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). + +Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: + +```prisma file=prisma/schema.prisma highlight=7,14,22,23;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique +} + +model User { + id Int @id @default(autoincrement()) + email String @unique @db.VarChar(255) + name String? @db.VarChar(255) + posts Post[] + profile Profile? +} +``` + +In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. + +
+ Using custom model and field names + +Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. + +Assume you obtained the following model from introspection that's based on _snake_case_ notation: + +```prisma no-lines +model my_user { + user_id Int @id @default(autoincrement()) + first_name String? + last_name String @unique +} +``` + +If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: + +```ts no-lines +const user = await prisma.my_user.create({ + data: { + first_name: 'Alice', + last_name: 'Smith', + }, +}) +``` + +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): + +```prisma no-lines +model MyUser { + userId Int @id @default(autoincrement()) @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") + + @@map("my_user") +} +``` + +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts no-lines +const user = await prisma.myUser.create({ + data: { + firstName: 'Alice', + lastName: 'Smith', + }, +}) +``` + +Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. + +
+ + + + + Connect your database + + + + Baseline your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection.mdx deleted file mode 100644 index 972bda81cc..0000000000 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection.mdx +++ /dev/null @@ -1,1329 +0,0 @@ ---- -title: 'Introspection' -metaTitle: 'Introspection' -metaDescription: 'Introspection your database with Prisma' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true ---- - -## Introspect your database with Prisma ORM - - - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE "public"."User" ( - id SERIAL PRIMARY KEY NOT NULL, - name VARCHAR(255), - email VARCHAR(255) UNIQUE NOT NULL -); - -CREATE TABLE "public"."Post" ( - id SERIAL PRIMARY KEY NOT NULL, - title VARCHAR(255) NOT NULL, - "createdAt" TIMESTAMP NOT NULL DEFAULT now(), - content TEXT, - published BOOLEAN NOT NULL DEFAULT false, - "authorId" INTEGER NOT NULL, - FOREIGN KEY ("authorId") REFERENCES "public"."User"(id) -); - -CREATE TABLE "public"."Profile" ( - id SERIAL PRIMARY KEY NOT NULL, - bio TEXT, - "userId" INTEGER UNIQUE NOT NULL, - FOREIGN KEY ("userId") REFERENCES "public"."User"(id) -); -``` - -> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes were used, PostgreSQL would just read everything as _lowercase_ characters. - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `VARCHAR(255)` | No | No | No | - | -| `email` | `VARCHAR(255)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `TEXT` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INTEGER` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `TEXT` | No | No | No | - | -| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | - -
- -
- - - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE User ( - id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, - name VARCHAR(255), - email VARCHAR(255) UNIQUE NOT NULL -); - -CREATE TABLE Post ( - id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, - title VARCHAR(255) NOT NULL, - createdAt TIMESTAMP NOT NULL DEFAULT now(), - content TEXT, - published BOOLEAN NOT NULL DEFAULT false, - authorId INTEGER NOT NULL, - FOREIGN KEY (authorId) REFERENCES User(id) -); - -CREATE TABLE Profile ( - id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, - bio TEXT, - userId INTEGER UNIQUE NOT NULL, - FOREIGN KEY (userId) REFERENCES User(id) -); -``` - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `VARCHAR(255)` | No | No | No | - | -| `email` | `VARCHAR(255)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `DATETIME(3)` | No | No | **✔️** | `now()` | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `TEXT` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INTEGER` | No | **✔️** | **✔️** | `false` | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `TEXT` | No | No | No | - | -| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | - -
- -
- - - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE `Post` ( - `id` int NOT NULL AUTO_INCREMENT, - `createdAt` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), - `updatedAt` datetime(3) NOT NULL, - `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, - `content` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - `published` tinyint(1) NOT NULL DEFAULT '0', - `authorId` int NOT NULL, - PRIMARY KEY (`id`), - KEY `Post_authorId_idx` (`authorId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - -CREATE TABLE `Profile` ( - `id` int NOT NULL AUTO_INCREMENT, - `bio` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - `userId` int NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `Profile_userId_key` (`userId`), - KEY `Profile_userId_idx` (`userId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - -CREATE TABLE `User` ( - `id` int NOT NULL AUTO_INCREMENT, - `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, - `name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `User_email_key` (`email`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -``` - -
-Expand for a graphical overview of the tables - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `datetime(3)` | No | No | **✔️** | `now()` | -| `updatedAt` | `datetime(3)` | No | No | **✔️** | | -| `title` | `varchar(255)` | No | No | **✔️** | - | -| `content` | `varchar(191)` | No | No | No | - | -| `published` | `tinyint(1)` | No | No | **✔️** | `false` | -| `authorId` | `int` | No | No | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `varchar(191)` | No | No | No | - | -| `userId` | `int` | No | No | **✔️** | - | - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `varchar(191)` | No | No | No | - | -| `email` | `varchar(191)` | No | No | **✔️** | - | - -
- -
- - - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE [dbo].[Post] ( - [id] INT NOT NULL IDENTITY(1,1), - [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, - [updatedAt] DATETIME2 NOT NULL, - [title] VARCHAR(255) NOT NULL, - [content] NVARCHAR(1000), - [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, - [authorId] INT NOT NULL, - CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) -); - -CREATE TABLE [dbo].[Profile] ( - [id] INT NOT NULL IDENTITY(1,1), - [bio] NVARCHAR(1000), - [userId] INT NOT NULL, - CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), - CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) -); - -CREATE TABLE [dbo].[User] ( - [id] INT NOT NULL IDENTITY(1,1), - [email] NVARCHAR(1000) NOT NULL, - [name] NVARCHAR(1000), - CONSTRAINT [User_pkey] PRIMARY KEY ([id]), - CONSTRAINT [User_email_key] UNIQUE ([email]) -); - -ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; - -ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; -``` - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `NVARCHAR(1000)` | No | No | No | - | -| `email` | `NVARCHAR(1000)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `DATETIME2` | No | No | **✔️** | `now()` | -| `updatedAt` | `DATETIME2` | No | No | **✔️** | | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `NVARCHAR(1000)` | No | No | No | - | -| `published` | `BIT` | No | No | **✔️** | `false` | -| `authorId` | `INT` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `NVARCHAR(1000)` | No | No | No | - | -| `userId` | `INT` | No | **✔️** | **✔️** | - | - -
- -
- - - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE "User" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - name STRING(255), - email STRING(255) UNIQUE NOT NULL -); - -CREATE TABLE "Post" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - title STRING(255) UNIQUE NOT NULL, - "createdAt" TIMESTAMP NOT NULL DEFAULT now(), - content STRING, - published BOOLEAN NOT NULL DEFAULT false, - "authorId" INT8 NOT NULL, - FOREIGN KEY ("authorId") REFERENCES "User"(id) -); - -CREATE TABLE "Profile" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - bio STRING, - "userId" INT8 UNIQUE NOT NULL, - FOREIGN KEY ("userId") REFERENCES "User"(id) -); -``` - -> **Note**: Some fields are written in double quotes to ensure CockroachDB uses proper casing. If no double-quotes were used, CockroachDB would just read everything as _lowercase_ characters. - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------ | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `STRING(255)` | No | No | No | - | -| `email` | `STRING(255)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------ | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | -| `title` | `STRING(255)` | No | No | **✔️** | - | -| `content` | `STRING` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INT8` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `STRING` | No | No | No | - | -| `userId` | `INT8` | No | **✔️** | **✔️** | - | - -
- -
- - - -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a data model in your Prisma schema. - -After the introspection is complete, your Prisma schema file was updated: - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this (note that the fields on the models have been reordered for better readability): - -```prisma file=prisma/schema.prisma -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - Post Post[] - Profile Profile? -} -``` - -Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=8,15,22,23;edit -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - posts Post[] - profile Profile? -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
- -
- - - -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema file was updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this (note that the fields on the models have been reordered for better readability): - -```prisma file=prisma/schema.prisma -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(0) - content String? @db.Text - published Boolean @default(false) - authorId Int - User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Post_ibfk_1") - - @@index([authorId], map: "authorId") -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? @db.Text - userId Int @unique(map: "userId") - User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Profile_ibfk_1") -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique(map: "email") @db.VarChar(255) - Post Post[] - Profile Profile? -} -``` - - - -Refer to the [Prisma schema reference](/orm/reference/prisma-schema-reference) for detailed information about the schema definition. - - - -Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=8,17,24,25;edit -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(0) - content String? @db.Text - published Boolean @default(false) - authorId Int - author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Post_ibfk_1") - - @@index([authorId], map: "authorId") -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? @db.Text - userId Int @unique(map: "userId") - user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Profile_ibfk_1") -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique(map: "email") @db.VarChar(255) - posts Post[] - profile Profile? -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - - - - - -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema file was updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this (note that the fields on the models have been reordered for better readability): - -```prisma file=prisma/schema.prisma -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - User User @relation(fields: [authorId], references: [id]) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - User User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - Post Post[] - Profile Profile? -} -``` - -Prisma's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=7,14,22,23;edit -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique @db.VarChar(255) - name String? @db.VarChar(255) - posts Post[] - profile Profile? -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
- -
- - - -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This commands reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema file was updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this: - -```prisma file=prisma/schema.prisma -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime - title String @db.VarChar(255) - content String? - published Boolean @default(false) - authorId Int - - @@index([authorId]) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - - @@index([userId]) -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? -} -``` - - - -Refer to the [Prisma schema reference](/orm/reference/prisma-schema-reference) for detailed information about the schema definition. - - - -Prisma's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -You will then need to add in any missing relations between your data using [relation fields](/orm/prisma-schema/data-model/relations#relation-fields): - -```prisma file=prisma/schema.prisma highlight=8,17,27,28;add -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int - - @@index([authorId]) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique - - @@index([userId]) -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -After this, run introspection on your database for a second time: - -```terminal copy -npx prisma db pull -``` - -Prisma Migrate will now keep the manually added relation fields. - -Because relation fields are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database. - -In this example, the database schema follows the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models. This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
- -
- - - -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This commands reads the environment variable used to define the `url` in your `schema.prisma`, `DATABASE_URL`, that in our case is set in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema file was updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this: - -```prisma file=prisma/schema.prisma -model Post { - id BigInt @id @default(autoincrement()) - title String @unique @db.String(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId BigInt - User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id BigInt @id @default(autoincrement()) - bio String? - userId BigInt @unique - User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id BigInt @id @default(autoincrement()) - name String? @db.String(255) - email String @unique @db.String(255) - Post Post[] - Profile Profile? -} -``` - -Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=8,15,22,23;edit -model Post { - id BigInt @id @default(autoincrement()) - title String @unique @db.String(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId BigInt - author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id BigInt @id @default(autoincrement()) - bio String? - userId BigInt @unique - user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id BigInt @id @default(autoincrement()) - name String? @db.String(255) - email String @unique @db.String(255) - posts Post[] - profile Profile? -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(sequence()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(sequence()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
- -
- - - - - - - Connect your database - - - - Baseline your database - - - - - - - - - - - - Connect your database - - - - Baseline your database - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Baseline your database - - - - - - - - - - - - Connect your database - - - - Baseline your database - - - - - - - - - - - - Connect your database - - - - Baseline your database - - - - - - - - - - - - Connect your database - - - - Baseline your database - - - - - - - - - - - - Connect your database - - - - Install Prisma Client - - - - - - - - - - - - Connect your database - - - - Baseline your database - - - - - - - - - - - - Connect your database - - - - Baseline your database - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-cockroachdb.mdx new file mode 100644 index 0000000000..49c98bfe73 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-cockroachdb.mdx @@ -0,0 +1,110 @@ +--- +title: 'Baseline your database' +metaTitle: 'Baseline your database' +metaDescription: 'Baseline your database using Prisma Migrate in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Create an initial migration + +To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). + +Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. + +To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. + +First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: + +```terminal +mkdir -p prisma/migrations/0_init +``` + + + +`-p` will recursively create any missing folders in the path you provide. + + + +Next, generate the migration file with `prisma migrate diff`. Use the following arguments: + +- `--from-empty`: assumes the data model you're migrating from is empty +- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block +- `--script`: output a SQL script + +```terminal wrap +npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +## Review the migration + +The command will generate a migration that should resemble the following script: + +```sql file=prisma/migrations/0_init/migration.sql +CREATE TABLE "User" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + name STRING(255), + email STRING(255) UNIQUE NOT NULL +); + +CREATE TABLE "Post" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + title STRING(255) UNIQUE NOT NULL, + "createdAt" TIMESTAMP NOT NULL DEFAULT now(), + content STRING, + published BOOLEAN NOT NULL DEFAULT false, + "authorId" INT8 NOT NULL, + FOREIGN KEY ("authorId") REFERENCES "User"(id) +); + +CREATE TABLE "Profile" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + bio STRING, + "userId" INT8 UNIQUE NOT NULL, + FOREIGN KEY ("userId") REFERENCES "User"(id) +); +``` + +Review the SQL migration file to ensure everything is correct. + +Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. + +You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. + + + + + Introspection + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-mysql.mdx new file mode 100644 index 0000000000..11c5ff5f3f --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-mysql.mdx @@ -0,0 +1,126 @@ +--- +title: 'Baseline your database' +metaTitle: 'Baseline your database' +metaDescription: 'Baseline your database using Prisma Migrate in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Create an initial migration + +To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). + +Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. + +To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. + +First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: + +```terminal +mkdir -p prisma/migrations/0_init +``` + + + +`-p` will recursively create any missing folders in the path you provide. + + + +Next, generate the migration file with `prisma migrate diff`. Use the following arguments: + +- `--from-empty`: assumes the data model you're migrating from is empty +- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block +- `--script`: output a SQL script + +```terminal wrap +npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +## Review the migration + +The command will generate a migration that should resemble the following script: + +```sql file=prisma/migrations/0_init/migration.sql +-- CreateTable +CREATE TABLE `Post` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `title` VARCHAR(255) NOT NULL, + `createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), + `content` TEXT NULL, + `published` BOOLEAN NOT NULL DEFAULT false, + `authorId` INTEGER NOT NULL, + + INDEX `authorId`(`authorId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Profile` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `bio` TEXT NULL, + `userId` INTEGER NOT NULL, + + UNIQUE INDEX `userId`(`userId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `User` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `name` VARCHAR(255) NULL, + `email` VARCHAR(255) NOT NULL, + + UNIQUE INDEX `email`(`email`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `Post` ADD CONSTRAINT `Post_ibfk_1` FOREIGN KEY (`authorId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT; + +-- AddForeignKey +ALTER TABLE `Profile` ADD CONSTRAINT `Profile_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT; +``` + +Review the SQL migration file to ensure everything is correct. + +Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. + +You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. + + + + + Introspection + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-postgresql.mdx new file mode 100644 index 0000000000..43ac802290 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-postgresql.mdx @@ -0,0 +1,129 @@ +--- +title: 'Baseline your database' +metaTitle: 'Baseline your database' +metaDescription: 'Baseline your database using Prisma Migrate in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Create an initial migration + +To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). + +Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. + +To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. + +First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: + +```terminal +mkdir -p prisma/migrations/0_init +``` + + + +`-p` will recursively create any missing folders in the path you provide. + + + +Next, generate the migration file with `prisma migrate diff`. Use the following arguments: + +- `--from-empty`: assumes the data model you're migrating from is empty +- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block +- `--script`: output a SQL script + +```terminal wrap +npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +## Review the migration + +The command will generate a migration that should resemble the following script: + +```sql file=prisma/migrations/0_init/migration.sql +-- CreateTable +CREATE TABLE "Post" ( + "id" SERIAL NOT NULL, + "title" VARCHAR(255) NOT NULL, + "createdAt" TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "content" TEXT, + "published" BOOLEAN NOT NULL DEFAULT false, + "authorId" INTEGER NOT NULL, + + CONSTRAINT "Post_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Profile" ( + "id" SERIAL NOT NULL, + "bio" TEXT, + "userId" INTEGER NOT NULL, + + CONSTRAINT "Profile_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "User" ( + "id" SERIAL NOT NULL, + "name" VARCHAR(255), + "email" VARCHAR(255) NOT NULL, + + CONSTRAINT "User_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId"); + +-- CreateIndex +CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); + +-- AddForeignKey +ALTER TABLE "Post" ADD CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; + +-- AddForeignKey +ALTER TABLE "Profile" ADD CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; +``` + +Review the SQL migration file to ensure everything is correct. + +Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. + +You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. + + + + + Introspection + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-sqlserver.mdx new file mode 100644 index 0000000000..df1d587dd3 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-sqlserver.mdx @@ -0,0 +1,118 @@ +--- +title: 'Baseline your database' +metaTitle: 'Baseline your database' +metaDescription: 'Baseline your database using Prisma Migrate in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Create an initial migration + +To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). + +Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. + +To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. + +First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: + +```terminal +mkdir -p prisma/migrations/0_init +``` + + + +`-p` will recursively create any missing folders in the path you provide. + + + +Next, generate the migration file with `prisma migrate diff`. Use the following arguments: + +- `--from-empty`: assumes the data model you're migrating from is empty +- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block +- `--script`: output a SQL script + +```terminal wrap +npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +## Review the migration + +The command will generate a migration that should resemble the following script: + +```sql file=prisma/migrations/0_init/migration.sql +CREATE TABLE [dbo].[Post] ( + [id] INT NOT NULL IDENTITY(1,1), + [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, + [updatedAt] DATETIME2 NOT NULL, + [title] VARCHAR(255) NOT NULL, + [content] NVARCHAR(1000), + [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, + [authorId] INT NOT NULL, + CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) +); + +CREATE TABLE [dbo].[Profile] ( + [id] INT NOT NULL IDENTITY(1,1), + [bio] NVARCHAR(1000), + [userId] INT NOT NULL, + CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), + CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) +); + +CREATE TABLE [dbo].[User] ( + [id] INT NOT NULL IDENTITY(1,1), + [email] NVARCHAR(1000) NOT NULL, + [name] NVARCHAR(1000), + CONSTRAINT [User_pkey] PRIMARY KEY ([id]), + CONSTRAINT [User_email_key] UNIQUE ([email]) +); + +ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; + +ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; +``` + +Review the SQL migration file to ensure everything is correct. + +Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. + +You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. + + + + + Introspection + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-cockroachdb.mdx new file mode 100644 index 0000000000..ad91c75472 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-cockroachdb.mdx @@ -0,0 +1,99 @@ +--- +title: 'Baseline your database' +metaTitle: 'Baseline your database' +metaDescription: 'Baseline your database using Prisma Migrate in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Create an initial migration + +To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). + +Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. + +To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. + +First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: + +```terminal +mkdir -p prisma/migrations/0_init +``` + + + +`-p` will recursively create any missing folders in the path you provide. + + + +Next, generate the migration file with `prisma migrate diff`. Use the following arguments: + +- `--from-empty`: assumes the data model you're migrating from is empty +- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block +- `--script`: output a SQL script + +```terminal wrap +npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +## Review the migration + +The command will generate a migration that should resemble the following script: + + +```sql file=prisma/migrations/0_init/migration.sql +CREATE TABLE "User" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + name STRING(255), + email STRING(255) UNIQUE NOT NULL +); + +CREATE TABLE "Post" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + title STRING(255) UNIQUE NOT NULL, + "createdAt" TIMESTAMP NOT NULL DEFAULT now(), + content STRING, + published BOOLEAN NOT NULL DEFAULT false, + "authorId" INT8 NOT NULL, + FOREIGN KEY ("authorId") REFERENCES "User"(id) +); + +CREATE TABLE "Profile" ( + id INT8 PRIMARY KEY DEFAULT unique_rowid(), + bio STRING, + "userId" INT8 UNIQUE NOT NULL, + FOREIGN KEY ("userId") REFERENCES "User"(id) +); +``` + + + + + Introspection + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-mysql.mdx new file mode 100644 index 0000000000..36f8c19767 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-mysql.mdx @@ -0,0 +1,127 @@ +--- +title: 'Baseline your database' +metaTitle: 'Baseline your database' +metaDescription: 'Baseline your database using Prisma Migrate in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Create an initial migration + +To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). + +Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. + +To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. + +First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: + +```terminal +mkdir -p prisma/migrations/0_init +``` + + + +`-p` will recursively create any missing folders in the path you provide. + + + +Next, generate the migration file with `prisma migrate diff`. Use the following arguments: + +- `--from-empty`: assumes the data model you're migrating from is empty +- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block +- `--script`: output a SQL script + +```terminal wrap +npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +## Review the migration + +The command will generate a migration that should resemble the following script: + +```sql file=prisma/migrations/0_init/migration.sql +-- CreateTable +CREATE TABLE `Post` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `title` VARCHAR(255) NOT NULL, + `createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), + `content` TEXT NULL, + `published` BOOLEAN NOT NULL DEFAULT false, + `authorId` INTEGER NOT NULL, + + INDEX `authorId`(`authorId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Profile` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `bio` TEXT NULL, + `userId` INTEGER NOT NULL, + + UNIQUE INDEX `userId`(`userId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `User` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `name` VARCHAR(255) NULL, + `email` VARCHAR(255) NOT NULL, + + UNIQUE INDEX `email`(`email`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `Post` ADD CONSTRAINT `Post_ibfk_1` FOREIGN KEY (`authorId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT; + +-- AddForeignKey +ALTER TABLE `Profile` ADD CONSTRAINT `Profile_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT; +``` + + +Review the SQL migration file to ensure everything is correct. + +Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. + +You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. + + + + + Introspection + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-postgresql.mdx new file mode 100644 index 0000000000..128aee17be --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-postgresql.mdx @@ -0,0 +1,128 @@ +--- +title: 'Baseline your database' +metaTitle: 'Baseline your database' +metaDescription: 'Baseline your database using Prisma Migrate in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +--- + + + + +## Create an initial migration + +To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). + +Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. + +To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. + +First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: + +```terminal +mkdir -p prisma/migrations/0_init +``` + + + +`-p` will recursively create any missing folders in the path you provide. + + + +Next, generate the migration file with `prisma migrate diff`. Use the following arguments: + +- `--from-empty`: assumes the data model you're migrating from is empty +- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block +- `--script`: output a SQL script + +```terminal wrap +npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +## Review the migration + +The command will generate a migration that should resemble the following script: + +```sql file=prisma/migrations/0_init/migration.sql +-- CreateTable +CREATE TABLE "Post" ( + "id" SERIAL NOT NULL, + "title" VARCHAR(255) NOT NULL, + "createdAt" TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "content" TEXT, + "published" BOOLEAN NOT NULL DEFAULT false, + "authorId" INTEGER NOT NULL, + + CONSTRAINT "Post_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Profile" ( + "id" SERIAL NOT NULL, + "bio" TEXT, + "userId" INTEGER NOT NULL, + + CONSTRAINT "Profile_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "User" ( + "id" SERIAL NOT NULL, + "name" VARCHAR(255), + "email" VARCHAR(255) NOT NULL, + + CONSTRAINT "User_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId"); + +-- CreateIndex +CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); + +-- AddForeignKey +ALTER TABLE "Post" ADD CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; + +-- AddForeignKey +ALTER TABLE "Profile" ADD CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; +``` + +Review the SQL migration file to ensure everything is correct. + +Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. + +You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. + + + + + Introspection + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-sqlserver.mdx new file mode 100644 index 0000000000..5e59ab8367 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-sqlserver.mdx @@ -0,0 +1,118 @@ +--- +title: 'Baseline your database' +metaTitle: 'Baseline your database' +metaDescription: 'Baseline your database using Prisma Migrate in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Create an initial migration + +To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). + +Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. + +To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. + +First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: + +```terminal +mkdir -p prisma/migrations/0_init +``` + + + +`-p` will recursively create any missing folders in the path you provide. + + + +Next, generate the migration file with `prisma migrate diff`. Use the following arguments: + +- `--from-empty`: assumes the data model you're migrating from is empty +- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block +- `--script`: output a SQL script + +```terminal wrap +npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +## Review the migration + +The command will generate a migration that should resemble the following script: + +```sql file=prisma/migrations/0_init/migration.sql +CREATE TABLE [dbo].[Post] ( + [id] INT NOT NULL IDENTITY(1,1), + [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, + [updatedAt] DATETIME2 NOT NULL, + [title] VARCHAR(255) NOT NULL, + [content] NVARCHAR(1000), + [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, + [authorId] INT NOT NULL, + CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) +); + +CREATE TABLE [dbo].[Profile] ( + [id] INT NOT NULL IDENTITY(1,1), + [bio] NVARCHAR(1000), + [userId] INT NOT NULL, + CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), + CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) +); + +CREATE TABLE [dbo].[User] ( + [id] INT NOT NULL IDENTITY(1,1), + [email] NVARCHAR(1000) NOT NULL, + [name] NVARCHAR(1000), + CONSTRAINT [User_pkey] PRIMARY KEY ([id]), + CONSTRAINT [User_email_key] UNIQUE ([email]) +); + +ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; + +ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; +``` + +Review the SQL migration file to ensure everything is correct. + +Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. + +You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. + + + + + Introspection + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database.mdx deleted file mode 100644 index ea3ed52a98..0000000000 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database.mdx +++ /dev/null @@ -1,421 +0,0 @@ ---- -title: 'Baseline your database' -metaTitle: 'Baseline your database' -metaDescription: 'Baseline your database using Prisma Migrate in your project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true ---- - -## Create an initial migration - -To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). - -Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. - -To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. - -First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: - -```terminal -mkdir -p prisma/migrations/0_init -``` - - - -`-p` will recursively create any missing folders in the path you provide. - - - -Next, generate the migration file with `prisma migrate diff`. Use the following arguments: - -- `--from-empty`: assumes the data model you're migrating from is empty -- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block -- `--script`: output a SQL script - -```terminal wrap -npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -## Review the migration - -The command will generate a migration that should resemble the following script: - - - -```sql file=prisma/migrations/0_init/migration.sql --- CreateTable -CREATE TABLE "Post" ( - "id" SERIAL NOT NULL, - "title" VARCHAR(255) NOT NULL, - "createdAt" TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "content" TEXT, - "published" BOOLEAN NOT NULL DEFAULT false, - "authorId" INTEGER NOT NULL, - - CONSTRAINT "Post_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "Profile" ( - "id" SERIAL NOT NULL, - "bio" TEXT, - "userId" INTEGER NOT NULL, - - CONSTRAINT "Profile_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "User" ( - "id" SERIAL NOT NULL, - "name" VARCHAR(255), - "email" VARCHAR(255) NOT NULL, - - CONSTRAINT "User_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId"); - --- CreateIndex -CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); - --- AddForeignKey -ALTER TABLE "Post" ADD CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - --- AddForeignKey -ALTER TABLE "Profile" ADD CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; -``` - - - - - -```sql file=prisma/migrations/0_init/migration.sql --- CreateTable -CREATE TABLE `Post` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `title` VARCHAR(255) NOT NULL, - `createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), - `content` TEXT NULL, - `published` BOOLEAN NOT NULL DEFAULT false, - `authorId` INTEGER NOT NULL, - - INDEX `authorId`(`authorId`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- CreateTable -CREATE TABLE `Profile` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `bio` TEXT NULL, - `userId` INTEGER NOT NULL, - - UNIQUE INDEX `userId`(`userId`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- CreateTable -CREATE TABLE `User` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `name` VARCHAR(255) NULL, - `email` VARCHAR(255) NOT NULL, - - UNIQUE INDEX `email`(`email`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- AddForeignKey -ALTER TABLE `Post` ADD CONSTRAINT `Post_ibfk_1` FOREIGN KEY (`authorId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT; - --- AddForeignKey -ALTER TABLE `Profile` ADD CONSTRAINT `Profile_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT; -``` - - - - - -```sql file=prisma/migrations/0_init/migration.sql -CREATE TABLE [dbo].[Post] ( - [id] INT NOT NULL IDENTITY(1,1), - [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, - [updatedAt] DATETIME2 NOT NULL, - [title] VARCHAR(255) NOT NULL, - [content] NVARCHAR(1000), - [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, - [authorId] INT NOT NULL, - CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) -); - -CREATE TABLE [dbo].[Profile] ( - [id] INT NOT NULL IDENTITY(1,1), - [bio] NVARCHAR(1000), - [userId] INT NOT NULL, - CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), - CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) -); - -CREATE TABLE [dbo].[User] ( - [id] INT NOT NULL IDENTITY(1,1), - [email] NVARCHAR(1000) NOT NULL, - [name] NVARCHAR(1000), - CONSTRAINT [User_pkey] PRIMARY KEY ([id]), - CONSTRAINT [User_email_key] UNIQUE ([email]) -); - -ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; - -ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; -``` - - - - - -```sql file=prisma/migrations/0_init/migration.sql -CREATE TABLE "User" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - name STRING(255), - email STRING(255) UNIQUE NOT NULL -); - -CREATE TABLE "Post" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - title STRING(255) UNIQUE NOT NULL, - "createdAt" TIMESTAMP NOT NULL DEFAULT now(), - content STRING, - published BOOLEAN NOT NULL DEFAULT false, - "authorId" INT8 NOT NULL, - FOREIGN KEY ("authorId") REFERENCES "User"(id) -); - -CREATE TABLE "Profile" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - bio STRING, - "userId" INT8 UNIQUE NOT NULL, - FOREIGN KEY ("userId") REFERENCES "User"(id) -); -``` - - - -Review the SQL migration file to ensure everything is correct. - -Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. - -```terminal -npx prisma migrate resolve --applied 0_init -``` - -The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. - -You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. - - - - - - - Introspection - - - - Install Prisma Client - - - - - - - - - - - - Introspection - - - - Install Prisma Client - - - - - - - - - - - - Introspection - - - - Install Prisma Client - - - - - - - - - - - - Introspection - - - - Install Prisma Client - - - - - - - - - - - - Introspection - - - - Install Prisma Client - - - - - - - - - - - - Introspection - - - - Install Prisma Client - - - - - - - - - - - - Introspection - - - - Install Prisma Client - - - - - - - - - - - - Introspection - - - - Install Prisma Client - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx new file mode 100644 index 0000000000..5feb702c52 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx @@ -0,0 +1,62 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: + +```terminal copy +npx prisma generate +``` + +This command reads your Prisma schema and generates your Prisma Client library: + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: + +![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) + + + + + Baseline your database + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-mysql.mdx new file mode 100644 index 0000000000..e2427b06c5 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-mysql.mdx @@ -0,0 +1,62 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: + +```terminal copy +npx prisma generate +``` + +This command reads your Prisma schema and generates your Prisma Client library: + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: + +![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) + + + + + Baseline your database + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-planetscale.mdx new file mode 100644 index 0000000000..cd959dc93f --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-planetscale.mdx @@ -0,0 +1,62 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: + +```terminal copy +npx prisma generate +``` + +This command reads your Prisma schema and generates your Prisma Client library: + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: + +![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) + + + + + Introspection + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-postgresql.mdx new file mode 100644 index 0000000000..31510a9e12 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-postgresql.mdx @@ -0,0 +1,62 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: + +```terminal copy +npx prisma generate +``` + +This command reads your Prisma schema and generates your Prisma Client library: + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: + +![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) + + + + + Baseline your database + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx new file mode 100644 index 0000000000..9961e807c8 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx @@ -0,0 +1,62 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: + +```terminal copy +npx prisma generate +``` + +This command reads your Prisma schema and generates your Prisma Client library: + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: + +![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) + + + + + Baseline your database + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx new file mode 100644 index 0000000000..1cbb22724a --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx @@ -0,0 +1,62 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: + +```terminal copy +npx prisma generate +``` + +This command reads your Prisma schema and generates your Prisma Client library: + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: + +![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) + + + + + Baseline your database + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx new file mode 100644 index 0000000000..f69c9dca49 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx @@ -0,0 +1,62 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: + +```terminal copy +npx prisma generate +``` + +This command reads your Prisma schema and generates your Prisma Client library: + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: + +![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) + + + + + Baseline your database + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx new file mode 100644 index 0000000000..df7534b4a9 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx @@ -0,0 +1,62 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: + +```terminal copy +npx prisma generate +``` + +This command reads your Prisma schema and generates your Prisma Client library: + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: + +![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) + + + + + Introspection + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx new file mode 100644 index 0000000000..e1fa64262d --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx @@ -0,0 +1,61 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: + +```terminal copy +npx prisma generate +``` + +This command reads your Prisma schema and generates your Prisma Client library: + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: + +![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) + + + + + Baseline your database + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx new file mode 100644 index 0000000000..056e44b21f --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx @@ -0,0 +1,62 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: + +```terminal copy +npx prisma generate +``` + +This command reads your Prisma schema and generates your Prisma Client library: + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: + +![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) + + + + + Baseline your database + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client.mdx deleted file mode 100644 index b474290d81..0000000000 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client.mdx +++ /dev/null @@ -1,290 +0,0 @@ ---- -title: 'Install Prisma Client' -metaTitle: 'Install Prisma Client' -metaDescription: 'Install and generate Prisma Client in your project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true ---- - -## Install and generate Prisma Client - -To get started with Prisma Client, you need to install the `@prisma/client` package: - -```terminal copy -npm install @prisma/client -``` - -Notice that the [`@prisma/client` node module](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) references a folder named `.prisma/client`. The `.prisma/client` folder contains your generated Prisma Client, and is modified each time you change the schema and run the following command: - -```terminal copy -npx prisma generate -``` - -This command reads your Prisma schema and generates your Prisma Client library: - -![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) - -The `@prisma/client` node module references a folder named `.prisma/client`, which contains your unique, generated Prisma Client: - -![The .prisma and @prisma folders](/img/getting-started/prisma-client-node-module.png) - - - - - - - Baseline your database - - - - Querying the database - - - - - - - - - - - - Baseline your database - - - - Querying the database - - - - - - - - - - - - Introspection - - - - Querying the database - - - - - - - - - - - - Baseline your database - - - - Querying the database - - - - - - - - - - - - Baseline your database - - - - Querying the database - - - - - - - - - - - - Baseline your database - - - - Querying the database - - - - - - - - - - - - Baseline your database - - - - Querying the database - - - - - - - - - - - - Introspection - - - - Querying the database - - - - - - - - - - - - Baseline your database - - - - Querying the database - - - - - - - - - - - - Baseline your database - - - - Querying the database - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx new file mode 100644 index 0000000000..73ee6355a8 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx @@ -0,0 +1,148 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +```js file=index.js +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. + +```no-copy +[] +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js +async function main() { + const post = await prisma.post.update({ + where: { title: 'Hello World' }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + + + + + Install Prisma Client + + + + Evolve your schema + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-mysql.mdx new file mode 100644 index 0000000000..f42798935e --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-mysql.mdx @@ -0,0 +1,150 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +```js file=index.js +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. + +```no-copy +[] +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + + + + + Install Prisma Client + + + + Evolve your schema + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-planetscale.mdx new file mode 100644 index 0000000000..411ee207d3 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-planetscale.mdx @@ -0,0 +1,162 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). + +The following examples are all based on the models in the Prisma schema. + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```js file=index.js +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. + +```no-copy +[] +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + + + + + Install Prisma Client + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-postgresql.mdx new file mode 100644 index 0000000000..3242035fd1 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-postgresql.mdx @@ -0,0 +1,149 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +```js file=index.js +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. + +```no-copy +[] +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + + + + + Install Prisma Client + + + + Evolve your schema + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-sqlserver.mdx new file mode 100644 index 0000000000..e9d2d1bbe1 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-sqlserver.mdx @@ -0,0 +1,157 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). + +The following examples are all based on the models in the Prisma schema. + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```js file=index.js +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. + +```no-copy +[] +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + + + + + Install Prisma Client + + + + Evolve your schema + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx new file mode 100644 index 0000000000..da43c8905f --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx @@ -0,0 +1,163 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + +Create a new file named `index.ts` and add the following code to it: + +```ts file=index.ts +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). + +The following examples are all based on the models in the Prisma schema. + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```ts file=index.ts +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + +If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. + +```no-copy +[] +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```ts file=index.ts +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```ts file=index.ts +async function main() { + const post = await prisma.post.update({ + where: { title: 'Hello World' }, + data: { published: true }, + }) + console.log(post) +} +``` + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + + + + + Install Prisma Client + + + + Evolve your schema + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-mysql.mdx new file mode 100644 index 0000000000..faa3cafd7d --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-mysql.mdx @@ -0,0 +1,163 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + +Create a new file named `index.ts` and add the following code to it: + +```ts file=index.ts +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). + +The following examples are all based on the models in the Prisma schema. + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```ts file=index.ts +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + +If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. + +```no-copy +[] +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```ts file=index.ts +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```ts file=index.ts +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + + + + + Install Prisma Client + + + + Evolve your schema + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx new file mode 100644 index 0000000000..88030a2a5c --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx @@ -0,0 +1,164 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + +Create a new file named `index.ts` and add the following code to it: + +```ts file=index.ts +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). + +The following examples are all based on the models in the Prisma schema. + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```ts file=index.ts +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + + +If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. + +```no-copy +[] +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```ts file=index.ts +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```ts file=index.ts +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx new file mode 100644 index 0000000000..92b7586ab4 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx @@ -0,0 +1,162 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +--- + + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + +Create a new file named `index.ts` and add the following code to it: + +```ts file=index.ts +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). + +The following examples are all based on the models in the Prisma schema. + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```ts file=index.ts +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + +If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. + +```no-copy +[] +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```ts file=index.ts +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```ts file=index.ts +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + + + + + Install Prisma Client + + + + Evolve your schema + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx new file mode 100644 index 0000000000..770a4fe719 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx @@ -0,0 +1,163 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + +Create a new file named `index.ts` and add the following code to it: + +```ts file=index.ts +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). + +The following examples are all based on the models in the Prisma schema. + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```ts file=index.ts +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + +If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. + +```no-copy +[] +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```ts file=index.ts +async function main() { + await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { title: 'Hello World' }, + }, + profile: { + create: { bio: 'I like turtles' }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```ts file=index.ts +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +```terminal copy +npx ts-node index.ts +``` + + + + + Install Prisma Client + + + + Evolve your schema + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database.mdx deleted file mode 100644 index cba41fc44f..0000000000 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database.mdx +++ /dev/null @@ -1,641 +0,0 @@ ---- -title: 'Querying the database' -metaTitle: 'Querying the database' -metaDescription: 'Write data to and query the database' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true ---- - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - - - -Create a new file named `index.ts` and add the following code to it: - -```ts file=index.ts -import { PrismaClient } from '@prisma/client' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - - - - - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - - - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). - -The following examples are all based on the models in the Prisma schema. - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - - - -```ts file=index.ts -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - - - - - -```js file=index.js -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - - - - - -Now run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: - -```terminal copy -npx ts-node index.ts -``` - - - - - -Now run the code with this command: - -```terminal copy -node index.js -``` - - - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - - - -```ts file=index.ts -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - - - - - -```js file=index.js -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - - - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - - - -Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: - -```terminal copy -npx ts-node index.ts -``` - - - - - -Run the code with this command: - -```terminal copy -node index.js -``` - - - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - - - -```ts file=index.ts -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - -```js file=index.js -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - -```ts file=index.ts -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - -```js file=index.js -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - -```ts file=index.ts -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - -```js file=index.js -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - -```ts file=index.ts -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - -```js file=index.js -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - -```ts file=index.ts -async function main() { - const post = await prisma.post.update({ - where: { title: 'Hello World' }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - -```js file=index.js -async function main() { - const post = await prisma.post.update({ - where: { title: 'Hello World' }, - data: { published: true }, - }) - console.log(post) -} -``` - - - - - -Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: - -```terminal copy -npx ts-node index.ts -``` - - - - - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - - - - - - - - - Install Prisma Client - - - - Evolve your schema - - - - - - - - - - - - Install Prisma Client - - - - Evolve your schema - - - - - - - - - - - - Install Prisma Client - - - Next Steps - - - - - - - - - - - - Install Prisma Client - - - - Evolve your schema - - - - - - - - - - - - Install Prisma Client - - - - Evolve your schema - - - - - - - - - - - - Install Prisma Client - - - - Evolve your schema - - - - - - - - - - - - Install Prisma Client - - - - Evolve your schema - - - - - - - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - - - Install Prisma Client - - - - Evolve your schema - - - - - - - - - - - - Install Prisma Client - - - - Evolve your schema - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-cockroachdb.mdx new file mode 100644 index 0000000000..b648bc0fea --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-cockroachdb.mdx @@ -0,0 +1,128 @@ +--- +title: 'Evolve your schema' +metaTitle: 'Evolve your Prisma schema with Prisma Migrate' +metaDescription: 'Evolve your Prisma schema with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Add a `Tag` model to your schema + +In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). + +For the purpose of this guide, we'll make the following changes to the Prisma schema: + +1. Create a new model called `Tag` with the following fields: + - `id`: an auto-incrementing integer that will be the primary key for the model + - `name`: a non-null `String` + - `posts`: an implicit many-to-many relation field that links to the `Post` model +2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model + +Once you've made the changes to your schema, your schema should resemble the one below: + +```prisma file=prisma/schema.prisma highlight=9,27-31;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + user User @relation(fields: [authorId], references: [id]) + tags Tag[] +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + user User @relation(fields: [userId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + post Post[] + profile Profile? +} + +model Tag { + id Int @id @default(autoincrement()) + name String + posts Post[] +} +``` + +To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: + +```terminal copy +npx prisma migrate dev --name tags-model +``` + +This command will: + +1. Create a new SQL migration file for the migration +1. Apply the generated SQL migration to the database +1. Regenerate Prisma Client + +The following migration will be generated and saved in your `prisma/migrations` folder: + +```sql file=prisma/migrations/TIMESTAMP_tags_model.sql + -- CreateTable +CREATE TABLE "Tag" ( + "id" SERIAL NOT NULL, + "name" VARCHAR(255) NOT NULL, + + CONSTRAINT "Tag_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "_PostToTag" ( + "A" INTEGER NOT NULL, + "B" INTEGER NOT NULL +); + +-- CreateIndex +CREATE UNIQUE INDEX "_PostToTag_AB_unique" ON "_PostToTag"("A", "B"); + +-- CreateIndex +CREATE INDEX "_PostToTag_B_index" ON "_PostToTag"("B"); + +-- AddForeignKey +ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; +``` + + + + + Querying the database + + + + Next steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-mysql.mdx new file mode 100644 index 0000000000..9ab5ff6247 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-mysql.mdx @@ -0,0 +1,125 @@ +--- +title: 'Evolve your schema' +metaTitle: 'Evolve your Prisma schema with Prisma Migrate' +metaDescription: 'Evolve your Prisma schema with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Add a `Tag` model to your schema + +In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). + +For the purpose of this guide, we'll make the following changes to the Prisma schema: + +1. Create a new model called `Tag` with the following fields: + - `id`: an auto-incrementing integer that will be the primary key for the model + - `name`: a non-null `String` + - `posts`: an implicit many-to-many relation field that links to the `Post` model +2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model + +Once you've made the changes to your schema, your schema should resemble the one below: + +```prisma file=prisma/schema.prisma highlight=9,27-31;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + user User @relation(fields: [authorId], references: [id]) + tags Tag[] +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + user User @relation(fields: [userId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + post Post[] + profile Profile? +} + +model Tag { + id Int @id @default(autoincrement()) + name String + posts Post[] +} +``` + +To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: + +```terminal copy +npx prisma migrate dev --name tags-model +``` + +This command will: + +1. Create a new SQL migration file for the migration +1. Apply the generated SQL migration to the database +1. Regenerate Prisma Client + +The following migration will be generated and saved in your `prisma/migrations` folder: + +```sql file=prisma/migrations/TIMESTAMP_tags_model.sql +-- CreateTable +CREATE TABLE Tag ( + id SERIAL NOT NULL, + name VARCHAR(255) NOT NULL, + + CONSTRAINT Tag_pkey PRIMARY KEY (id) +); + +-- CreateTable +CREATE TABLE _PostToTag ( + A INTEGER NOT NULL, + B INTEGER NOT NULL +); + +-- CreateIndex +CREATE UNIQUE INDEX _PostToTag_AB_unique ON _PostToTag(A, B); + +-- CreateIndex +CREATE INDEX _PostToTag_B_index ON _PostToTag(B); + +-- AddForeignKey +ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_A_fkey FOREIGN KEY (A) REFERENCES Post(id) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_B_fkey FOREIGN KEY (B) REFERENCES Tag(id) ON DELETE CASCADE ON UPDATE CASCADE; +``` + +Congratulations, you just evolved your database with Prisma Migrate 🚀 + + + + + Querying the database + + + + Next steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-postgresql.mdx new file mode 100644 index 0000000000..db0ea0fa0f --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-postgresql.mdx @@ -0,0 +1,130 @@ +--- +title: 'Evolve your schema' +metaTitle: 'Evolve your Prisma schema with Prisma Migrate' +metaDescription: 'Evolve your Prisma schema with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Add a `Tag` model to your schema + +In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). + +For the purpose of this guide, we'll make the following changes to the Prisma schema: + +1. Create a new model called `Tag` with the following fields: + - `id`: an auto-incrementing integer that will be the primary key for the model + - `name`: a non-null `String` + - `posts`: an implicit many-to-many relation field that links to the `Post` model +2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model + +Once you've made the changes to your schema, your schema should resemble the one below: + +```prisma file=prisma/schema.prisma highlight=9,27-31;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + user User @relation(fields: [authorId], references: [id]) + tags Tag[] +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + user User @relation(fields: [userId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + post Post[] + profile Profile? +} + +model Tag { + id Int @id @default(autoincrement()) + name String + posts Post[] +} +``` + +To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: + +```terminal copy +npx prisma migrate dev --name tags-model +``` + +This command will: + +1. Create a new SQL migration file for the migration +1. Apply the generated SQL migration to the database +1. Regenerate Prisma Client + +The following migration will be generated and saved in your `prisma/migrations` folder: + +```sql file=prisma/migrations/TIMESTAMP_tags_model.sql + -- CreateTable +CREATE TABLE "Tag" ( + "id" SERIAL NOT NULL, + "name" VARCHAR(255) NOT NULL, + + CONSTRAINT "Tag_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "_PostToTag" ( + "A" INTEGER NOT NULL, + "B" INTEGER NOT NULL +); + +-- CreateIndex +CREATE UNIQUE INDEX "_PostToTag_AB_unique" ON "_PostToTag"("A", "B"); + +-- CreateIndex +CREATE INDEX "_PostToTag_B_index" ON "_PostToTag"("B"); + +-- AddForeignKey +ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; +``` + +Congratulations, you just evolved your database with Prisma Migrate 🚀 + + + + + Querying the database + + + + Next steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-sqlserver.mdx new file mode 100644 index 0000000000..c5938c6a96 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-sqlserver.mdx @@ -0,0 +1,130 @@ +--- +title: 'Evolve your schema' +metaTitle: 'Evolve your Prisma schema with Prisma Migrate' +metaDescription: 'Evolve your Prisma schema with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Add a `Tag` model to your schema + +In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). + +For the purpose of this guide, we'll make the following changes to the Prisma schema: + +1. Create a new model called `Tag` with the following fields: + - `id`: an auto-incrementing integer that will be the primary key for the model + - `name`: a non-null `String` + - `posts`: an implicit many-to-many relation field that links to the `Post` model +2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model + +Once you've made the changes to your schema, your schema should resemble the one below: + +```prisma file=prisma/schema.prisma highlight=9,27-31;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + user User @relation(fields: [authorId], references: [id]) + tags Tag[] +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + user User @relation(fields: [userId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + post Post[] + profile Profile? +} + +model Tag { + id Int @id @default(autoincrement()) + name String + posts Post[] +} +``` + +To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: + +```terminal copy +npx prisma migrate dev --name tags-model +``` + +This command will: + +1. Create a new SQL migration file for the migration +1. Apply the generated SQL migration to the database +1. Regenerate Prisma Client + +The following migration will be generated and saved in your `prisma/migrations` folder: + +```sql file=prisma/migrations/TIMESTAMP_tags_model.sql + -- CreateTable +CREATE TABLE [dbo].[Tag] ( + [id] SERIAL NOT NULL, + [name] VARCHAR(255) NOT NULL, + + CONSTRAINT [Tag_pkey] PRIMARY KEY ([id]) +); + +-- CreateTable +CREATE TABLE [dbo].[_PostToTag] ( + [A] INTEGER NOT NULL, + [B] INTEGER NOT NULL +); + +-- CreateIndex +CREATE UNIQUE INDEX [_PostToTag_AB_unique] ON _PostToTag([A], [B]); + +-- CreateIndex +CREATE INDEX [_PostToTag_B_index] ON [_PostToTag]([B]); + +-- AddForeignKey +ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_A_fkey] FOREIGN KEY ([A]) REFERENCES [dbo].[Post]([id]) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_B_fkey] FOREIGN KEY ([B]) REFERENCES [dbo].[Tag]([id]) ON DELETE CASCADE ON UPDATE CASCADE; +``` + +Congratulations + + + + + Querying the database + + + + Next steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-cockroachdb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-cockroachdb.mdx new file mode 100644 index 0000000000..67cb651ae7 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-cockroachdb.mdx @@ -0,0 +1,130 @@ +--- +title: 'Evolve your schema' +metaTitle: 'Evolve your Prisma schema with Prisma Migrate' +metaDescription: 'Evolve your Prisma schema with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Add a `Tag` model to your schema + +In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). + +For the purpose of this guide, we'll make the following changes to the Prisma schema: + +1. Create a new model called `Tag` with the following fields: + - `id`: an auto-incrementing integer that will be the primary key for the model + - `name`: a non-null `String` + - `posts`: an implicit many-to-many relation field that links to the `Post` model +2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model + +Once you've made the changes to your schema, your schema should resemble the one below: + +```prisma file=prisma/schema.prisma highlight=9,27-31;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + user User @relation(fields: [authorId], references: [id]) + tags Tag[] +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + user User @relation(fields: [userId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + post Post[] + profile Profile? +} + +model Tag { + id Int @id @default(autoincrement()) + name String + posts Post[] +} +``` + +To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: + +```terminal copy +npx prisma migrate dev --name tags-model +``` + +This command will: + +1. Create a new SQL migration file for the migration +1. Apply the generated SQL migration to the database +1. Regenerate Prisma Client + +The following migration will be generated and saved in your `prisma/migrations` folder: + +```sql file=prisma/migrations/TIMESTAMP_tags_model.sql + -- CreateTable +CREATE TABLE "Tag" ( + "id" SERIAL NOT NULL, + "name" VARCHAR(255) NOT NULL, + + CONSTRAINT "Tag_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "_PostToTag" ( + "A" INTEGER NOT NULL, + "B" INTEGER NOT NULL +); + +-- CreateIndex +CREATE UNIQUE INDEX "_PostToTag_AB_unique" ON "_PostToTag"("A", "B"); + +-- CreateIndex +CREATE INDEX "_PostToTag_B_index" ON "_PostToTag"("B"); + +-- AddForeignKey +ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; +``` + +Congratulations, you just evolved your database with Prisma Migrate 🚀 + + + + + Querying the database + + + + Next steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-mysql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-mysql.mdx new file mode 100644 index 0000000000..35ac7a3c2f --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-mysql.mdx @@ -0,0 +1,130 @@ +--- +title: 'Evolve your schema' +metaTitle: 'Evolve your Prisma schema with Prisma Migrate' +metaDescription: 'Evolve your Prisma schema with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Add a `Tag` model to your schema + +In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). + +For the purpose of this guide, we'll make the following changes to the Prisma schema: + +1. Create a new model called `Tag` with the following fields: + - `id`: an auto-incrementing integer that will be the primary key for the model + - `name`: a non-null `String` + - `posts`: an implicit many-to-many relation field that links to the `Post` model +2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model + +Once you've made the changes to your schema, your schema should resemble the one below: + +```prisma file=prisma/schema.prisma highlight=9,27-31;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + user User @relation(fields: [authorId], references: [id]) + tags Tag[] +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + user User @relation(fields: [userId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + post Post[] + profile Profile? +} + +model Tag { + id Int @id @default(autoincrement()) + name String + posts Post[] +} +``` + +To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: + +```terminal copy +npx prisma migrate dev --name tags-model +``` + +This command will: + +1. Create a new SQL migration file for the migration +1. Apply the generated SQL migration to the database +1. Regenerate Prisma Client + +The following migration will be generated and saved in your `prisma/migrations` folder: + +```sql file=prisma/migrations/TIMESTAMP_tags_model.sql +-- CreateTable +CREATE TABLE Tag ( + id SERIAL NOT NULL, + name VARCHAR(255) NOT NULL, + + CONSTRAINT Tag_pkey PRIMARY KEY (id) +); + +-- CreateTable +CREATE TABLE _PostToTag ( + A INTEGER NOT NULL, + B INTEGER NOT NULL +); + +-- CreateIndex +CREATE UNIQUE INDEX _PostToTag_AB_unique ON _PostToTag(A, B); + +-- CreateIndex +CREATE INDEX _PostToTag_B_index ON _PostToTag(B); + +-- AddForeignKey +ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_A_fkey FOREIGN KEY (A) REFERENCES Post(id) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_B_fkey FOREIGN KEY (B) REFERENCES Tag(id) ON DELETE CASCADE ON UPDATE CASCADE; +``` + +Congratulations, you just evolved your database with Prisma Migrate 🚀 + + + + + Querying the database + + + + Next steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-postgresql.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-postgresql.mdx new file mode 100644 index 0000000000..a963afbde0 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-postgresql.mdx @@ -0,0 +1,131 @@ +--- +title: 'Evolve your schema' +metaTitle: 'Evolve your Prisma schema with Prisma Migrate' +metaDescription: 'Evolve your Prisma schema with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +--- + + + +## Add a `Tag` model to your schema + +In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). + +For the purpose of this guide, we'll make the following changes to the Prisma schema: + +1. Create a new model called `Tag` with the following fields: + - `id`: an auto-incrementing integer that will be the primary key for the model + - `name`: a non-null `String` + - `posts`: an implicit many-to-many relation field that links to the `Post` model +2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model + +Once you've made the changes to your schema, your schema should resemble the one below: + +```prisma file=prisma/schema.prisma highlight=9,27-31;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + user User @relation(fields: [authorId], references: [id]) + tags Tag[] +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + user User @relation(fields: [userId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + post Post[] + profile Profile? +} + +model Tag { + id Int @id @default(autoincrement()) + name String + posts Post[] +} +``` + +To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: + +```terminal copy +npx prisma migrate dev --name tags-model +``` + +This command will: + +1. Create a new SQL migration file for the migration +1. Apply the generated SQL migration to the database +1. Regenerate Prisma Client + +The following migration will be generated and saved in your `prisma/migrations` folder: + +```sql file=prisma/migrations/TIMESTAMP_tags_model.sql + -- CreateTable +CREATE TABLE "Tag" ( + "id" SERIAL NOT NULL, + "name" VARCHAR(255) NOT NULL, + + CONSTRAINT "Tag_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "_PostToTag" ( + "A" INTEGER NOT NULL, + "B" INTEGER NOT NULL +); + +-- CreateIndex +CREATE UNIQUE INDEX "_PostToTag_AB_unique" ON "_PostToTag"("A", "B"); + +-- CreateIndex +CREATE INDEX "_PostToTag_B_index" ON "_PostToTag"("B"); + +-- AddForeignKey +ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; +``` + + + +Congratulations, you just evolved your database with Prisma Migrate 🚀 + + + + + Querying the database + + + + Next steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-sqlserver.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-sqlserver.mdx new file mode 100644 index 0000000000..7410427bf0 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-sqlserver.mdx @@ -0,0 +1,130 @@ +--- +title: 'Evolve your schema' +metaTitle: 'Evolve your Prisma schema with Prisma Migrate' +metaDescription: 'Evolve your Prisma schema with Prisma Migrate' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Add a `Tag` model to your schema + +In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). + +For the purpose of this guide, we'll make the following changes to the Prisma schema: + +1. Create a new model called `Tag` with the following fields: + - `id`: an auto-incrementing integer that will be the primary key for the model + - `name`: a non-null `String` + - `posts`: an implicit many-to-many relation field that links to the `Post` model +2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model + +Once you've made the changes to your schema, your schema should resemble the one below: + +```prisma file=prisma/schema.prisma highlight=9,27-31;edit +model Post { + id Int @id @default(autoincrement()) + title String @db.VarChar(255) + createdAt DateTime @default(now()) @db.Timestamp(6) + content String? + published Boolean @default(false) + authorId Int + user User @relation(fields: [authorId], references: [id]) + tags Tag[] +} + +model Profile { + id Int @id @default(autoincrement()) + bio String? + userId Int @unique + user User @relation(fields: [userId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + name String? @db.VarChar(255) + email String @unique @db.VarChar(255) + post Post[] + profile Profile? +} + +model Tag { + id Int @id @default(autoincrement()) + name String + posts Post[] +} +``` + +To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: + +```terminal copy +npx prisma migrate dev --name tags-model +``` + +This command will: + +1. Create a new SQL migration file for the migration +1. Apply the generated SQL migration to the database +1. Regenerate Prisma Client + +The following migration will be generated and saved in your `prisma/migrations` folder: + +```sql file=prisma/migrations/TIMESTAMP_tags_model.sql + -- CreateTable +CREATE TABLE [dbo].[Tag] ( + [id] SERIAL NOT NULL, + [name] VARCHAR(255) NOT NULL, + + CONSTRAINT [Tag_pkey] PRIMARY KEY ([id]) +); + +-- CreateTable +CREATE TABLE [dbo].[_PostToTag] ( + [A] INTEGER NOT NULL, + [B] INTEGER NOT NULL +); + +-- CreateIndex +CREATE UNIQUE INDEX [_PostToTag_AB_unique] ON _PostToTag([A], [B]); + +-- CreateIndex +CREATE INDEX [_PostToTag_B_index] ON [_PostToTag]([B]); + +-- AddForeignKey +ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_A_fkey] FOREIGN KEY ([A]) REFERENCES [dbo].[Post]([id]) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_B_fkey] FOREIGN KEY ([B]) REFERENCES [dbo].[Tag]([id]) ON DELETE CASCADE ON UPDATE CASCADE; +``` + +Congratulations, you just evolved your database with Prisma Migrate 🚀 + + + + + Querying the database + + + + Next steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema.mdx deleted file mode 100644 index 4fe0847c6b..0000000000 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema.mdx +++ /dev/null @@ -1,402 +0,0 @@ ---- -title: 'Evolve your schema' -metaTitle: 'Evolve your Prisma schema with Prisma Migrate' -metaDescription: 'Evolve your Prisma schema with Prisma Migrate' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true ---- - -## Add a `Tag` model to your schema - -In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). - -For the purpose of this guide, we'll make the following changes to the Prisma schema: - -1. Create a new model called `Tag` with the following fields: - - `id`: an auto-incrementing integer that will be the primary key for the model - - `name`: a non-null `String` - - `posts`: an implicit many-to-many relation field that links to the `Post` model -2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model - -Once you've made the changes to your schema, your schema should resemble the one below: - -```prisma file=prisma/schema.prisma highlight=9,27-31;edit -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - user User @relation(fields: [authorId], references: [id]) - tags Tag[] -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - user User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - post Post[] - profile Profile? -} - -model Tag { - id Int @id @default(autoincrement()) - name String - posts Post[] -} -``` - -To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: - -```terminal copy -npx prisma migrate dev --name tags-model -``` - -This command will: - -1. Create a new SQL migration file for the migration -1. Apply the generated SQL migration to the database -1. Regenerate Prisma Client - -The following migration will be generated and saved in your `prisma/migrations` folder: - - - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql - -- CreateTable -CREATE TABLE "Tag" ( - "id" SERIAL NOT NULL, - "name" VARCHAR(255) NOT NULL, - - CONSTRAINT "Tag_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "_PostToTag" ( - "A" INTEGER NOT NULL, - "B" INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX "_PostToTag_AB_unique" ON "_PostToTag"("A", "B"); - --- CreateIndex -CREATE INDEX "_PostToTag_B_index" ON "_PostToTag"("B"); - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; -``` - - - - - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql - -- CreateTable -CREATE TABLE "Tag" ( - "id" SERIAL NOT NULL, - "name" VARCHAR(255) NOT NULL, - - CONSTRAINT "Tag_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "_PostToTag" ( - "A" INTEGER NOT NULL, - "B" INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX "_PostToTag_AB_unique" ON "_PostToTag"("A", "B"); - --- CreateIndex -CREATE INDEX "_PostToTag_B_index" ON "_PostToTag"("B"); - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; -``` - - - - - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql - -- CreateTable -CREATE TABLE [dbo].[Tag] ( - [id] SERIAL NOT NULL, - [name] VARCHAR(255) NOT NULL, - - CONSTRAINT [Tag_pkey] PRIMARY KEY ([id]) -); - --- CreateTable -CREATE TABLE [dbo].[_PostToTag] ( - [A] INTEGER NOT NULL, - [B] INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX [_PostToTag_AB_unique] ON _PostToTag([A], [B]); - --- CreateIndex -CREATE INDEX [_PostToTag_B_index] ON [_PostToTag]([B]); - --- AddForeignKey -ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_A_fkey] FOREIGN KEY ([A]) REFERENCES [dbo].[Post]([id]) ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_B_fkey] FOREIGN KEY ([B]) REFERENCES [dbo].[Tag]([id]) ON DELETE CASCADE ON UPDATE CASCADE; -``` - - - - - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql --- CreateTable -CREATE TABLE Tag ( - id SERIAL NOT NULL, - name VARCHAR(255) NOT NULL, - - CONSTRAINT Tag_pkey PRIMARY KEY (id) -); - --- CreateTable -CREATE TABLE _PostToTag ( - A INTEGER NOT NULL, - B INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX _PostToTag_AB_unique ON _PostToTag(A, B); - --- CreateIndex -CREATE INDEX _PostToTag_B_index ON _PostToTag(B); - --- AddForeignKey -ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_A_fkey FOREIGN KEY (A) REFERENCES Post(id) ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_B_fkey FOREIGN KEY (B) REFERENCES Tag(id) ON DELETE CASCADE ON UPDATE CASCADE; -``` - - - -Congratulations, you just evolved your database with Prisma Migrate 🚀 - - - - - - Querying the database - - - - Next steps - - - - - - - - - - - - Querying the database - - - - Next steps - - - - - - - - - - - - Querying the database - - - - Next steps - - - - - - - - - - - - Querying the database - - - - Next steps - - - - - - - - - - - - Querying the database - - - - Next steps - - - - - - - - - - - - Querying the database - - - - Next steps - - - - - - - - - - - - Querying the database - - - - Next steps - - - - - - - - - - - - Querying the database - - - - Next steps - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/300-next-steps.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/300-next-steps.mdx index c83c819613..853d6fd54d 100644 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/300-next-steps.mdx +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/300-next-steps.mdx @@ -2,8 +2,6 @@ title: 'Next steps' metaTitle: 'Next steps' metaDescription: 'Next steps to take now that you have successfully added Prisma to your project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] hide_table_of_contents: true --- diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/index.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/index.mdx deleted file mode 100644 index 5d4298f8a2..0000000000 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/index.mdx +++ /dev/null @@ -1,276 +0,0 @@ ---- -title: 'Relational databases' -metaTitle: 'Add Prisma to an existing project that uses a relational database (15 min)' -metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your relational database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } ---- - - - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -:::tip - -
- -If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides. - -
-::: - -## Prerequisites - -In order to successfully complete this guide, you need: - - - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine -- a [PostgreSQL](https://www.postgresql.org/) database server running and a database with at least one table - - - - - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine -- a [MySQL](https://www.mysql.com/) database server running and a database with at least one table - - - - - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine -- a [PlanetScale](https://www.planetscale.com/) database server running and a database with at least one table - - - - - -- [Node.js](https://nodejs.org/en/) installed on your machine -- A [Microsoft SQL Server](https://docs.microsoft.com/en-us/sql/?view=sql-server-ver15) database - - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) - - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) - - - - - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine -- a [CockroachDB](https://www.cockroachlabs.com) database server running and a database with at least one table - - - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). - -## Set up Prisma ORM - -As a first step, navigate into your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```terminal -npx prisma -``` - - - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. - - - -Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: - -```terminal copy -npx prisma init -``` - -This command does two things: - -- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models -- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - - - - - - - - Connect your database - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx new file mode 100644 index 0000000000..0ec81432d3 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx @@ -0,0 +1,86 @@ +--- +title: 'MongoDB' +metaTitle: 'Add Prisma to an existing MongoDB project (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your MongoDB database and generating a Prisma Client for database access.' +toc: false +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['mongodb'] +sidebar_class_name: hidden-sidebar +--- + + + +Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). + + + +:::tip + +
+ +If you're migrating to Prisma ORM from Mongoose, see our [Migrate from Mongoose guide](/orm/more/migrating-to-prisma/migrate-from-mongoose). + +
+::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine +- Access to a MongoDB 4.2+ server with a replica set deployment. We recommend using [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). + + + + The MongoDB database connector uses transactions to support nested writes. Transactions **requires** a [replica set](https://docs.mongodb.com/manual/tutorial/deploy-replica-set/) deployment. The easiest way to deploy a replica set is with [Atlas](https://docs.atlas.mongodb.com/getting-started/). It's free to get started. + + + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart). + +> See [System requirements](/orm/reference/system-requirements) for exact version requirements. + +## Set up Prisma ORM + +As a first step, navigate into it your project directory that contains the `package.json` file. + +Next, add the Prisma CLI as a development dependency to your project: + +```terminal copy +npm install prisma --save-dev +``` + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma schema](/orm/prisma-schema) file template with the following command: + +```terminal copy +npx prisma init +``` + +This command does two things: + +- creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models +- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) + + + + + Connect your database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/index.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-typescript-mongodb.mdx similarity index 89% rename from docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/index.mdx rename to docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-typescript-mongodb.mdx index eebf0dcd89..d457d68e73 100644 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/index.mdx +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-typescript-mongodb.mdx @@ -6,9 +6,15 @@ hide_table_of_contents: true langSwitcher: ['typescript', 'node'] dbSwitcher: ['mongodb'] sidebar_custom_props: { badge: '15 min' } +sidebar_class_name: hidden-sidebar --- - + Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). @@ -67,24 +73,6 @@ This command does two things: - creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma schema with your database connection variable and schema models - creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection) - - - - - - Connect your database - - - - - - - @@ -98,5 +86,3 @@ This command does two things: - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-node-mongodb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-node-mongodb.mdx new file mode 100644 index 0000000000..c39cf6c902 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-node-mongodb.mdx @@ -0,0 +1,73 @@ +--- +title: 'Connect your database (MongoDB)' +metaTitle: 'Connect your database' +metaDescription: 'Connect your database to your project' +langSwitcher: ['typescript', 'node'] +sidebar_class_name: hidden-sidebar +dbSwitcher: ['mongodb'] +toc: false +--- + + + +## Connecting your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): + +```prisma file=prisma/schema.prisma +datasource db { + provider = "mongodb" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`: + +```bash file=.env +DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase" +``` + +You now need to adjust the connection URL to point to your own database. + +The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For MongoDB, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +```no-lines +mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- `USERNAME`: The name of your database user +- `PASSWORD`: The password for your database user +- `HOST`: The host where a [`mongod`](https://docs.mongodb.com/manual/reference/program/mongod/#mongodb-binary-bin.mongod) (or [`mongos`](https://docs.mongodb.com/manual/reference/program/mongos/#mongodb-binary-bin.mongos)) instance is running +- `PORT`: The port where your database server is running (typically `27017` for MongoDB) +- `DATABASE`: The name of the database + +> If you see the following error: `Error in connector: SCRAM failure: Authentication failed.`, you can specify the source database for the authentication by [adding](https://github.com/prisma/prisma/discussions/9994#discussioncomment-1562283) `?authSource=admin` to the end of the connection string. + + + + + Installation + + + + Introspection + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-typescript-mongodb.mdx similarity index 81% rename from docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database.mdx rename to docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-typescript-mongodb.mdx index e8e25b38da..60f65a077b 100644 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database.mdx +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-typescript-mongodb.mdx @@ -1,5 +1,5 @@ --- -title: 'Connect your database' +title: 'Connect your database (MongoDB)' metaTitle: 'Connect your database' metaDescription: 'Connect your database to your project' langSwitcher: ['typescript', 'node'] @@ -7,6 +7,13 @@ dbSwitcher: ['mongodb'] hide_table_of_contents: true --- + + ## Connecting your database To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): @@ -42,34 +49,6 @@ Here's a short explanation of each component: > If you see the following error: `Error in connector: SCRAM failure: Authentication failed.`, you can specify the source database for the authentication by [adding](https://github.com/prisma/prisma/discussions/9994#discussioncomment-1562283) `?authSource=admin` to the end of the connection string. - - - - - - Installation - - - - Introspection - - - - - - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-node-mongodb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-node-mongodb.mdx new file mode 100644 index 0000000000..d9b36133d7 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-node-mongodb.mdx @@ -0,0 +1,153 @@ +--- +title: 'Introspection' +metaTitle: 'Introspection' +metaDescription: 'Introspection your database with Prisma' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['mongodb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +# Introspection + +Prisma ORM introspects a MongoDB schema by sampling the data stored in the given database and inferring the schema of that data. + +For the purposes of illustrating introspection, this guide will help you setup a MongoDB from scratch. But if you have a MongoDB database already, feel free to jump to [Initializing Prisma ORM](#initializing-prisma-orm) in your project. + +## Setting up your Database + +To see this in action, first create a `blog` database with 2 collections: `User` and `Post`. We recommend [MongoDB Compass](https://www.mongodb.com/products/compass) for setting this up: + +![Create a blog database using Compass](/img/getting-started/1-create-database.jpg) + +First, add a user to our `User` collection: + +![Create a user within the User collection](/img/getting-started/2-create-user.jpg) + +Next, add some posts to our `Post` collection. It's important that the ObjectID in `userId` matches the user you created above. + +![Create some posts within the Post collection](/img/getting-started/3-create-posts.jpg) + +## Initializing Prisma ORM + +Now that you have a MongoDB database, the next step is to create a new project and initialize Prisma ORM: + +```terminal copy +mkdir blog +cd blog +npm init -y +npm install -D prisma +npx prisma init +``` + +Initializing Prisma ORM will create a `prisma/schema.prisma` file. Edit this file to use MongoDB: + +```prisma file=prisma/schema.prisma +datasource db { + provider = "mongodb" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} +``` + +Next you'll need to adjust your `.env` file to point the `DATABASE_URL` to your MongoDB database + +## Introspecting MongoDB with Prisma ORM + +You're now ready to introspect. Run the following command to introspect your database: + +```terminal copy +npx prisma db pull +``` + +This command introspects our database and writes the inferred schema into your `prisma/schema.prisma` file: + +```prisma file=prisma/schema.prisma +datasource db { + provider = "mongodb" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} + +model Post { + id String @id @default(auto()) @map("_id") @db.ObjectId + title String + userId String @db.ObjectId +} + +model User { + id String @id @default(auto()) @map("_id") @db.ObjectId + email String +} +``` + +## Tweaking the Schema + +To be able to join data using Prisma Client, you can add the [`@relation`](/orm/reference/prisma-schema-reference#relation) attributes to our models: + +```prisma file=prisma/schema.prisma highlight=14;add|20;add +datasource db { + provider = "mongodb" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} + +model Post { + id String @id @default(auto()) @map("_id") @db.ObjectId + title String + userId String @db.ObjectId + user User @relation(fields: [userId], references: [id]) +} + +model User { + id String @id @default(auto()) @map("_id") @db.ObjectId + email String + posts Post[] +} +``` + +:::tip + +We're actively working on MongoDB introspection. Provide feedback for this feature in [this issue](https://github.com/prisma/prisma/issues/8241). + +::: + +And with that, you're ready to generate Prisma Client. + + + + + Connect to your Database + + + + Install Prisma Client + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-typescript-mongodb.mdx similarity index 88% rename from docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection.mdx rename to docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-typescript-mongodb.mdx index 03faa6758b..16aaf9c8b4 100644 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection.mdx +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-typescript-mongodb.mdx @@ -7,6 +7,13 @@ dbSwitcher: ['mongodb'] hide_table_of_contents: true --- + + # Introspection Prisma ORM introspects a MongoDB schema by sampling the data stored in the given database and inferring the schema of that data. @@ -122,34 +129,6 @@ We're actively working on MongoDB introspection. Provide feedback for this featu And with that, you're ready to generate Prisma Client. - - - - - - Connect to your Database - - - - Install Prisma Client - - - - - - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-node-mongodb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-node-mongodb.mdx new file mode 100644 index 0000000000..d2483e91b6 --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-node-mongodb.mdx @@ -0,0 +1,53 @@ +--- +title: 'Install Prisma Client' +metaTitle: 'Install Prisma Client' +metaDescription: 'Install and generate Prisma Client in your project' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['mongodb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install the `@prisma/client` package: + +```terminal copy +npm install @prisma/client +``` + +The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. + +![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) + +Whenever you make changes to your Prisma schema in the future, you manually need to invoke `prisma generate` in order to accommodate the changes in your Prisma Client API. + + + + + + Introspection + + + + Querying the database + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx similarity index 72% rename from docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client.mdx rename to docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx index faef472a33..1543aa843f 100644 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client.mdx +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx @@ -7,6 +7,13 @@ dbSwitcher: ['mongodb'] hide_table_of_contents: true --- + + ## Install and generate Prisma Client To get started with Prisma Client, you need to install the `@prisma/client` package: @@ -21,34 +28,6 @@ The install command invokes `prisma generate` for you which reads your Prisma sc Whenever you make changes to your Prisma schema in the future, you manually need to invoke `prisma generate` in order to accommodate the changes in your Prisma Client API. - - - - - - Introspection - - - - Querying the database - - - - - - - - - - diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-node-mongodb.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-node-mongodb.mdx new file mode 100644 index 0000000000..5a9556b44d --- /dev/null +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-node-mongodb.mdx @@ -0,0 +1,237 @@ +--- +title: 'Querying the database' +metaTitle: 'Querying the database' +metaDescription: 'Write data to and query the database' +langSwitcher: ['typescript', 'node'] +dbSwitcher: ['mongodb'] +hide_table_of_contents: true +sidebar_class_name: hidden-sidebar +--- + + + +## Write your first query with Prisma Client + +Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + +If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. + +For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + +Create a new file named `index.js` and add the following code to it: + +```js file=index.js copy +const { PrismaClient } = require('@prisma/client') + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function named `main` to send queries to the database +1. Connect to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the following query to read all `User` records from the database and print the result: + +```js file=index.js +async function main() { +- // ... you will write your Prisma Client queries here ++ const allUsers = await prisma.user.findMany() ++ console.log(allUsers) +} +``` + +Now run the code with this command: + +```terminal copy +node index.js +``` + +If you introspected an existing database with records, the query should return an array of JavaScript objects. + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post`, `User` and `Comment` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js file=index.js copy +async function main() { + await prisma.user.create({ + data: { + name: 'Rich', + email: 'hello@prisma.com', + posts: { + create: { + title: 'My first post', + body: 'Lots of really interesting stuff', + slug: 'my-first-post', + }, + }, + }, + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with a new `Post` using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the other one via the `Post.author` ↔ `User.posts` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` relations on the returned `User` objects. + +Run the code with this command: + +```terminal copy +node index.js +``` + +The output should look similar to this: + +```json5 no-lines +[ + { + id: '60cc9b0e001e3bfd00a6eddf', + email: 'hello@prisma.com', + name: 'Rich', + posts: [ + { + id: '60cc9bad005059d6007f45dd', + slug: 'my-first-post', + title: 'My first post', + body: 'Lots of really interesting stuff', + userId: '60cc9b0e001e3bfd00a6eddf', + }, + ], + }, +] +``` + +The query added new records to the `User` and the `Post` collections: + + + +The `id` field in the Prisma schema maps to `_id` in the underlying MongoDB database. + + + +**User** collection + +| **\_id** | **email** | **name** | +| :------------------------- | :------------------- | :------- | +| `60cc9b0e001e3bfd00a6eddf` | `"hello@prisma.com"` | `"Rich"` | + +**Post** collection + +| **\_id** | **createdAt** | **title** | **content** | **published** | **authorId** | +| :------------------------- | :------------------------- | :---------------- | :--------------------------------- | :------------ | :------------------------- | +| `60cc9bad005059d6007f45dd` | `2020-03-21T16:45:01.246Z` | `"My first post"` | `Lots of really interesting stuff` | `false` | `60cc9b0e001e3bfd00a6eddf` | + +> **Note**: The unique identifier in the `authorId` document field on `Post` reference the `_id` document field in the `User` collection, meaning the `_id` value `60cc9b0e001e3bfd00a6eddf` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll add a couple of comments to the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js file=index.js copy +async function main() { + await prisma.post.update({ + where: { + slug: 'my-first-post', + }, + data: { + comments: { + createMany: { + data: [ + { comment: 'Great post!' }, + { comment: "Can't wait to read more!" }, + ], + }, + }, + }, + }) + const posts = await prisma.post.findMany({ + include: { + comments: true, + }, + }) + + console.dir(posts, { depth: Infinity }) +} +``` + +Now run the code using the same command as before: + +```terminal copy +node index.js +``` + +You will see the following output: + +```json5 no-lines +[ + { + id: '60cc9bad005059d6007f45dd', + slug: 'my-first-post', + title: 'My first post', + body: 'Lots of really interesting stuff', + userId: '60cc9b0e001e3bfd00a6eddf', + comments: [ + { + id: '60cca420008a21d800578793', + postId: '60cca40300af8bf000f6ca99', + comment: 'Great post!', + }, + { + id: '60cca420008a21d800578794', + postId: '60cca40300af8bf000f6ca99', + comment: "Can't wait to try this!", + }, + ], + }, +] +``` + +Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 + + + + + Install Prisma Client + + + + Next Steps + + + diff --git a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database.mdx b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-typescript-mongodb.mdx similarity index 71% rename from docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database.mdx rename to docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-typescript-mongodb.mdx index 8cd27930d4..8a004062be 100644 --- a/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database.mdx +++ b/docs/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-typescript-mongodb.mdx @@ -7,6 +7,13 @@ dbSwitcher: ['mongodb'] hide_table_of_contents: true --- + + ## Write your first query with Prisma Client Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. @@ -15,8 +22,6 @@ If you're building a REST API, you can use Prisma Client in your route handlers For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - - Create a new file named `index.ts` and add the following code to it: ```js file=index.ts copy @@ -39,34 +44,6 @@ main() }) ``` - - - - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js copy -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - - - Here's a quick overview of the different parts of the code snippet: 1. Import the `PrismaClient` constructor from the `@prisma/client` node module @@ -78,8 +55,6 @@ Here's a quick overview of the different parts of the code snippet: Inside the `main` function, add the following query to read all `User` records from the database and print the result: - - ```ts file=index.ts async function main() { // ... you will write your Prisma Client queries here @@ -88,38 +63,12 @@ async function main() { } ``` - - - - -```js file=index.js -async function main() { -- // ... you will write your Prisma Client queries here -+ const allUsers = await prisma.user.findMany() -+ console.log(allUsers) -} -``` - - - Now run the code with this command: - - ```terminal copy npx ts-node index.ts ``` - - - - -```terminal copy -node index.js -``` - - - If you introspected an existing database with records, the query should return an array of JavaScript objects. ## Write data into the database @@ -128,8 +77,6 @@ The `findMany` query you used in the previous section only _reads_ data from the Adjust the `main` function to send a `create` query to the database: - - ```ts file=index.ts copy async function main() { await prisma.user.create({ @@ -155,59 +102,16 @@ async function main() { } ``` - - - - -```js file=index.js copy -async function main() { - await prisma.user.create({ - data: { - name: 'Rich', - email: 'hello@prisma.com', - posts: { - create: { - title: 'My first post', - body: 'Lots of really interesting stuff', - slug: 'my-first-post', - }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - - - This code creates a new `User` record together with a new `Post` using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the other one via the `Post.author` ↔ `User.posts` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` relations on the returned `User` objects. Run the code with this command: - - ```terminal copy npx ts-node index.ts ``` - - - - -```terminal copy -node index.js -``` - - - The output should look similar to this: ```json5 no-lines @@ -229,8 +133,6 @@ The output should look similar to this: ] ``` - - Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: ```ts no-lines @@ -247,8 +149,6 @@ export type Post = { } ``` - - The query added new records to the `User` and the `Post` collections: @@ -273,8 +173,6 @@ The `id` field in the Prisma schema maps to `_id` in the underlying MongoDB data Before moving on to the next section, you'll add a couple of comments to the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - - ```ts file=index.ts copy async function main() { await prisma.post.update({ @@ -302,59 +200,12 @@ async function main() { } ``` - - - - -```js file=index.js copy -async function main() { - await prisma.post.update({ - where: { - slug: 'my-first-post', - }, - data: { - comments: { - createMany: { - data: [ - { comment: 'Great post!' }, - { comment: "Can't wait to read more!" }, - ], - }, - }, - }, - }) - const posts = await prisma.post.findMany({ - include: { - comments: true, - }, - }) - - console.dir(posts, { depth: Infinity }) -} -``` - - - - - Now run the code using the same command as before: ```terminal copy npx ts-node index.ts ``` - - - - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - - - You will see the following output: ```json5 no-lines @@ -383,29 +234,6 @@ You will see the following output: Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 - - - - - - Install Prisma Client - - - - Next Steps - - - - - - - - - - diff --git a/docs/200-orm/200-prisma-client/450-testing/index.mdx b/docs/200-orm/200-prisma-client/450-testing/index.mdx index 849d0ec882..ca0152c8ae 100644 --- a/docs/200-orm/200-prisma-client/450-testing/index.mdx +++ b/docs/200-orm/200-prisma-client/450-testing/index.mdx @@ -3,6 +3,7 @@ title: 'Testing' navTitle: Testing metaTitle: 'Testing with Prisma ORM' metaDescription: 'How to implement unit and integration testing with Prisma ORM' +hide_table_of_contents: true --- diff --git a/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/02-schema-incompatibilities-mysql.mdx b/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/02-schema-incompatibilities-mysql.mdx new file mode 100644 index 0000000000..7522000083 --- /dev/null +++ b/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/02-schema-incompatibilities-mysql.mdx @@ -0,0 +1,767 @@ +--- +title: 'Schema incompatibilities' +metaTitle: 'Schema Incompatibilities | MySQL' +metaDescription: 'Problems and workarounds for Prisma 1 and 2.0 schemas with MySQL' +dbSwitcher: ['postgresql', 'mysql'] +sidebar_class_name: hidden-sidebar +--- + + + +## Overview + +Each section on this page describes a potential problem when upgrading from Prisma 1 to Prisma ORM 2._x_ and later and explains the available workarounds. + +## Default values aren't represented in database + +### Problem + +When adding the `@default` directive in a Prisma 1 datamodel, the default values for this field are generated by the Prisma 1 server at runtime. There's no `DEFAULT` constraint added to the database column. Because this constraint is not reflected in the database itself, the Prisma ORM 2._x_ and later versions of introspection can't recognize it. + +### Example + +#### Prisma 1 datamodel + +```graphql +type Post { + id: ID! @id + published: Boolean @default(value: false) +} +``` + +#### Prisma 1 generated SQL migration + +```sql +CREATE TABLE "Post" ( + id VARCHAR(25) PRIMARY KEY NOT NULL, + published BOOLEAN NOT NULL +); +``` + +#### Result of introspection in Prisma ORM versions 2._x_ and later + +```prisma file=schema.prisma +model Post { + id String @id + published Boolean +} +``` + +Because the `DEFAULT` constraint has not been added to the database when mapping the Prisma 1 datamodel to the database with `prisma deploy`, Prisma ORM v2 (and later versions) doesn't recognize it during introspection. + +### Workarounds + +#### Manually add a `DEFAULT` constraint to the database column + +You can alter the column to add the `DEFAULT` constraint as follows: + +```sql +ALTER TABLE `Post` + ALTER COLUMN published SET DEFAULT false; +``` + +After this adjustment, you can re-introspect your database and the `@default` attribute will be added to the `published` field: + +```prisma line-number file=schema.prisma highlight=3;normal +model Post { + id String @id + published Boolean @default(false) +} +``` + +#### Manually add a `@default` attribute to the Prisma model + +You can add the `@default` attribute to the Prisma model: + +```prisma line-number file=schema.prisma highlight=3;add +model Post { + id String + published Boolean @default(false) +} +``` + +If the `@default` attribute is set in the Prisma schema and you run `prisma generate`, the resulting Prisma Client code will generate the specified default values at runtime (similar to what the Prisma 1 server did in Prisma 1). + +## Generated CUIDs as ID values aren't represented in database + +### Problem + +Prisma 1 auto-generates ID values as CUIDs for `ID` fields when they're annotated with the `@id` directive. These CUIDs are generated by the Prisma 1 server at runtime. Because this behavior is not reflected in the database itself, the introspection in Prisma ORM 2._x_ and later can't recognize it. + +### Example + +#### Prisma 1 datamodel + +```graphql +type Post { + id: ID! @id +} +``` + +#### Prisma 1 generated SQL migration + +```sql +CREATE TABLE "Post" ( + id VARCHAR(25) PRIMARY KEY NOT NULL +); +``` + +#### Result of introspection in Prisma ORM versions 2._x_ and later + +```prisma file=schema.prisma +model Post { + id String @id +} +``` + +Because there's no indication of the CUID behavior in the database, Prisma ORM's introspection doesn't recognize it. + +### Workaround + +As a workaround, you can manually add the `@default(cuid())` attribute to the Prisma model: + +```prisma line-number file=schema.prisma highlight=2;add +model Post { + id String @id @default(cuid()) +} +``` + +If the `@default` attribute is set in the Prisma schema and you run `prisma generate`, the resulting Prisma Client code will generate the specified default values at runtime (similar to what the Prisma 1 server did in Prisma 1). + +Note that you'll have to re-add the attribute after each introspection because introspection removes it (as the previous version of the Prisma schema is overwritten)! + +## `@createdAt` isn't represented in database + +### Problem + +Prisma 1 auto-generates values for `DateTime` fields when they're annotated with the `@createdAt` directive. These values are generated by the Prisma 1 server at runtime. Because this behavior is not reflected in the database itself, the introspection in Prisma ORM 2._x_ and later can't recognize it. + +### Example + +#### Prisma 1 datamodel + +```graphql line-number highlight=3;normal +type Post { + id: ID! @id + createdAt: DateTime! @createdAt +} +``` + +#### Prisma 1 generated SQL migration + +```sql +CREATE TABLE "Post" ( + id VARCHAR(25) PRIMARY KEY NOT NULL, + "createdAt" TIMESTAMP NOT NULL +); +``` + +#### Result of introspection in Prisma ORM 2._x_ and later versions + +```prisma file=schema.prisma +model Post { + id String @id + createdAt DateTime +} +``` + +### Workarounds + +#### Manually add `DEFAULT CURRENT_TIMESTAMP` to the database column + +You can alter the column to add the `DEFAULT` constraint as follows: + +```sql +ALTER TABLE "Post" + ALTER COLUMN "createdAt" SET DEFAULT CURRENT_TIMESTAMP; +``` + +After this adjustment, you can re-introspect your database and the `@default` attribute will be added to the `createdAt` field: + +```prisma file=schema.prisma +model Post { + id String + createdAt DateTime @default(now()) +} +``` + +#### Manually add the `@default(now())` attribute to the Prisma model + +As a workaround, you can manually add the `@default(now())` attribute to the Prisma model: + +```prisma line-number file=schema.prisma highlight=3;normal +model Post { + id String @id + createdAt DateTime @default(now()) +} +``` + +If the `@default` attribute is set in the Prisma schema and you run `prisma generate`, the resulting Prisma Client code will generate the specified default values at runtime (similar to what the Prisma 1 server did in Prisma 1). + +Note that you'll have to re-add the attribute after each introspection because introspection removes it (as the previous version of the Prisma schema is overwritten)! + +## `@updatedAt` isn't represented in database + +### Problem + +Prisma 1 auto-generates values for `DateTime` fields when they're annotated with the `@updatedAt` directive. These values are generated by the Prisma 1 server at runtime. Because this behavior is not reflected in the database itself, the introspection in Prisma ORM 2._x_ and later can't recognize it.. + +### Example + +#### Prisma 1 datamodel + +```graphql +type Post { + id: ID! @id + updatedAt: DateTime! @updatedAt +} +``` + +#### Prisma 1 generated SQL migration + +```sql +CREATE TABLE "Post" ( + id VARCHAR(25) PRIMARY KEY NOT NULL, + updatedAt TIMESTAMP +); +``` + +#### Result of introspection in Prisma ORM 2._x_ and later versions + +```prisma file=schema.prisma +model Post { + id String @id + updatedAt DateTime +} +``` + +### Workarounds + +#### Manually add the `@updatedAt` attribute to the Prisma model + +As a workaround, you can manually add the `@updatedAt` attribute to the Prisma model: + +```prisma line-number file=schema.prisma highlight=3;add +model Post { + id String @id + updatedAt DateTime @updatedAt +} +``` + +If the `@updatedAt` attribute is set in the Prisma schema and you run `prisma generate`, the resulting Prisma Client code will automatically generate values for this column when an existing record is updated (similar to what the Prisma 1 server did in Prisma 1). + +Note that you'll have to re-add the attribute after each introspection because introspection removes it (as the previous version of the Prisma schema is overwritten)! + +## Inline 1-1 relations are recognized as 1-n (missing `UNIQUE` constraint) + +### Problem + +In the [datamodel v1.1](https://www.prisma.io/blog/datamodel-v11-lrzqy1f56c90) that was introduced in Prisma ORM v1.31, 1-1 relations can be declared as _inline_. In that case, the relation will not be maintained via a [relation table](/orm/prisma-schema/data-model/relations/many-to-many-relations#relation-tables) but via a single foreign key on one of the two tables involved. + +When this approach is used, Prisma ORM doesn't add a `UNIQUE` constraint to the foreign key column which means that after introspection in Prisma ORM version 2._x_ and later, this former 1-1 relation will be added as a 1-n relation to the Prisma schema. + +### Example + +#### Prisma ORM datamodel v1.1 (available from Prisma ORM v1.31) + +```graphql +type User { + id: ID! @id + profile: Profile @relation(link: INLINE) +} + +type Profile { + id: ID! @id + user: User +} +``` + +Note that omitting the `@relation` directive in this case would result in the same behavior because `link: INLINE` is the _default_ for 1-1 relations. + +#### Prisma 1 generated SQL migration + +```sql +CREATE TABLE "User" ( + id VARCHAR(25) PRIMARY KEY NOT NULL +); + +CREATE TABLE "Profile" ( + id VARCHAR(25) PRIMARY KEY NOT NULL, + "user" VARCHAR(25), + FOREIGN KEY ("user") REFERENCES "User"(id) +); +``` + +#### Result of introspection in Prisma ORM 2._x_ and later versions + +```prisma file=schema.prisma +model User { + id String @id + Profile Profile[] +} + +model Profile { + id String @id + user String? + User User? @relation(fields: [user], references: [id]) +} +``` + +Because there's no `UNIQUE` constraint defined on the `user` column (which represents the foreign key in this relation), Prisma ORM's introspection recognizes the relation as 1-n. + +### Workaround + +#### Manually add `UNIQUE` constraint to the foreign key column + +You can alter the foreign key column to add the `UNIQUE` constraint as follows: + +```sql +ALTER TABLE `Profile` + ADD CONSTRAINT userId_unique UNIQUE (`user`); +``` + +After this adjustment, you can re-introspect your database and the 1-1 relation will be properly recognized: + +```prisma line-number file=schema.prisma highlight=3;normal +model User { + id String @id + Profile Profile? +} + +model Profile { + id String @id + user String? @unique + User User? @relation(fields: [user], references: [id]) +} +``` + +## _All_ non-inline relations are recognized as m-n + +### Problem + +Prisma 1 represents relations as relation tables most of the time: + +- All relations in the Prisma 1 **datamodel v1.0** are represented as relation tables +- In **datamodel v1.1**, all m-n relations as well as the 1-1 and 1-n relations declared as `link: TABLE` are represented as relation tables. + +Because of this representation, introspection in Prisma ORM version 2._x_ and later will recognize all these relations as m-n relations, even though they might have been declared as 1-1 or 1-n in Prisma 1. + +### Example + +#### Prisma 1 datamodel + +```graphql +type User { + id: ID! @id + posts: [Post!]! +} + +type Post { + id: ID! @id + author: User! @relation(link: TABLE) +} +``` + +#### Prisma 1 generated SQL migration + +```sql +CREATE TABLE "User" ( + id VARCHAR(25) PRIMARY KEY NOT NULL +); + +CREATE TABLE "Post" ( + id VARCHAR(25) PRIMARY KEY NOT NULL +); + +CREATE TABLE "_PostToUser" ( + "A" VARCHAR(25) NOT NULL REFERENCES "Post"(id) ON DELETE CASCADE, + "B" VARCHAR(25) NOT NULL REFERENCES "User"(id) ON DELETE CASCADE +); +CREATE UNIQUE INDEX "_PostToUser_AB_unique" ON "_PostToUser"("A" text_ops,"B" text_ops); +CREATE INDEX "_PostToUser_B" ON "_PostToUser"("B" text_ops); +``` + +#### Result of introspection in Prisma ORM 2._x_ and later versions + +```prisma file=schema.prisma +model User { + id String @id + Post Post[] @relation(references: [id]) +} + +model Post { + id String @id + User User[] @relation(references: [id]) +} +``` + +Because the relation table that was created by Prisma 1 uses the same [conventions for relation tables](/orm/prisma-schema/data-model/relations/many-to-many-relations#conventions-for-relation-tables-in-implicit-m-n-relations) as in Prisma ORM version 2._x_ and later, the relation now gets recognized as a m-n relation. + +### Workaround + +As a workaround, you can migrate the data into a structure that's compatible with Prisma ORM's 1-n relation: + +1. Create new column `authorId` on the `Post` table. This column should be a _foreign key_ that references the `id` field of the `User` table: + ```sql + ALTER TABLE `Post` ADD COLUMN `authorId` VARCHAR(25); + ALTER TABLE `Post` ADD FOREIGN KEY (`authorId`) REFERENCES `User` (`id`); + ``` +1. Write a SQL query that reads all the rows from the `_PostToUser` relation table and for each row: + 1. Finds the respective `Post` record by looking up the value from column `A` + 1. Inserts the value from column `B` as the value for `authorId` into that `Post` record + ```sql + UPDATE Post, _PostToUser + SET Post.authorId = _PostToUser.B + WHERE Post.id = _PostToUser.A + ``` +1. Delete the `_PostToUser` relation table + ```sql + DROP TABLE `_PostToUser`; + ``` + +After that you can introspect your database and the relation will now be recognized as 1-n: + +```prisma line-number file=schema.prisma highlight=3,8,9;normal +model User { + id String @id + Post Post[] +} + +model Post { + id String @id + User User @relation(fields: [authorId], references: [id]) + authorId String +} +``` + +## `Json` type is represented as `TEXT` in database + +### Problem + +Prisma 1 supports the `Json` data type in its datamodel. However, in the underlying database, fields of type `Json` are actually stored as plain strings using the `TEXT` data type of the underlying database. Any parsing and validation of the stored JSON data is done by the Prisma 1 server at runtime. + +### Example + +#### Prisma 1 datamodel + +```graphql +type User { + id: ID! @id + jsonData: Json +} +``` + +#### Prisma 1 generated SQL migration + +```sql +CREATE TABLE "User" ( + id VARCHAR(25) PRIMARY KEY NOT NULL, + jsonData TEXT +); +``` + +#### Result of introspection in Prisma ORM 2._x_ and later versions + +```prisma file=schema.prisma +model User { + id String @id + jsonData String? +} +``` + +### Workaround + +You can manually change the type of the column to `JSON` + +```sql +ALTER TABLE User MODIFY COLUMN jsonData JSON; +``` + +After this adjustment, you can re-introspect your database and the field will now be recognized as `Json`: + +```prisma line-number file=schema.prisma highlight=3;normal +model User { + id String @id + jsonData Json? +} +``` + +## Enums are represented as `TEXT` in database + +### Problem + +Prisma 1 supports the `enum` data type in its datamodel. However, in the underlying database, types declared as `enum` are actually stored as plain strings using the `TEXT` data type of the underlying database. Any validation of the stored `enum` data is done by the Prisma 1 server at runtime. + +### Example + +#### Prisma 1 datamodel + +```graphql +type User { + id: ID! @id + role: Role +} + +enum Role { + ADMIN + CUSTOMER +} +``` + +#### Prisma 1 generated SQL migration + +```sql +CREATE TABLE "User" ( + id VARCHAR(25) PRIMARY KEY NOT NULL, + role TEXT +); +``` + +#### Result of introspection in Prisma ORM 2._x_ and later versions + +```prisma file=schema.prisma +model User { + id String @id + role String? +} +``` + +### Workaround + +You can manually turn the `role` column into an enum with your desired values: + +1. Create an `enum` in your database that mirrors the `enum` you defined in the Prisma 1 datamodel: + ```sql + CREATE TYPE "Role" AS ENUM ('CUSTOMER', 'ADMIN'); + ``` +1. Change the type from `TEXT` to your new `enum`: + ```sql + ALTER TABLE "User" ALTER COLUMN "role" TYPE "Role" + USING "role"::text::"Role"; + ``` + +After introspection, the type is now properly recognized as an enum: + +```prisma line-number file=schema.prisma highlight=3,6-9;normal +model User { + id String @id + role Role? +} + +enum Role { + ADMIN + CUSTOMER +} +``` + +## Mismatching CUID length + +### Problem + +Prisma 1 uses CUIDs as ID values for all database records. In the underlying database, these IDs are represented as strings with a maximum size of 25 characters (as `VARCHAR(25)`). However, when configuring default CUIDs in your Prisma ORM 2._x_ (or later versions) schema with `@default(cuid())` the generated ID values might exceed the limit of 25 characters (the maximum length might be 30 characters). To make your IDs proof for Prisma ORM 2._x_ (or later versions), you therefore need to adjust the column type to `VARCHAR(30)`. + +### Example + +#### Prisma 1 datamodel + +```graphql +type User { + id: ID! @id +} +``` + +#### Prisma 1 generated SQL migration + +```sql +CREATE TABLE "User" ( + id VARCHAR(25) PRIMARY KEY NOT NULL +); +``` + +#### Result of introspection in Prisma ORM 2._x_ and later versions + +```prisma file=schema.prisma +model User { + id String @id +} +``` + +### Workaround + +You can manually turn the `VARCHAR(25)` columns into `VARCHAR(30)`: + +```sql +SET FOREIGN_KEY_CHECKS=0; +ALTER TABLE `User` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; +SET FOREIGN_KEY_CHECKS=1; +``` + +> **Note**: When fixing this issue with the [Upgrade CLI](/orm/more/upgrade-guides/upgrade-from-prisma-1/how-to-upgrade#prisma-1-upgrade-cli), the generated SQL statements will keep appearing in the Upgrade CLI even after you have changed the column types in the underlying database. This is a currently a limitation in the Upgrade CLI. + +## Scalar lists (arrays) are maintained with extra table + +### Problem + +In Prisma 1, you can define lists of _scalar_ types on your models. Under the hood, this is implemented with an extra table that keeps track of the values in the list. + +To remove the approach with the extra table which incurred hidden performance costs, Prisma ORM 2._x_ and later versions only support scalar lists only when they're natively supported by the database you use. At the moment, only [PostgreSQL supports scalar lists (arrays) natively](https://www.postgresql.org/docs/9.1/arrays.html). + +With PostgreSQL, you therefore can keep using scalar lists in Prisma ORM 2._x_ and later versions, but you'll need to perform a data migration to transfer the data from the extra table from Prisma 1 into an actual PostgreSQL array. + +### Example + +#### Prisma 1 datamodel + +```graphql +type User { + id: ID! @id + coinflips: [Boolean!]! @scalarList(strategy: RELATION) +} +``` + +#### Prisma 1 generated SQL migration + +```sql +CREATE TABLE "User" ( + id VARCHAR(25) PRIMARY KEY NOT NULL +); + +CREATE TABLE "User_coinflips" ( + "nodeId" VARCHAR(25) REFERENCES "User"(id), + position INTEGER, + value BOOLEAN NOT NULL, + CONSTRAINT "User_coinflips_pkey" PRIMARY KEY ("nodeId", position) +); +CREATE UNIQUE INDEX "User_coinflips_pkey" ON "User_coinflips"("nodeId" text_ops,position int4_ops); +``` + +#### Result of Prisma ORM 2 introspection + +```prisma file=schema.prisma +model User { + id String @id + User_coinflips User_coinflips[] +} + +model User_coinflips { + nodeId String + position Int + value Boolean + User User @relation(fields: [nodeId], references: [id]) + + @@id([nodeId, position]) +} +``` + +Note that you can now generate Prisma Client and you'll be able to access the data from the scalar lists through the extra table. PostgreSQL users can alternatively migrate the data into a native PostgreSQL array and continue to benefit from the slicker Prisma Client API for scalar lists (read the section below for more info). + +
+ +Expand for sample Prisma Client API calls + +To access the coinflips data, you will now have to always [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields) it in your queries: + +```ts +const user = await prisma.user.findUnique({ + where: { id: 1 }, + include: { + coinflips: { + orderBy: { position: 'asc' }, + }, + }, +}) +``` + +> **Note**: The `orderBy` is important to retain the order of the list. + +This is the `result of the query: + +```js +{ + id: 1, + name: 'Alice', + coinflips: [ + { id: 1, position: 1000, value: false }, + { id: 2, position: 2000, value: true }, + { id: 3, position: 3000, value: false }, + { id: 4, position: 4000, value: true }, + { id: 5, position: 5000, value: true }, + { id: 6, position: 6000, value: false } + ] +} +``` + +To access just the boolean values from the list, you can `map` over the `coinflips` on `user` as follows: + +```ts +const currentCoinflips = user!.coinflips.map((cf) => cf.value) +``` + +> **Note**: The exclamation mark above means that you're _force unwrapping_ the `user` value. This is necessary because the `user` returned from the previous query might be `null`. + +Here's the value of `currentCoinflips` after the call to `map`: + +```json5 +[false, true, false, true, true, false] +``` + +
+ +### Workaround + +The following workaround is only available for PostgreSQL users! + +As scalar lists (i.e. [arrays](https://www.postgresql.org/docs/9.1/arrays.html)) are available as a native PostgreSQL feature, you can keep using the same notation of `coinflips: Boolean[]` in your Prisma schema. + +However, in order to do so you need to manually migrate the underlying data from the `User_coinflips` table into a PostgreSQL array. Here's how you can do that: + +1. Add the new `coinflips` column to the `User` tables: + ```sql + ALTER TABLE "User" ADD COLUMN coinflips BOOLEAN[]; + ``` +1. Migrate the data from `"User_coinflips".value` to `"User.coinflips"`: + ```sql + UPDATE "User" + SET coinflips = t.flips + FROM ( + SELECT "nodeId", array_agg(VALUE ORDER BY position) AS flips + FROM "User_coinflips" + GROUP BY "nodeId" + ) t + where t."nodeId" = "User"."id"; + ``` +1. To cleanup, you can delete the `User_coinflips` table: + ```sql + DROP TABLE "User_coinflips"; + ``` + +You can now introspect your database and the `coinflips` field will be represented as an array in your new Prisma schema: + +```prisma file=schema.prisma +model User { + id String @id + coinflips Boolean[] +} +``` + +You can keep using Prisma Client as before: + +```ts +const user = await prisma.user.findUnique({ + where: { id: 1 }, +}) +``` + +This is the result from the API call: + +```js +{ + id: 1, + name: 'Alice', + coinflips: [ false, true, false, true, true, false ] +} +``` diff --git a/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/02-schema-incompatibilities.mdx b/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/02-schema-incompatibilities-postgresql.mdx similarity index 89% rename from docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/02-schema-incompatibilities.mdx rename to docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/02-schema-incompatibilities-postgresql.mdx index e2435a90f8..10cf8ec61f 100644 --- a/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/02-schema-incompatibilities.mdx +++ b/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/02-schema-incompatibilities-postgresql.mdx @@ -1,26 +1,16 @@ --- title: 'Schema incompatibilities' -# metaTitle: 'Problems and workarounds for Prisma 1 and 2.x and later schemas' -# metaDescription: 'Learn about the schema incompatibilities between Prisma 1 and Prisma ORM versions 2 and later, and how to resolve them with several workarounds.' +metaTitle: 'Schema Incompatibilities | PostgreSQL' +metaDescription: 'Problems and workarounds for Prisma 1 and 2.0 schemas with PostgreSQL' dbSwitcher: ['postgresql', 'mysql'] -techMetaTitles: - [ - { name: 'mysql', value: 'Schema Incompatibilities | MySQL' }, - { name: 'postgresql', value: 'Schema Incompatibilities | PostgreSQL' }, - ] -techMetaDescriptions: - [ - { - name: 'mysql', - value: 'Problems and workarounds for Prisma 1 and 2.0 schemas with MySQL', - }, - { - name: 'postgresql', - value: 'Problems and workarounds for Prisma 1 and 2.0 schemas with PostgreSQL', - }, - ] --- + + ## Overview Each section on this page describes a potential problem when upgrading from Prisma 1 to Prisma ORM 2._x_ and later and explains the available workarounds. @@ -68,24 +58,11 @@ Because the `DEFAULT` constraint has not been added to the database when mapping You can alter the column to add the `DEFAULT` constraint as follows: - - ```sql ALTER TABLE "Post" ALTER COLUMN published SET DEFAULT false; ``` - - - - -```sql -ALTER TABLE `Post` - ALTER COLUMN published SET DEFAULT false; -``` - - - After this adjustment, you can re-introspect your database and the `@default` attribute will be added to the `published` field: ```prisma line-number file=schema.prisma highlight=3;normal @@ -341,24 +318,11 @@ Because there's no `UNIQUE` constraint defined on the `user` column (which repre You can alter the foreign key column to add the `UNIQUE` constraint as follows: - - ```sql ALTER TABLE "Profile" ADD CONSTRAINT userId_unique UNIQUE ("user"); ``` - - - - -```sql -ALTER TABLE `Profile` - ADD CONSTRAINT userId_unique UNIQUE (`user`); -``` - - - After this adjustment, you can re-introspect your database and the 1-1 relation will be properly recognized: ```prisma line-number file=schema.prisma highlight=3;normal @@ -440,8 +404,6 @@ Because the relation table that was created by Prisma 1 uses the same [conventio As a workaround, you can migrate the data into a structure that's compatible with Prisma ORM's 1-n relation: - - 1. Create new column `authorId` on the `Post` table. This column should be a _foreign key_ that references the `id` field of the `User` table: ```sql ALTER TABLE "Post" ADD COLUMN "authorId" VARCHAR(25); @@ -464,30 +426,6 @@ As a workaround, you can migrate the data into a structure that's compatible wit DROP TABLE "_PostToUser"; ``` - - - - -1. Create new column `authorId` on the `Post` table. This column should be a _foreign key_ that references the `id` field of the `User` table: - ```sql - ALTER TABLE `Post` ADD COLUMN `authorId` VARCHAR(25); - ALTER TABLE `Post` ADD FOREIGN KEY (`authorId`) REFERENCES `User` (`id`); - ``` -1. Write a SQL query that reads all the rows from the `_PostToUser` relation table and for each row: - 1. Finds the respective `Post` record by looking up the value from column `A` - 1. Inserts the value from column `B` as the value for `authorId` into that `Post` record - ```sql - UPDATE Post, _PostToUser - SET Post.authorId = _PostToUser.B - WHERE Post.id = _PostToUser.A - ``` -1. Delete the `_PostToUser` relation table - ```sql - DROP TABLE `_PostToUser`; - ``` - - - After that you can introspect your database and the relation will now be recognized as 1-n: ```prisma line-number file=schema.prisma highlight=3,8,9;normal @@ -542,22 +480,10 @@ model User { You can manually change the type of the column to `JSON` - - ```sql ALTER TABLE "User" ALTER COLUMN "jsonData" TYPE JSON USING "jsonData"::json; ``` - - - - -```sql -ALTER TABLE User MODIFY COLUMN jsonData JSON; -``` - - - After this adjustment, you can re-introspect your database and the field will now be recognized as `Json`: ```prisma line-number file=schema.prisma highlight=3;normal @@ -671,24 +597,10 @@ model User { You can manually turn the `VARCHAR(25)` columns into `VARCHAR(30)`: - - ```sql ALTER TABLE "User" ALTER COLUMN "id" SET DATA TYPE character varying(30); ``` - - - - -```sql -SET FOREIGN_KEY_CHECKS=0; -ALTER TABLE `User` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; -SET FOREIGN_KEY_CHECKS=1; -``` - - - > **Note**: When fixing this issue with the [Upgrade CLI](/orm/more/upgrade-guides/upgrade-from-prisma-1/how-to-upgrade#prisma-1-upgrade-cli), the generated SQL statements will keep appearing in the Upgrade CLI even after you have changed the column types in the underlying database. This is a currently a limitation in the Upgrade CLI. ## Scalar lists (arrays) are maintained with extra table diff --git a/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer-mysql.mdx b/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer-mysql.mdx new file mode 100644 index 0000000000..44568fff60 --- /dev/null +++ b/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer-mysql.mdx @@ -0,0 +1,1315 @@ +--- +title: 'Upgrading the Prisma ORM layer' +metaTitle: 'Upgrading the Prisma ORM layer to Prisma ORM 2 | MySQL' +metaDescription: 'Learn how to upgrade the Prisma ORM layer to Prisma ORM 2 and create your Prisma schema with MySQL' +dbSwitcher: ['postgresql', 'mysql'] +sidebar_class_name: hidden-sidebar +--- + + + +## Overview + +This page explains the first step of your upgrade process: Taking your Prisma 1 configuration and upgrading it to Prisma ORM 2. Concretely, you will learn how to: + +1. Add the Prisma ORM 2 CLI as a development dependency +1. Create your Prisma ORM 2 schema +1. Determine your connection URL and connect to your database +1. Introspect your database (that was so far managed with Prisma 1) +1. Use the [Prisma 1 Upgrade CLI](/orm/more/upgrade-guides/upgrade-from-prisma-1/how-to-upgrade#prisma-1-upgrade-cli) to resolve the [schema incompatibilities](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql) in the new Prisma ORM 2 data model +1. Install and generate Prisma Client + +Once done with these steps, you can move on to the next guide that explains how you can upgrade the application layer to use Prisma Client for your database queries. + +> **Note**: During the upgrade process it can be helpful to get a graphical view on your database. It is therefore recommended to use a graphical database client to connect to your database, such as [TablePlus](https://tableplus.com/) or [Postico](https://eggerapps.at/postico/). + +## 1. Install Prisma ORM 2 CLI + +The Prisma ORM 2 CLI is available as the [`prisma`](https://www.npmjs.com/package/prisma) package on npm and is invoked via the `prisma` command. + +Note that the former `prisma` command for Prisma 1 has been renamed to `prisma1`. You can learn more about this [here](https://www.prisma.io/blog/prisma-2-beta-b7bcl0gd8d8e#renaming-the-prisma2-cli). + +You can install the Prisma ORM 2 CLI in your Node.js project as follows (be sure to invoke this command in the directory where your `package.json` is located): + +```terminal copy +npm install prisma --save-dev +``` + +> **Note**: With Prisma 1, it was usually recommended to install the CLI globally. We now recommend to [install the Prisma CLI locally](/orm/tools/prisma-cli#installation) to prevent version conflicts. + +You can now use the local installation of the `prisma` CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +If you're upgrading your entire project [all at once](/orm/more/upgrade-guides/upgrade-from-prisma-1/how-to-upgrade#upgrade-strategies), you can now also uninstall the Prisma 1 CLI (otherwise expand below): + +```terminal +# remove global installation +npm uninstall -g prisma1 + +# remove local installation +npm uninstall prisma1 +``` + +
+ +
+ +Expand if you want to keep using your Prisma 1 CLI side-by-side + +If you want to keep using the Prisma 1 CLI, it is recommend to remove your global installation of it and add the `prisma1` CLI as a development dependency: + +```terminal +# installs v1.34 of the Prisma 1 CLI +npm uninstall -g prisma +npm install prisma1 --save-dev +``` + +You can now invoke it as follows: + +```terminal +npx prisma1 +``` + +Note that if you need a CLI version smaller than 1.34 (e.g. 1.30), you can install it as follows: + +```terminal +# installs v1.30 of the Prisma 1 CLI +npm uninstall -g prisma@1.30 +npm install prisma@1.30 --save-dev +``` + +You can now invoke it as follows: + +```terminal +npx prisma +``` + +
+ +## 2. Create your Prisma ORM 2 schema + +For this guide, you'll first create a new Prisma schema using the `prisma init` command and then "fill" it with a data model using [introspection](/orm/prisma-schema/introspection). + +Run the following command to create your Prisma schema (note that this throws an error if you already have a folder called `prisma`): + +```terminal copy +npx prisma init +``` + +If you're seeing the following error, you need to rename your current `prisma` directory: + +```no-lines +ERROR A folder called prisma already exists in your project. + Please try again in a project that is not yet using Prisma. +``` + +You can rename the current `prisma` directory to `prisma1` to make it clear that this holds the former Prisma 1 configuration: + +```terminal copy +mv prisma prisma1 +``` + +Now you can run `init` and it will succeed: + +```terminal copy +npx prisma init +``` + +It should print the following output: + +```no-lines wrap +✔ Your Prisma schema was created at prisma/schema.prisma. + You can now open it in your favorite editor. + +Next steps: +1. Set the `DATABASE_URL` in the `.env` file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started +2. Set the `provider` of your `datasource` block in `schema.prisma` to match your database: `postgresql`, `mysql` or `sqlite`. +3. Run `prisma db pull` to turn your database schema into a Prisma data model. +4. Run `prisma generate` to install Prisma Client. You can then start querying your database. + +More information in our documentation: +https://pris.ly/d/getting-started +``` + +The command created a new folder called `prisma`, and two files: + +- `prisma/schema.prisma`: Your Prisma schema file that specifies the [data source](/orm/prisma-schema/overview/data-sources), [generator](/orm/prisma-schema/overview/generators) and [data model](/orm/prisma-schema/data-model/models) (note that the data model doesn't exist yet, it will be generated via introspection). +- `.env`: A [dotenv](https://github.com/motdotla/dotenv#readme) file to configure your database [connection URL](/orm/reference/connection-urls). + +Your initial Prisma schema looks as follows: + +```prisma file=schema.prisma +// This is your Prisma schema file, +// learn more about it in the docs: https://pris.ly/d/prisma-schema + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} +``` + +With Prisma 1, you specify which language variant of Prisma Client you wanted to use in your `prisma.yml`. With Prisma ORM 2, this information is now specified inside the Prisma schema via a `generator` block. + +> **Note**: Unlike Prisma 1, the TypeScript and JavaScript variants of Prisma Client 2.0 use the _same_ generator called `prisma-client-js`. The generated types in `index.d.ts` are _always_ included, even in plain JavaScript projects. This enables feature like autocompletion in VS Code even when not using TypeScript. + +## 3. Determine your connection URL and connect to your database + +With Prisma 1, the database connection is configured in the Docker Compose file that's used to launch the Prisma ORM server. The Prisma ORM server then exposes a GraphQL endpoint (via HTTP) that proxies all database requests from the Prisma Client application code. That HTTP endpoint is specified in your `prisma.yml`. + +With Prisma ORM 2, the HTTP layer isn't exposed any more and Prisma Client 2.0 is configured to run requests "directly" against the database (that is, requests are proxied by Prisma ORM's [query engine](/orm/more/under-the-hood/engines), but there isn't an extra server any more). + +So, as a next step you'll need to tell Prisma ORM 2 _what_ kind of database you use (MySQL or PostgreSQL) and _where_ it is located. + +First, you need to ensure that that `provider` field on the `datasource` block inside `schema.prisma` is configured to use the right database: + +- If you're using PostgreSQL, it needs to define the value `"postgresql"` in the `provider` field. +- If you're using MySQL, it needs to define the value `"mysql"` in the `provider` field. + +Switch around with the tabs in the code block to see examples of both: + + + + +```prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + + + + +```prisma +datasource db { + provider = "mysql" + url = env("DATABASE_URL") +} +``` + + + + +With the `provider` field set, you can go ahead and configure the connection URL inside the `.env` file. + +Assume the database configuration in your Docker Compose file that you used to deploy your Prisma ORM server looks as follows: + +```yml file=docker-compose.yml +PRISMA_CONFIG: | + port: 4466 + databases: + default: + connector: mysql + host: mysql + port: 3306 + user: root + password: randompassword +``` + +Also assume your `endpoint` in `prisma.yml` is configured as follows: + +```yml file=prisma.yml +endpoint: http://localhost:4466/myproject/dev +``` + +Based on these connection details, you need to configure the `DATABASE_URL` environment variable inside your `.env` file as follows: + +```bash file=.env +DATABASE_URL="mysql://root:randompassword@localhost:3306/myproject@dev" +``` + +Note that the _database name_ in the connection URL is typically composed of your _service name_ and _service stage_ (which are part of the `endpoint` in `prisma.yml`), separated by the `@` character. + +Sometimes no service name and stage are specified in `prisma.yml`: + +```yml file=prisma.yml +endpoint: http://localhost:4466/ +``` + +In that case, the database name must be specified as follows: + +```bash file=.env +DATABASE_URL="mysql://root:randompassword@localhost:3306/default@default" +``` + +Learn more on the [Connection URLs](/orm/reference/connection-urls) page. + +## 4. Introspect your database + +For the purpose of this guide, we'll use the following Prisma 1 data model (select the **SQL** tab below to see what the data model maps to in SQL): + + + + +```graphql +type User { + id: ID! @id + email: String @unique + name: String! + role: Role! @default(value: CUSTOMER) + jsonData: Json + profile: Profile + posts: [Post!]! +} + +type Post { + id: ID! @id + createdAt: DateTime! @createdAt + updatedAt: DateTime! @updatedAt + title: String! + content: String + published: Boolean! @default(value: false) + author: User @relation(link: TABLE) + categories: [Category!]! +} + +type Profile { + id: ID! @id + bio: String + user: User! @relation(link: INLINE) +} + +type Category { + id: ID! @id + name: String! + posts: [Post!]! +} + +enum Role { + ADMIN + CUSTOMER +} +``` + + + + +```sql +CREATE TABLE"User" ( + id character varying(25) PRIMARY KEY, + email text, + name text NOT NULL, + role text NOT NULL, + "jsonData" text +); +CREATE UNIQUE INDEX "User_pkey" ON"User"(id text_ops); +CREATE UNIQUE INDEX "default$default.User.email._UNIQUE" ON"User"(email text_ops); + +CREATE TABLE"Post" ( + id character varying(25) PRIMARY KEY, + title text NOT NULL, + published boolean NOT NULL, + "createdAt" timestamp(3) without time zone NOT NULL, + "updatedAt" timestamp(3) without time zone NOT NULL, + content text +); +CREATE UNIQUE INDEX "Post_pkey" ON"Post"(id text_ops); + +CREATE TABLE"Profile" ( + id character varying(25) PRIMARY KEY, + bio text, + user character varying(25) REFERENCES"User"(id) ON DELETE SET NULL +); +CREATE UNIQUE INDEX "Profile_pkey" ON"Profile"(id text_ops); + +CREATE TABLE"Category" ( + id character varying(25) PRIMARY KEY, + name text NOT NULL +); +CREATE UNIQUE INDEX "Category_pkey" ON"Category"(id text_ops); + +CREATE TABLE"_PostToUser" ( + "A" character varying(25) NOT NULL REFERENCES"Post"(id) ON DELETE CASCADE, + "B" character varying(25) NOT NULL REFERENCES"User"(id) ON DELETE CASCADE +); +CREATE UNIQUE INDEX "_PostToUser_AB_unique" ON"_PostToUser"("A" text_ops,"B" text_ops); +CREATE INDEX "_PostToUser_B" ON"_PostToUser"("B" text_ops); + +CREATE TABLE"_CategoryToPost" ( + "A" character varying(25) NOT NULL REFERENCES"Category"(id) ON DELETE CASCADE, + "B" character varying(25) NOT NULL REFERENCES"Post"(id) ON DELETE CASCADE +); +CREATE UNIQUE INDEX "_CategoryToPost_AB_unique" ON"_CategoryToPost"("A" text_ops,"B" text_ops); +CREATE INDEX "_CategoryToPost_B" ON"_CategoryToPost"("B" text_ops); +``` + + + + +Note that this data model has three [relations](/orm/prisma-schema/data-model/relations): + +- 1-1: `User` ↔ `Profile` +- 1-n: `User` ↔ `Post` (maintained via the `_PostToUser` relation table) +- m-n: `Post` ↔ `Category` (maintained via the `_CategoryToPost` relation table) + +Now you can run Prisma ORM's introspection against your database with the following command: + +```terminal copy +npx prisma db pull +``` + +Here's a graphical illustration for what happens when `db pull` is invoked: + +![Introspect your database](/img/orm/prisma-db-pull-generate-schema.png) + +For the above Prisma 1 datamodel, this results in the following Prisma ORM 2 schema (note that the models have been reordered to match the initial order of the Prisma 1 datamodel): + +```prisma file=schema.prisma +model User { + id String @id @default(cuid()) + email String? @unique + name String + role String + jsonData String? + Profile Profile[] + Post Post[] +} + +model Post { + id String @id @default(cuid()) + createdAt DateTime + updatedAt DateTime + title String + content String? + published Boolean + Category Category[] + User User[] +} + +model Profile { + id String @id @default(cuid()) + bio String? + user String? @unique + User User? @relation(fields: [user], references: [id]) +} + +model Category { + id String @id @default(cuid()) + name String + Post Post[] +} +``` + +While this is already a valid Prisma ORM 2 schema, it lacks a number of _features_ that were part of its Prisma 1 equivalent: + +- no auto-generated date values for the `createdAt` and `updatedAt` fields on `Post` +- no default value for the `role` field on `User` +- no default value for the `published` field on `Post` + +There further are a number of inconsistencies which result in a less idiomatic/ergonomic Prisma Client API: + +- `User` ↔ `Profile` is a 1-n instead of 1-1 relation +- `User` ↔ `Post` is a m-n instead of 1-n relation +- relation fields are uppercased (e.g. `Profile` and `Post` on `User`) +- the `jsonData` field on `User` is of type `String` instead of `Json` +- the `role` field on `User` is of type `String` instead of `Role`, the `enum` definition for role is missing altogether + +While these inconsistencies don't actually impact the "feature set" you'll have available in your Prisma Client API, they make you lose certain constraints/guarantees that were present before. + +For example, Prisma ORM now won't guarantee that a `User` is connected to _at most_ one `Profile` because the relation between the tables was recognized as 1-n during introspection, so one `User` record _could_ now get connected to multiple `Profile` records. + +Another issue is that you can store whatever text for the `jsonData` and `role` fields, regardless of whether it's valid JSON or represents a value of the `Role` enum. + +To learn more about these inconsistencies check out the [Schema incompatibilities](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql) page. + +In the following, we'll go through these incompatibilities and fix them one by one using the Prisma schema upgrade CLI. + +## 5. Use the Prisma schema upgrade CLI to resolve schema incompatibilities + +The [Prisma 1 Upgrade CLI](/orm/more/upgrade-guides/upgrade-from-prisma-1/how-to-upgrade#prisma-1-upgrade-cli) is an interactive tool that helps you upgrading your Prisma schema and ironing out most of the inconsistencies listed above. + +The Prisma 1 Upgrade CLI works in two major phases: + +1. Fix the database schema via plain SQL +1. Add missing attributes to the Prisma ORM 2 schema and other schema fixes + +During the first phase, it will generate and print a number of SQL statements that you should run against your database to adjust the database schema. You can either run all of the statements or a subset of them before continuing to the second phase. + +During the second phase, you don't need to do anything manually. The Upgrade CLI will make changes to your Prisma schema by adding certain Prisma ORM-level attributes (like `@default(cuid))` or `@updatedAt`), adjusting the names of relation fields to match the ones from your Prisma 1 datamodel and ensure 1-1-relations that were required on both sides in your Prisma 1 datamodel are also required in the Prisma ORM 2 schema. + +Note that **you can start over at any time during the process** and go back from the second to the first phase. + +In this illustration, the green area shows the first phase, the blue area shows the second phase. Note that you can optionally run `prisma db pull` in between the phases to update your Prisma ORM data model: + +![Fixing the schema incompatibilities](images/fix-schema-incompatibilities.png) + +To use the Upgrade CLI, you can either install it locally in your project, or invoke it once without installation using `npx` as done here: + +```terminal copy +npx prisma-upgrade prisma1/prisma.yml prisma/schema.prisma +``` + +The CLI will greet you with the following message: + +```no-lines wrap +◮ Welcome to the interactive Prisma Upgrade CLI that helps with the +upgrade process from Prisma 1 to Prisma ORM 2. + +Please read the docs to learn more about the upgrade process: +https://pris.ly/d/how-to-upgrade + +➤ Goal +The Upgrade CLI helps you resolve the schema incompatibilities +between Prisma 1 and Prisma ORM 2. Learn more in the docs: +https://pris.ly/d/schema-incompatibilities + +➤ How it works +Throughout the process, you'll need to adjust your database schema by sending +SQL statements to it. The SQL statements are provided by the Upgrade CLI. + +Note that the Upgrade CLI never makes changes to your database, +you are in full control over any operations that are executed against it. + +You can stop and re-run the Upgrade CLI at any time. + +These are the different steps of the upgrade process: + + 1. The Upgrade CLI generates SQL commands for you to run on your database. + 2. You run the SQL commands against your database. + 3. You run the `npx prisma db pull` command again. + 4. You run the `npx prisma-upgrade` command again. + 5. The Upgrade CLI adjusts the Prisma ORM 2 schema by adding missing attributes. + +➤ Note +It is recommended that you make a full backup of your existing data before starting +the upgrade process. If possible, the migration should be performed in a staging +environment before executed against a production environment. + +➤ Help +If you have any questions or run into any problems along the way, +please create an issue at: +https://github.com/prisma/upgrade/issues/new + +Are you ready? [Y/n] +``` + +Press the Y button, then confirm by hitting RETURN on your keyboard to continue. + +Once you confirmed, the CLI outputs the SQL statements you should be running against your database: + +```no-lines wrap +➤ Adjust your database schema +Run the following SQL statements against your database: + + Fix columns with ENUM data types + https://pris.ly/d/schema-incompatibilities#enums-are-represented-as-text-in-database + + ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL; + + + Add missing `DEFAULT` constraints to the database + https://pris.ly/d/schema-incompatibilities#default-values-arent-represented-in-database + + ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL DEFAULT 'CUSTOMER'; + ALTER TABLE `Post` CHANGE `published` `published` TINYINT(1) NOT NULL DEFAULT 0; + + + Fix columns with JSON data types + https://pris.ly/d/schema-incompatibilities#json-type-is-represented-as-text-in-database + + ALTER TABLE `User` CHANGE `jsonData` `jsonData` JSON ; + + + Replicate `@createdAt` behavior in Prisma ORM 2.0 + https://pris.ly/d/schema-incompatibilities#createdat-isnt-represented-in-database + + ALTER TABLE `Post` CHANGE `createdAt` `createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; + + + Fix 1-1 relations by adding `UNIQUE` constraints + https://pris.ly/d/schema-incompatibilities#inline-1-1-relations-are-recognized-as-1-n-missing-unique-constraint + + ALTER TABLE `Profile` ADD UNIQUE (`user`); + + + Migrate IDs from varchar(25) to varchar(30) + https://pris.ly/d/schema-incompatibilities#mismatching-cuid-length + + SET FOREIGN_KEY_CHECKS=0; + ALTER TABLE `Category` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; + ALTER TABLE `Post` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; + ALTER TABLE `Profile` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; + ALTER TABLE `Profile` CHANGE `user` `user` char(30) CHARACTER SET utf8 ; + ALTER TABLE `User` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; + SET FOREIGN_KEY_CHECKS=1; + +➤ Breaking changes detected + +In order to fully optimize your database schema, you'll need to run a few SQL +statements that can break your Prisma 1 setup. Note that these changes are optional +and if you are upgrading gradually and running Prisma 1 and Prisma ORM 2 side-by-side, +you should not perform these changes yet. Instead, you can perform them whenever +you are ready to completely remove Prisma 1 from your project. +If you are upgrading all at once, you can safely perform these changes now. + +Learn more in the docs: +https://pris.ly/d/how-to-upgrade' +``` + +> **Note**: If you're seeing the note about breaking changes, you can ignore it for now. We'll discuss it later. + +The shown SQL statements are categorized into a number of "buckets", all aiming to resolve a certain [schema incompatibility](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql): + +- Fix columns with ENUM data types +- Add missing `DEFAULT` constraints to the database +- Fix columns with JSON data types +- Replicate `@createdAt` behavior in Prisma 2 +- Fix 1-1 relations by adding `UNIQUE` constraints + +As a next step, you can start sending the SQL statements to your database. Note that all of these changes are non-breaking and you'll be able to continue using Prisma 1 side-by-side with Prisma ORM 2. + +The next sections cover the different kinds of SQL statements to be sent to your database individually. + +### 5.1. Fix the database schema via plain SQL (non-breaking) + +In this section, we'll walk through the printed SQL statements and run them against the database one by one. + +### 5.1.1. Fix columns with ENUM data types + +The first thing the tool does is help you ensure that `enum` definitions in your Prisma 1 datamodel will be represented as actual `ENUM` types in the underlying database, right now they are represented as plain strings (e.g. as `MEDIUMTEXT` in MySQL). + +The CLI currently shows the following output: + +```no-lines wrap +Fix columns with ENUM data types +https://pris.ly/d/schema-incompatibilities#enums-are-represented-as-text-in-database + + ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL; +``` + +Go ahead and run these statements against your database now. + +![Altering columns to use ENUM with SQL](images/altering-columns-to-use-enum.png) + +### 5.1.2. Add missing `DEFAULT` constraints to the database + +Next, the Upgrade CLI helps you resolve the issue that [default values aren't represented in the database](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql#default-values-arent-represented-in-database) by generating SQL statements that add the respective `DEFAULT` constraints directly to the database. + +In this case, two `DEFAULT` constraints are missing which are suggested by the tool: + +```no-lines wrap +Add missing `DEFAULT` constraints to the database +https://pris.ly/d/schema-incompatibilities#default-values-arent-represented-in-database + + ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL DEFAULT 'CUSTOMER'; + ALTER TABLE `Post` CHANGE `published` `published` TINYINT(1) NOT NULL DEFAULT 0; +``` + +You can now run these SQL statements against your database either using a command line client or a GUI like TablePlus: + +![TablePlus GUI](images/TablePlus-GUI.png) + +### 5.1.3. Fix columns with JSON data types + +Next, the tool helps you ensure that `Json` fields in your Prisma 1 datamodel will be represented as `JSON` columns in the underlying database, right now they are represented as plain strings (e.g. as `MEDIUMTEXT` in MySQL). + +Changing the column type to `JSON` will ensure that the field is properly recognized as `Json` during Prisma ORM 2 introspection. + +The CLI currently shows the following output: + +```no-lines wrap +Fix columns with JSON data types +https://pris.ly/d/schema-incompatibilities#json-type-is-represented-as-text-in-database + + ALTER TABLE `User` CHANGE `jsonData` `jsonData` JSON ; +``` + +You can now run these SQL statements against your database either using a command line client or a GUI like TablePlus: + +![TablePlus GUI](images/fix-columns-with-json-data-types.png) + +### 5.1.4. Replicate `@createdAt` behavior in Prisma ORM 2 + +The next thing the tools does is help you resolve the issue that the behavior of [`@createdAt` isn't represented in database](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql#default-values-arent-represented-in-database) + +The CLI currently shows the following output: + +```no-lines wrap +Replicate `@createdAt` behavior in Prisma ORM 2.0 +https://pris.ly/d/schema-incompatibilities#createdat-isnt-represented-in-database + + ALTER TABLE `Post` CHANGE `createdAt` `createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; +``` + +You can now run these SQL statements against your database either using a command line client or a GUI like TablePlus. + +### 5.1.5. Fix 1-1 relations by adding `UNIQUE` constraints + +Now, the tool will help you [turn the current 1-n relation between `User` ↔ `Profile` back into a 1-1 relation](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql#inline-1-1-relations-are-recognized-as-1-n-missing-unique-constraint) by adding a `UNIQUE` constraint to the foreign key column called `user` (named after the relation field in the Prisma 1 datamodel) in the database. + +The CLI currently shows the following output: + +```no-lines wrap +Fix 1-1 relations by adding `UNIQUE` constraints +https://pris.ly/d/schema-incompatibilities#inline-1-1-relations-are-recognized-as-1-n-missing-unique-constraint + + ALTER TABLE `Profile` ADD UNIQUE (`user`); +``` + +You can now run these SQL statements against your database either using a command line client or a GUI like TablePlus. + +### 5.1.6. Fix mismatch of CUID length + +> **Note**: These SQL statements will keep appearing in the Upgrade CLI even after you have changed the column types in the underlying database. This is a currently a limitation in the Upgrade CLI. + +Finally, the tool will help you [turn the current ID columns of type `VARCHAR(25)` into `VARCHAR(30)`](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql#mismatching-cuid-length) by adding a `UNIQUE` constraint to the foreign key column called `user` (named after the relation field in the Prisma 1 datamodel) in the database. + +The CLI currently shows the following output: + +```no-lines wrap +Migrate IDs from varchar(25) to varchar(30) +https://pris.ly/d/schema-incompatibilities#mismatching-cuid-length + +SET FOREIGN_KEY_CHECKS=0; +ALTER TABLE `Category` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; +ALTER TABLE `Post` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; +ALTER TABLE `Profile` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; +ALTER TABLE `Profile` CHANGE `user` `user` char(30) CHARACTER SET utf8 ; +ALTER TABLE `User` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; +SET FOREIGN_KEY_CHECKS=1; +``` + +You can now run these SQL statements against your database either using a command line client or a GUI like TablePlus. + +### 5.1.7. Breaking changes detected + +In case the Upgrade CLI has printed a note about breaking changes, your database schema needs some adjustments that will break Prisma 1 compatibility in order to be fully optimized. + +If there are no breaking changes detected, you can [skip forward to section 5.2](#52-re-introspect-your-database-to-update-your-prisma-schema) + +Depending on your [upgrade strategy](/orm/more/upgrade-guides/upgrade-from-prisma-1/how-to-upgrade#upgrade-strategies), you can either perform these changes now or skip to the next phase of the Upgrade CLI: + +- If you are following the gradual side-by-side upgrade strategy, do not perform these changes yet since they will break your Prisma 1 setup. In that case, you can continue to the next phase of the Upgrade CLI by typing n and hitting RETURN. +- If you are following the all at once upgrade strategy, you can perform these changes now. In that case, continue by typing Y and hitting RETURN. + +### 5.2. Fix the database schema via plain SQL (breaking) + +In this section, you'll resolve the schema incompatibilities that are breaking your Prisma 1 setup. Do not perform these changes if you are still running Prisma 1 in your project! + +### 5.2.1. Fix incorrect m-n relations + +Now, the Upgrade CLI helps you fix all 1-1 and 1-n relations that Prisma 1 represents with relation tables and that [currently only exist as m-n relations](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql#all-non-inline-relations-are-recognized-as-m-n) in your new Prisma ORM 2 schema. Concretely, this is the case for the `User` ↔ `Post` relation which currently is defined as m-n but _should_ really be a 1-n relation. + +To fix this, you'll need to perform the following migration: + +1. Create a new foreign key column on `Post` to link directly to the `User` table. +1. Migrate the foreign key values from the relation table into the new foreign key column on `Post`. +1. Delete the relation table. + +These instructions are now printed by the CLI: + +```no-lines wrap +➤ Adjust your database schema +Run the following SQL statements against your database: + + Fix one-to-many table relations + https://pris.ly/d/schema-incompatibilities#all-non-inline-relations-are-recognized-as-m-n + + ALTER TABLE `Post` ADD COLUMN `authorId` char(25) CHARACTER SET utf8 ; + ALTER TABLE `Post` ADD CONSTRAINT author FOREIGN KEY (`authorId`) REFERENCES `User`(`id`); + UPDATE `Post`, `_PostToUser` SET `Post`.`authorId` = `_PostToUser`.B where `_PostToUser`.A = `Post`.`id`; + DROP TABLE `_PostToUser`; + + +➤ Next Steps + +After you executed one or more of the above SQL statements against your database, +please run the following two commands to refresh your Prisma ORM 2 Schema and check +the changes. + + 1. Run `npx prisma db pull` again to refresh your Prisma ORM 2 schema. + 2. Run `npx prisma-upgrade` again. + +If you can't or don't want to execute the remaining SQL statements right now, you can +skip to the last step where the Upgrade CLI adds missing attributes to your Prisma ORM 2 +schema that are not picked up by introspection. + +Skip to the last step? [Y/n]? +``` + +For this fix, you'll need to run three SQL statements: + +1. Create new column `authorId` on the `Post` table. This column should be a _foreign key_ that references the `id` field of the `User` table: + ```sql no-lines + ALTER TABLE `Post` ADD COLUMN `authorId` char(25) CHARACTER SET utf8 ; + ALTER TABLE `Post` ADD CONSTRAINT author FOREIGN KEY (`authorId`) REFERENCES `User`(`id`); + ``` +1. Write a SQL query that reads all the rows from the `_PostToUser` relation table and for each row: + 1. Finds the respective `Post` record by looking up the value from column `A` + 1. Inserts the value from column `B` as the value for `authorId` into that `Post` record + ```sql no-lines + UPDATE `Post`, `_PostToUser` SET `Post`.`authorId` = `_PostToUser`.B where `_PostToUser`.A = `Post`.`id`; + ``` +1. Delete the `_PostToUser` relation table + ```sql no-lines + DROP TABLE `_PostToUser`; + ``` + +![Fixing incorrect m-n relations with SQL](images/fix-incorrect-m-n-relations-sql.png) + +After these commands, the user ID values of the records from column `B` of the relation table are migrated to the new `authorId` column. + +### 5.2. Re-introspect your database to update your Prisma schema + +At this point, you've resolved the schema incompatibilities with the Upgrade CLI. You can now exit the Upgrade CLI for now by typing n and hitting RETURN. + +In this section, you'll update your Prisma schema with another introspection round. This time, the previous flaws of the Prisma schema will be resolved because the database schema has been adjusted: + +```terminal copy +npx prisma db pull +``` + +This time, the resulting Prisma schema looks as follows: + +```prisma file=schema.prisma +model User { + id String @id + name String + email String? @unique + jsonData Json? + role Role @default(CUSTOMER) + Post Post[] + Profile Profile? +} + +model Post { + id String @id + createdAt DateTime @default(now()) + updatedAt DateTime + title String + content String? + published Boolean @default(false) + authorId String? + User User? @relation(fields: [authorId], references: [id]) + Category Category[] @relation(references: [id]) +} + +model Category { + id String @id + name String + Post Post[] @relation(references: [id]) +} + +model Profile { + bio String? + id String @id + user String? @unique + User User? @relation(fields: [user], references: [id]) +} + +enum Role { + ADMIN + CUSTOMER +} +``` + +This schema has most issues resolved, but it still lacks the following: + +### 5.2. Add missing attributes to the Prisma 2 schema and other schema fixes + +The CLI now prints the following: + +```no-lines wrap +➤ What happens next +As a last step, some final adjustments will be made to your Prisma ORM 2 schema +to carry over some Prisma ORM-level attributes that aren't picked up by introspection. + +As a last step, some final adjustments will be made to your Prisma ORM 2.0 +schema to carry over some Prisma ORM-level attributes that aren't picked +up by introspection. + +Warning +Your current Prisma ORM 2.0 schema will be overwritten, so please +make sure you have a backup! + +Are you ready? [Y/n] +``` + +At this point, you either ran all the SQL statement that were printed by the CLI or you skipped some of them. Either way, you can now move on the last step and let the Upgrade CLI add the missing Prisma ORM 2 attributes. Typically these are the following: + +- `@default(cuid())` for your `@id` fields +- `@updatedAt` for any fields that were using this attribute in Prisma 1 +- `@map` and `@@map` as replacements for `@db` and `@@db` from Prisma 1 + +In that step, the Upgrade CLI also fixes other issues that occurred in the transition to Prisma ORM 2: + +- it makes sure that 1-1-relations that were required on both sides in Prisma 1 are also required in your Prisma ORM 2 schema +- it renames relation fields to the same names they had in your Prisma 1 datamodel ([coming soon](https://github.com/prisma/upgrade/issues/25)) + +To apply these changes, you can re-run the Upgrade CLI: + +```terminal copy +npx prisma-upgrade prisma1/prisma.yml prisma/schema.prisma +``` + +If you did not resolve all schema incompatibilities, the Upgrade CLI now prints the remaining SQL statements (as well as the ones for migrating IDs). You can just ignore them at this point and continue to the last step by continuously typing Y and hitting RETURN when prompted. + +If you did resolve all schema incompatibilities, no SQL statements will be printed and the Upgrade CLI only outputs the following: + +```no-lines wrap +$ npx prisma-upgrade prisma1/prisma.yml prisma/schema.prisma + +➤ Next Steps + +After you executed one or more of the previous SQL statements against your database, +please run the following two commands to refresh your Prisma ORM 2 schema and check +the changes. + + 1. Run `npx prisma db pull` again to refresh your Prisma ORM 2 schema. + 2. Run `npx prisma-upgrade` again. + +If you can't or don't want to execute the remaining SQL statements right now, you can +skip to the last step where the Upgrade CLI adds missing attributes to your Prisma ORM 2 +schema that are not picked up by introspection. + +Skip to the last step? [Y/n]? +``` + +One more time, type Y and hit RETURN to confirm. + +The final prompt of the Upgrade CLI now asks you to confirm the above mentioned changes it will make to your Prisma schema: + +```no-lines wrap +➤ What happens next +As a last step, some final adjustments will be made to your Prisma ORM 2 schema +to carry over some Prisma ORM-level attributes that aren't picked up by introspection. + +As a last step, some final adjustments will be made to your Prisma ORM 2.0 +schema to carry over some Prisma ORM-level attributes that aren't picked +up by introspection. + +Warning +Your current Prisma ORM 2.0 schema will be overwritten, so please +make sure you have a backup! + +Are you ready? [Y/n] +``` + +One last time, type Y and hit RETURN to confirm. + +This is the final output of the Upgrade CLI: + +```no-lines +Updating prisma/schema.prisma... +Done updating prisma/schema.prisma! + +✔ Congratulations, you're all set! + +➤ Note +If you didn't execute all generated SQL commands against your database, +you can re-run the Upgrade CLI at any time. + +Note that the Upgrade CLI doesn't resolve all of the schema incompatibilities +between Prisma 1 and Prisma ORM 2. If you want to resolve the remaining ones, +you can do so manually by following this guide: +https://pris.ly/d/upgrading-the-prisma-layer + +➤ Next steps +Otherwise you can continue your upgrade process by installing Prisma Client 2: +npm install @prisma/client + +You can find guides for different upgrade scenarios in the docs: +https://pris.ly/d/upgrade-from-prisma-1 +``` + +### 5.3. Final result + +The final version of the Prisma schema should look as follows: + +```prisma file=schema.prisma +model User { + id String @id @default(cuid()) + name String + email String? @unique + jsonData Json? + role Role @default(CUSTOMER) + Post Post[] + Profile Profile? +} + +model Post { + id String @id @default(cuid()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String + content String? + published Boolean @default(false) + authorId String? + User User? @relation(fields: [authorId], references: [id]) + Category Category[] @relation(references: [id]) +} + +model Profile { + id String @id @default(cuid()) + bio String? + user String? @unique + User User? @relation(fields: [user], references: [id]) +} + +model Category { + id String @id @default(cuid()) + name String + Post Post[] @relation(references: [id]) +} + +enum Role { + ADMIN + CUSTOMER +} +``` + +### 5.4. Rename relation fields + +One thing you'll notice with this version of the Prisma ORM 2 schema is that all [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are named after their respective models, e.g: + +```prisma file=schema.prisma +model User { + Post Post[] + Profile Profile? +} + +model Post { + User User? @relation(fields: [authorId], references: [id]) + Category Category[] @relation(references: [id]) +} + +model Profile { + User User? @relation(fields: [user], references: [id]) +} + +model Category { + Post Post[] @relation(references: [id]) +} +``` + +This is not ideal and you can in fact manually rename all of them to their previous versions! + +Because all relation fields are _virtual_, meaning they don't _manifest_ in the database, you can name them whatever you like. In this case, all relation fields are lowercased and sometimes pluralized. + +Here's what they look like after the rename: + +```prisma file=schema.prisma +model User { + posts Post[] + profile Profile? +} + +model Post { + author User? @relation(fields: [authorId], references: [id]) + categories Category[] @relation(references: [id]) +} + +model Profile { + user String? @unique + owner User? @relation(fields: [user], references: [id]) +} + +model Category { + posts Post[] @relation(references: [id]) +} +``` + +> **Note**: For the 1-1-relation between `User` and `Profile` it was not possible to set the old name `user` for the relation field. This is because there'd be a naming conflict with the already existing [relation scalar](/orm/prisma-schema/data-model/relations#annotated-relation-fields) field that holds the foreign key. In that case, you can choose a different name or alternatively rename the foreign key column directly in the database via SQL. + +### 5.5. Resolving remaining schema incompatibilities + +There are a few schema incompatibilities that were not yet resolved by the Upgrade CLI. At this point you still haven't fixed [scalar lists](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql#scalar-lists-arrays-are-maintained-with-extra-table) and [cascading deletes](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql#cascading-deletes-are-not-supported-in-prisma-orm-2). You can find the recommended workarounds for these on the [Schema incompatibilities](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql) page. + +## 6. Install and generate Prisma Client + +Now that you have your Prisma ORM 2 schema ready, you can install Prisma Client with the following command: + +```terminal copy +npm install @prisma/client +``` + +## 7. Next steps + +Congratulations, you have now upgraded your Prisma ORM layer to Prisma ORM 2! From here on, you can move on to update your application code using one of the following guides: + +- [Old to new Nexus](/orm/more/upgrade-guides/upgrade-from-prisma-1/upgrading-nexus-prisma-to-nexus): Choose this guide if you're currently running Prisma 1 with GraphQL Nexus. +- [prisma-binding to Nexus](/orm/more/upgrade-guides/upgrade-from-prisma-1/upgrading-prisma-binding-to-nexus): Choose this guide if you're currently running Prisma 1 with `prisma-binding` and want to upgrade to [Nexus](https://www.nexusjs.org/#/) (and TypeScript). +- [prisma-binding to SDL-first](/orm/more/upgrade-guides/upgrade-from-prisma-1/upgrading-prisma-binding-to-sdl-first): Choose this guide if you're currently running Prisma 1 with `prisma-binding` and want to upgrade to an [SDL-first](https://www.prisma.io/blog/the-problems-of-schema-first-graphql-development-x1mn4cb0tyl3) GraphQL server. +- [REST API](/orm/more/upgrade-guides/upgrade-from-prisma-1/upgrading-a-rest-api): Choose this guide if you're currently running Prisma 1 using Prisma Client 1 and are building a REST API. + +## Bonus: Prisma Client API comparison + +This section contains a high-level and side-by-side comparison of the Prisma Client APIs of Prisma 1 and Prisma ORM 2. For more details about the new Prisma Client API, you can explore the [Prisma Client](/orm/prisma-client) docs. + +### Reading single records + + + + + +```ts +const user = await prisma.user({ id: 1 }) +``` + + + + + +```ts +await prisma.user.findUnique({ + where: { id: 1 }, +}) +``` + + + + + +### Reading lists of records + + + + + +```ts +const user = await prisma.users() +``` + + + + + +```ts +await prisma.user.findMany() +``` + + + + + +### Filtering lists + + + + + +```ts +const users = await prisma.users({ + where: { + name: 'Alice', + }, +}) +``` + + + + + +```ts +await prisma.user.findMany({ + where: { + name: 'Alice', + }, +}) +``` + + + + + +### Paginating lists + + + + + +```ts +const posts = await prisma.posts({ + skip: 5, + first: 10, +}) +``` + + + + + +```ts +await prisma.user.findMany({ + skip: 5, + take: 10, +}) +``` + + + + + +> **Note**: You can learn more about the new pagination API in the respective [release notes](https://github.com/prisma/prisma/releases/tag/2.0.0-beta.7) or the [Pagination](/orm/prisma-client/queries/pagination) page in the docs. + +### Sorting lists + + + + + +```ts +await prisma.posts({ + orderBy: 'title_ASC', +}) +``` + + + + + +```ts +await prisma.posts({ + orderBy: { + title: 'asc', + }, +}) +``` + + + + + +### Creating records + + + + + +```ts +await prisma.createUser({ + name: 'Alice', +}) +``` + + + + + +```ts +await prisma.user.create({ + data: { + name: 'Alice', + }, +}) +``` + + + + + +### Updating records + + + + + +```ts +await prisma.updateUser({ + where: { id: 1 }, + data: { + name: 'James', + email: 'james@prisma.io', + }, +}) +``` + + + + + +```ts +await prisma.user.update({ + where: { id: 1 }, + data: { + name: 'James', + email: 'james@prisma.io', + }, +}) +``` + + + + + +### Deleting records + + + + + +```ts +await prisma.deleteUser({ id: 1 }) +``` + + + + + +```ts +await prisma.user.delete({ + where: { id: 1 }, +}) +``` + + + + + +### Selecting fields & loading relations + +In Prisma 1, the only ways to select specific fields and/or load relations of an object was by using the string-based `$fragment` and `$graphql` functions. With Prisma ORM 2, this is now done in a clean and type-safe manner using [`select`](/orm/prisma-client/queries/select-fields#select-specific-fields) and [`include`](/orm/prisma-client/queries/select-fields#include-relations-and-select-relation-fields). + +Another benefit of this approach is that you can use `select` and `include` on _any_ Prisma Client query, e.g. `findUnique`, `findMany`, `create`, `update`, `delete`, ... + + + + + +```ts +await prisma.user({ id: 1 }).$fragment(` + fragment NameAndEmail on User { id email }` +`) +``` + + + + + +```ts +await prisma.user.findUnique({ + where: { id: 1 }, + select: { + id: true, + email: true, + }, +}) +``` + + + + + +As an example, creating a new record and only retrieving the `id` in the returned object was not possible in Prisma 1. With Prisma ORM 2 you can achieve this as follows: + +```ts +await prisma.user.create({ + data: { + name: 'Alice', + }, + select: { + id: true, + }, +}) +``` diff --git a/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer.mdx b/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer-postgresql.mdx similarity index 82% rename from docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer.mdx rename to docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer-postgresql.mdx index aef0671de7..02b7a8572e 100644 --- a/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer.mdx +++ b/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer-postgresql.mdx @@ -1,29 +1,16 @@ --- title: 'Upgrading the Prisma ORM layer' -# metaTitle: 'Upgrading the Prisma ORM layer to Prisma ORM 2' -# metaDescription: 'Learn how to upgrade the Prisma ORM layer to Prisma ORM 2 and create your Prisma schema.' +metaTitle: 'Upgrading the Prisma ORM layer to Prisma ORM 2 | PostgreSQL' +metaDescription: 'Learn how to upgrade the Prisma ORM layer to Prisma ORM 2 and create your Prisma schema with PostgreSQL' dbSwitcher: ['postgresql', 'mysql'] -techMetaTitles: - [ - { name: 'mysql', value: 'Upgrading the Prisma ORM layer to Prisma ORM 2 | MySQL' }, - { - name: 'postgresql', - value: 'Upgrading the Prisma ORM layer to Prisma ORM 2 | PostgreSQL', - }, - ] -techMetaDescriptions: - [ - { - name: 'mysql', - value: 'Learn how to upgrade the Prisma ORM layer to Prisma ORM 2 and create your Prisma schema with MySQL', - }, - { - name: 'postgresql', - value: 'Learn how to upgrade the Prisma ORM layer to Prisma ORM 2 and create your Prisma schema with PostgreSQL', - }, - ] --- + + ## Overview This page explains the first step of your upgrade process: Taking your Prisma 1 configuration and upgrading it to Prisma ORM 2. Concretely, you will learn how to: @@ -217,8 +204,6 @@ With the `provider` field set, you can go ahead and configure the connection URL Assume the database configuration in your Docker Compose file that you used to deploy your Prisma ORM server looks as follows: - - ```yml file=docker-compose.yml PRISMA_CONFIG: | port: 4466 @@ -257,50 +242,6 @@ In that case, the `schema` must be specified as follows: DATABASE_URL="postgresql://janedoe:randompassword@localhost:5432/prisma?schema=default$default" ``` - - - - -```yml file=docker-compose.yml -PRISMA_CONFIG: | - port: 4466 - databases: - default: - connector: mysql - host: mysql - port: 3306 - user: root - password: randompassword -``` - -Also assume your `endpoint` in `prisma.yml` is configured as follows: - -```yml file=prisma.yml -endpoint: http://localhost:4466/myproject/dev -``` - -Based on these connection details, you need to configure the `DATABASE_URL` environment variable inside your `.env` file as follows: - -```bash file=.env -DATABASE_URL="mysql://root:randompassword@localhost:3306/myproject@dev" -``` - -Note that the _database name_ in the connection URL is typically composed of your _service name_ and _service stage_ (which are part of the `endpoint` in `prisma.yml`), separated by the `@` character. - -Sometimes no service name and stage are specified in `prisma.yml`: - -```yml file=prisma.yml -endpoint: http://localhost:4466/ -``` - -In that case, the database name must be specified as follows: - -```bash file=.env -DATABASE_URL="mysql://root:randompassword@localhost:3306/default@default" -``` - - - Learn more on the [Connection URLs](/orm/reference/connection-urls) page. ## 4. Introspect your database @@ -556,8 +497,6 @@ Press the Y button, then confirm by hitting RETURN on your Once you confirmed, the CLI outputs the SQL statements you should be running against your database: - - ```no-lines wrap ➤ Adjust your database schema Run the following SQL statements against your database: @@ -616,71 +555,6 @@ Learn more in the docs: https://pris.ly/d/how-to-upgrade' ``` - - - - -```no-lines wrap -➤ Adjust your database schema -Run the following SQL statements against your database: - - Fix columns with ENUM data types - https://pris.ly/d/schema-incompatibilities#enums-are-represented-as-text-in-database - - ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL; - - - Add missing `DEFAULT` constraints to the database - https://pris.ly/d/schema-incompatibilities#default-values-arent-represented-in-database - - ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL DEFAULT 'CUSTOMER'; - ALTER TABLE `Post` CHANGE `published` `published` TINYINT(1) NOT NULL DEFAULT 0; - - - Fix columns with JSON data types - https://pris.ly/d/schema-incompatibilities#json-type-is-represented-as-text-in-database - - ALTER TABLE `User` CHANGE `jsonData` `jsonData` JSON ; - - - Replicate `@createdAt` behavior in Prisma ORM 2.0 - https://pris.ly/d/schema-incompatibilities#createdat-isnt-represented-in-database - - ALTER TABLE `Post` CHANGE `createdAt` `createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; - - - Fix 1-1 relations by adding `UNIQUE` constraints - https://pris.ly/d/schema-incompatibilities#inline-1-1-relations-are-recognized-as-1-n-missing-unique-constraint - - ALTER TABLE `Profile` ADD UNIQUE (`user`); - - - Migrate IDs from varchar(25) to varchar(30) - https://pris.ly/d/schema-incompatibilities#mismatching-cuid-length - - SET FOREIGN_KEY_CHECKS=0; - ALTER TABLE `Category` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; - ALTER TABLE `Post` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; - ALTER TABLE `Profile` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; - ALTER TABLE `Profile` CHANGE `user` `user` char(30) CHARACTER SET utf8 ; - ALTER TABLE `User` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; - SET FOREIGN_KEY_CHECKS=1; - -➤ Breaking changes detected - -In order to fully optimize your database schema, you'll need to run a few SQL -statements that can break your Prisma 1 setup. Note that these changes are optional -and if you are upgrading gradually and running Prisma 1 and Prisma ORM 2 side-by-side, -you should not perform these changes yet. Instead, you can perform them whenever -you are ready to completely remove Prisma 1 from your project. -If you are upgrading all at once, you can safely perform these changes now. - -Learn more in the docs: -https://pris.ly/d/how-to-upgrade' -``` - - - > **Note**: If you're seeing the note about breaking changes, you can ignore it for now. We'll discuss it later. The shown SQL statements are categorized into a number of "buckets", all aiming to resolve a certain [schema incompatibility](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql): @@ -705,8 +579,6 @@ The first thing the tool does is help you ensure that `enum` definitions in your The CLI currently shows the following output: - - ```no-lines wrap Fix columns with ENUM data types https://pris.ly/d/schema-incompatibilities#enums-are-represented-as-text-in-database @@ -717,19 +589,6 @@ https://pris.ly/d/schema-incompatibilities#enums-are-represented-as-text-in-data > **⚠️ Warning**: If you are running Prisma 1 and Prisma ORM 2 [side-by-side](/orm/more/upgrade-guides/upgrade-from-prisma-1/how-to-upgrade#upgrade-strategies), these [SQL statements will break your Prisma 1 setup](https://github.com/prisma/upgrade/issues/74). The docs will be updated to reflect this soon. - - - - -```no-lines wrap -Fix columns with ENUM data types -https://pris.ly/d/schema-incompatibilities#enums-are-represented-as-text-in-database - - ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL; -``` - - - Go ahead and run these statements against your database now. ![Altering columns to use ENUM with SQL](images/altering-columns-to-use-enum.png) @@ -740,8 +599,6 @@ Next, the Upgrade CLI helps you resolve the issue that [default values aren't re In this case, two `DEFAULT` constraints are missing which are suggested by the tool: - - ```no-lines wrap Add missing `DEFAULT` constraints to the database https://pris.ly/d/schema-incompatibilities#default-values-arent-represented-in-database @@ -754,24 +611,6 @@ You can now run these SQL statements against your database either using a comman ![Adding missing `DEFAULT` constraints to columns](images/add-missing-default-constraints-to-columns.png) - - - - -```no-lines wrap -Add missing `DEFAULT` constraints to the database -https://pris.ly/d/schema-incompatibilities#default-values-arent-represented-in-database - - ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL DEFAULT 'CUSTOMER'; - ALTER TABLE `Post` CHANGE `published` `published` TINYINT(1) NOT NULL DEFAULT 0; -``` - -You can now run these SQL statements against your database either using a command line client or a GUI like TablePlus: - -![TablePlus GUI](images/TablePlus-GUI.png) - - - ### 5.1.3. Fix columns with JSON data types Next, the tool helps you ensure that `Json` fields in your Prisma 1 datamodel will be represented as `JSON` columns in the underlying database, right now they are represented as plain strings (e.g. as `MEDIUMTEXT` in MySQL). @@ -780,8 +619,6 @@ Changing the column type to `JSON` will ensure that the field is properly recogn The CLI currently shows the following output: - - ```no-lines wrap Fix columns with JSON data types https://pris.ly/d/schema-incompatibilities#json-type-is-represented-as-text-in-database @@ -795,22 +632,6 @@ You can now run these SQL statements against your database either using a comman ![Adding missing `DEFAULT` constraints to columns](images/fix-columns-with-json-data-types.png) - - - - -```no-lines wrap -Fix columns with JSON data types -https://pris.ly/d/schema-incompatibilities#json-type-is-represented-as-text-in-database - - ALTER TABLE `User` CHANGE `jsonData` `jsonData` JSON ; -``` - -You can now run these SQL statements against your database either using a command line client or a GUI like TablePlus: - -![TablePlus GUI](images/fix-columns-with-json-data-types.png) - - ### 5.1.4. Replicate `@createdAt` behavior in Prisma ORM 2 @@ -818,8 +639,6 @@ The next thing the tools does is help you resolve the issue that the behavior of The CLI currently shows the following output: - - ```no-lines wrap Replicate `@createdAt` behavior in Prisma ORM 2.0 https://pris.ly/d/schema-incompatibilities#createdat-isnt-represented-in-database @@ -831,29 +650,12 @@ You can now run these SQL statements against your database either using a comman ![Running an SQL command to alter a column](images/run-sql-command-to-alter-column.png) - - - - -```no-lines wrap -Replicate `@createdAt` behavior in Prisma ORM 2.0 -https://pris.ly/d/schema-incompatibilities#createdat-isnt-represented-in-database - - ALTER TABLE `Post` CHANGE `createdAt` `createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; -``` - -You can now run these SQL statements against your database either using a command line client or a GUI like TablePlus. - - - ### 5.1.5. Fix 1-1 relations by adding `UNIQUE` constraints Now, the tool will help you [turn the current 1-n relation between `User` ↔ `Profile` back into a 1-1 relation](/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql#inline-1-1-relations-are-recognized-as-1-n-missing-unique-constraint) by adding a `UNIQUE` constraint to the foreign key column called `user` (named after the relation field in the Prisma 1 datamodel) in the database. The CLI currently shows the following output: - - ```no-lines wrap Fix 1-1 relations by adding `UNIQUE` constraints https://pris.ly/d/schema-incompatibilities#inline-1-1-relations-are-recognized-as-1-n-missing-unique-constraint @@ -865,21 +667,6 @@ You can now run these SQL statements against your database either using a comman ![Running an SQL command to alter a column](images/run-sql-command-to-alter-column.png) - - - - -```no-lines wrap -Fix 1-1 relations by adding `UNIQUE` constraints -https://pris.ly/d/schema-incompatibilities#inline-1-1-relations-are-recognized-as-1-n-missing-unique-constraint - - ALTER TABLE `Profile` ADD UNIQUE (`user`); -``` - -You can now run these SQL statements against your database either using a command line client or a GUI like TablePlus. - - - ### 5.1.6. Fix mismatch of CUID length > **Note**: These SQL statements will keep appearing in the Upgrade CLI even after you have changed the column types in the underlying database. This is a currently a limitation in the Upgrade CLI. @@ -888,8 +675,6 @@ Finally, the tool will help you [turn the current ID columns of type `VARCHAR(25 The CLI currently shows the following output: - - ```no-lines wrap wrap Migrate IDs from varchar(25) to varchar(30) https://pris.ly/d/schema-incompatibilities#mismatching-cuid-length @@ -905,27 +690,6 @@ You can now run these SQL statements against your database either using a comman ![Running an SQL command to alter a column](images/run-sql-command-to-alter-column.png) - - - - -```no-lines wrap -Migrate IDs from varchar(25) to varchar(30) -https://pris.ly/d/schema-incompatibilities#mismatching-cuid-length - -SET FOREIGN_KEY_CHECKS=0; -ALTER TABLE `Category` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; -ALTER TABLE `Post` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; -ALTER TABLE `Profile` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; -ALTER TABLE `Profile` CHANGE `user` `user` char(30) CHARACTER SET utf8 ; -ALTER TABLE `User` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL; -SET FOREIGN_KEY_CHECKS=1; -``` - -You can now run these SQL statements against your database either using a command line client or a GUI like TablePlus. - - - ### 5.1.7. Breaking changes detected In case the Upgrade CLI has printed a note about breaking changes, your database schema needs some adjustments that will break Prisma 1 compatibility in order to be fully optimized. @@ -953,8 +717,6 @@ To fix this, you'll need to perform the following migration: These instructions are now printed by the CLI: - - ```no-lines wrap ➤ Adjust your database schema Run the following SQL statements against your database: @@ -1006,61 +768,6 @@ For this fix, you'll need to run three SQL statements: ![Fixing incorrect m-n relations with SQL](images/fix-incorrect-m-n-relations-sql.png) - - - - -```no-lines wrap -➤ Adjust your database schema -Run the following SQL statements against your database: - - Fix one-to-many table relations - https://pris.ly/d/schema-incompatibilities#all-non-inline-relations-are-recognized-as-m-n - - ALTER TABLE `Post` ADD COLUMN `authorId` char(25) CHARACTER SET utf8 ; - ALTER TABLE `Post` ADD CONSTRAINT author FOREIGN KEY (`authorId`) REFERENCES `User`(`id`); - UPDATE `Post`, `_PostToUser` SET `Post`.`authorId` = `_PostToUser`.B where `_PostToUser`.A = `Post`.`id`; - DROP TABLE `_PostToUser`; - - -➤ Next Steps - -After you executed one or more of the above SQL statements against your database, -please run the following two commands to refresh your Prisma ORM 2 Schema and check -the changes. - - 1. Run `npx prisma db pull` again to refresh your Prisma ORM 2 schema. - 2. Run `npx prisma-upgrade` again. - -If you can't or don't want to execute the remaining SQL statements right now, you can -skip to the last step where the Upgrade CLI adds missing attributes to your Prisma ORM 2 -schema that are not picked up by introspection. - -Skip to the last step? [Y/n]? -``` - -For this fix, you'll need to run three SQL statements: - -1. Create new column `authorId` on the `Post` table. This column should be a _foreign key_ that references the `id` field of the `User` table: - ```sql no-lines - ALTER TABLE `Post` ADD COLUMN `authorId` char(25) CHARACTER SET utf8 ; - ALTER TABLE `Post` ADD CONSTRAINT author FOREIGN KEY (`authorId`) REFERENCES `User`(`id`); - ``` -1. Write a SQL query that reads all the rows from the `_PostToUser` relation table and for each row: - 1. Finds the respective `Post` record by looking up the value from column `A` - 1. Inserts the value from column `B` as the value for `authorId` into that `Post` record - ```sql no-lines - UPDATE `Post`, `_PostToUser` SET `Post`.`authorId` = `_PostToUser`.B where `_PostToUser`.A = `Post`.`id`; - ``` -1. Delete the `_PostToUser` relation table - ```sql no-lines - DROP TABLE `_PostToUser`; - ``` - -![Fixing incorrect m-n relations with SQL](images/fix-incorrect-m-n-relations-sql.png) - - - After these commands, the user ID values of the records from column `B` of the relation table are migrated to the new `authorId` column. ### 5.2. Re-introspect your database to update your Prisma schema diff --git a/docs/index.mdx b/docs/index.mdx new file mode 100644 index 0000000000..112944992b --- /dev/null +++ b/docs/index.mdx @@ -0,0 +1,10 @@ +--- +title: 'Homepage' +metaTitle: 'homepage' +metaDescription: 'About the Prisma docs.' +hide_table_of_contents: true +--- + + + + diff --git a/docusaurus.config.ts b/docusaurus.config.ts index ec5d4a1a9d..af019706c6 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -11,7 +11,7 @@ const config: Config = { url: 'https://prisma.io', // Set the // pathname under which your site is served // For GitHub pages deployment, it is often '//' - baseUrl: '/', + baseUrl: '/docs', trailingSlash: false, onBrokenLinks: 'warn', diff --git a/sidebars.ts b/sidebars.ts index 6973fbd62c..eb6b78a47f 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -16,7 +16,35 @@ const platformCategory: SidebarItemConfig = { id: 'platform/index', }, className: "firstTitle", - items: [{ type: 'autogenerated', dirName: '500-platform' }], + items: [ + { + type: 'category', + label: 'Concepts', + collapsed: false, + collapsible: false, + link: { + type: 'generated-index', + title: 'Concepts', + slug: '/platform/concepts', + }, + items: [{ type: 'autogenerated', dirName: '500-platform/20-concepts' }] + }, + 'platform/maturity-levels', + 'platform/limits', + 'platform/support', + { + type: 'category', + collapsible: false, + collapsed: false, + label: 'Platform CLI', + link: { + type: 'generated-index', + title: 'Platform CLI', + slug: '/platform/platform-cli', + }, + items: [{ type: 'autogenerated', dirName: '500-platform/60-platform-cli' }], + }, + ], }; /** @@ -31,6 +59,7 @@ const platformCategory: SidebarItemConfig = { */ const sidebars: SidebarsConfig = { // By default, Docusaurus generates a sidebar from the docs folder structure + index: ['index'], gettingStarted: [ { type: 'category', @@ -48,6 +77,9 @@ const sidebars: SidebarsConfig = { type: 'doc', id: 'getting-started/quickstart', label: 'Quickstart', + customProps: { + badge: "5 Min" + } }, { type: 'category', @@ -59,31 +91,217 @@ const sidebars: SidebarsConfig = { id: 'getting-started/setup-prisma/index', }, items: [ - { - type: 'category', - label: 'Start from scratch', - link: { - type: 'doc', - id: 'getting-started/setup-prisma/start-from-scratch/index', + { + type: 'category', + label: "Start from scratch", + link: { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/index', + }, + items: [ + { + type: 'category', + label: 'Relational databases', + customProps: { + badge: '15 Min' + }, + link: { + type: 'generated-index', + title: 'Relation databases', + slug: '/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql', + }, + items: [ + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-mysql', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-planetscale', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-sqlserver', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-cockroachdb', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/relational-databases-node-postgresql', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/relational-databases-node-mysql', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/relational-databases-node-planetscale', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/relational-databases-node-sqlserver', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/relational-databases-node-cockroachdb', + className: 'hidden-sidebar' + }, + { + type: 'autogenerated', + dirName: '100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases', + } + ] }, - items: [{ - type: 'autogenerated', - dirName: '100-getting-started/02-setup-prisma/100-start-from-scratch' - }] + { + type: 'category', + label: 'MongoDB', + customProps: { + badge: '15 Min' + }, + link: { + type: 'generated-index', + title: 'MongoDB', + slug: '/getting-started/setup-prisma/start-from-scratch/mongodb-typescript-mongodb', + }, + items: [ + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/mongodb-node-mongodb', + className: "hidden-sidebar" + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/start-from-scratch/mongodb-typescript-mongodb', + className: "hidden-sidebar" + }, + { + type: 'autogenerated', + dirName: '100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb', + } + ] + } + ] + }, + { + type: 'category', + label: "Add to existing project", + link: { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/index', }, - { - type: 'category', - label: 'Add to existing project', - link: { - type: 'doc', - id: 'getting-started/setup-prisma/add-to-existing-project/index', + items: [ + { + type: 'category', + label: 'Relational databases', + customProps: { + badge: '15 Min' + }, + link: { + type: 'generated-index', + title: 'Relation databases', + slug: '/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql', + }, + items: [ + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-mysql', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-planetscale', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-sqlserver', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-cockroachdb', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/relational-databases-node-postgresql', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/relational-databases-node-mysql', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/relational-databases-node-planetscale', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/relational-databases-node-sqlserver', + className: 'hidden-sidebar' + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/relational-databases-node-cockroachdb', + className: 'hidden-sidebar' + }, + { + type: 'autogenerated', + dirName: '100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases', + } + ] }, - items: [{ - type: 'autogenerated', - dirName: '100-getting-started/02-setup-prisma/200-add-to-existing-project' - }] - } - ] + { + type: 'category', + label: 'MongoDB', + customProps: { + badge: '15 Min' + }, + link: { + type: 'generated-index', + title: 'MongoDB', + slug: '/getting-started/setup-prisma/add-to-existing-project/mongodb-typescript-mongodb', + }, + items: [ + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/mongodb-node-mongodb', + className: "hidden-sidebar" + }, + { + type: 'doc', + id: 'getting-started/setup-prisma/add-to-existing-project/mongodb-typescript-mongodb', + className: "hidden-sidebar" + }, + { + type: 'autogenerated', + dirName: '100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb', + }] + } + ] + },] } ] } @@ -98,7 +316,114 @@ const sidebars: SidebarsConfig = { id: 'orm/orm-index' }, className: 'firstTitle', - items: [{ type: 'autogenerated', dirName: '200-orm' }], + items: [ + 'orm/orm-index', + { + type: 'category', + label: 'Overview', + collapsed: false, + collapsible: false, + link: { + type: 'generated-index', + title: 'Overview', + slug: '/orm/overview', + }, + items: [{ + type: 'autogenerated', + dirName: '200-orm/050-overview', + }] + }, + { + type: 'category', + label: 'Prisma Schema', + collapsed: false, + collapsible: false, + link: { + type: 'generated-index', + title: 'Prisma Schema', + slug: '/orm/prisma-schema', + }, + items: [{ + type: 'autogenerated', + dirName: '200-orm/100-prisma-schema' + }] + }, + { + type: 'category', + label: 'Prisma Client', + collapsed: false, + collapsible: false, + link: { + type: 'generated-index', + title: 'Prisma Client', + slug: '/orm/prisma-client', + }, + items: [{ + type: 'autogenerated', + dirName: '200-orm/200-prisma-client' + }] + }, + { + type: 'category', + label: 'Prisma Migrate', + collapsed: false, + collapsible: false, + link: { + type: 'generated-index', + title: 'Prisma Migrate', + slug: '/orm/prisma-migrate', + }, + items: [{ + type: 'autogenerated', + dirName: '200-orm/300-prisma-migrate' + }] + }, + { + type: 'category', + label: 'Tools', + collapsed: false, + collapsible: false, + link: { + type: 'generated-index', + title: 'Tools', + slug: '/orm/tools', + }, + items: [{ + type: 'autogenerated', + dirName: '200-orm/400-tools' + }] + }, + { + type: 'category', + label: 'Reference', + collapsed: false, + collapsible: false, + link: { + type: 'generated-index', + title: 'Reference', + slug: '/orm/reference', + }, + items: [{ + type: 'autogenerated', + dirName: '200-orm/500-reference' + }] + }, + { + type: 'category', + label: 'More', + collapsed: false, + collapsible: false, + link: { + type: 'generated-index', + title: 'More', + slug: '/orm/more', + }, + items: [{ + type: 'autogenerated', + dirName: '200-orm/800-more' + }] + } + ] }], accelerateSidebar: [ { diff --git a/src/components/shortcodes/switcherBlock.tsx b/src/components/shortcodes/switcherBlock.tsx index 65073c36a0..2c2d21f756 100644 --- a/src/components/shortcodes/switcherBlock.tsx +++ b/src/components/shortcodes/switcherBlock.tsx @@ -90,7 +90,7 @@ const SwitcherBlock = ({ langSwitcher, dbSwitcher, location, slug }: any) => { defaultTech={dbSelected} /> )} - {langSelected === "typescript" && dbSwitcher && + {langSelected === "typescript" && langSwitcher && dbSwitcher && { defaultTech={dbSelected} /> } + {!langSwitcher && dbSwitcher && + + } ) } diff --git a/src/components/shortcodes/techSwitcher.tsx b/src/components/shortcodes/techSwitcher.tsx index 4224452088..0cd63a0ce8 100644 --- a/src/components/shortcodes/techSwitcher.tsx +++ b/src/components/shortcodes/techSwitcher.tsx @@ -1,18 +1,8 @@ import * as React from 'react' import styled from 'styled-components' -// import { Typescript } from '../icons/technologies/Typescript' import SelectComponent from './select' -// import PostgreSQL from '../icons/technologies/PostgreSQL' -// import MySQL from '../icons/technologies/MySQL' -// import SQLite from '../icons/technologies/SQLite' -// import MongoDB from '../icons/technologies/MongoDB' -// import JS from '../icons/technologies/JS' -// import SQLServer from '../icons/technologies/MSSQL' -// import PlanetScale from '../icons/technologies/PlanetScale' -// import CockroachDB from '../icons/technologies/CockroachDB' import { components } from 'react-select' import Link from '@docusaurus/Link' -// import ArrowDown from '../icons/ArrowDown' interface TechSwitchProps { type: string @@ -28,15 +18,15 @@ interface TechItem { } const icons = { - node: `/img/technologies/nodejs.svg`, //, - typescript: `/img/technologies/typescript.svg`, //, - mysql: `/img/technologies/mysql.svg`, //, - postgresql: `/img/technologies/postgresql.svg`, //, - sqlite: `/img/technologies/sqlite.svg`, //, - mongodb: `/img/technologies/mongodb.svg`, //, - sqlserver: `/img/technologies/sqlserver.svg`, //, - planetscale: `/img/technologies/planetscale.svg`, //, - cockroachdb: `/img/technologies/cockroachdb.svg`, //, + node: `/docs/img/technologies/nodejs.svg`, //, + typescript: `/docs/img/technologies/typescript.svg`, //, + mysql: `/docs/img/technologies/mysql.svg`, //, + postgresql: `/docs/img/technologies/postgresql.svg`, //, + sqlite: `/docs/img/technologies/sqlite.svg`, //, + mongodb: `/docs/img/technologies/mongodb.svg`, //, + sqlserver: `/docs/img/technologies/sqlserver.svg`, //, + planetscale: `/docs/img/technologies/planetscale.svg`, //, + cockroachdb: `/docs/img/technologies/cockroachdb.svg`, //, } const technologyTypes = { @@ -68,8 +58,6 @@ const TechnologySwitch = ({ type, onChangeTech, technologies, defaultTech, url, const langDefault = { technology: defaultTech || 'typescript' } const dbDefault = { technology: defaultTech || 'postgresql' } const defaultItem = type === 'lang' ? langDefault : dbDefault - - console const [selectedItem, setSelectedItem] = React.useState(defaultItem) const renderItem = (item: TechItem) => { diff --git a/src/css/custom.css b/src/css/custom.css index 5b0c6dc3d6..83e34b3951 100644 --- a/src/css/custom.css +++ b/src/css/custom.css @@ -8,7 +8,7 @@ @media (min-width: 997px) { main:has( > div > .row ){ - max-width: calc(100% - var(--doc-sidebar-width) - 20%) !important; + max-width: calc(100% - var(--doc-sidebar-width) - 20px) !important; } main:has( > div > .row .col--3){ max-width: calc(100% - var(--doc-sidebar-width)) !important; @@ -1050,7 +1050,7 @@ footer > .container { } .hidden-sidebar { - display: none; + display: none !important; } .theme-doc-markdown { diff --git a/src/theme/DocSidebarItem/Link/index.tsx b/src/theme/DocSidebarItem/Link/index.tsx index 1c742088ec..5e8e6ef5c1 100644 --- a/src/theme/DocSidebarItem/Link/index.tsx +++ b/src/theme/DocSidebarItem/Link/index.tsx @@ -5,6 +5,7 @@ import {isActiveSidebarItem} from '@docusaurus/theme-common/internal'; import Link from '@docusaurus/Link'; import isInternalUrl from '@docusaurus/isInternalUrl'; import styles from './styles.module.css'; +import {useLocation} from '@docusaurus/router'; import { Icon } from '@site/src/components/Icon'; export default function DocSidebarItemLink({ item, @@ -16,13 +17,38 @@ export default function DocSidebarItemLink({ }) { const {href, label, className, autoAddBaseUrl} = item; const isActive = isActiveSidebarItem(item, activePath); + const [techSwitch, setTechSwitch] = useState(false) const isInternalLink = isInternalUrl(href); + const location = useLocation(); + const [badgeContent, setBadgeContent] = useState(undefined) + + const checkPath = () => { + if (location.pathname.includes("-typescript-") || location.pathname.includes("-node-")) { + const splitLocation = location.pathname.split("typescript-")[0].split("node-")[0] + const splitItem = href.split("typescript-")[0].split("node-")[0] + + if (splitItem === splitLocation) return true + else return false + } else { + const splitLocation = location.pathname.split("-mysql")[0].split("-postgresql")[0] + const splitItem = href.split("-mysql")[0].split("-postgresql")[0] + + if (splitItem === splitLocation) return true + else return false + } + } + useEffect(() => { if (item && item.customProps && item.customProps.badge) { setBadgeContent(item.customProps.badge) } + setTechSwitch(checkPath()) }, [item]) + + useEffect(() => { + setTechSwitch(checkPath()) + }, [location]) return (