Skip to content

Commit

Permalink
Document how to delete all records from all tables (#1510)
Browse files Browse the repository at this point in the history
* adding content to crud page

* refactored, added tabs

* added some explainer text

* feedback changes

* Changed sqlite example
  • Loading branch information
molebox authored Apr 15, 2021
1 parent 38a849e commit 0548375
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 8 deletions.
6 changes: 6 additions & 0 deletions .vs/VSWorkspaceState.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"ExpandedNodes": [
""
],
"PreviewInSolutionExplorer": false
}
Binary file added .vs/docs/v15/.suo
Binary file not shown.
Binary file added .vs/slnx.sqlite
Binary file not shown.
86 changes: 78 additions & 8 deletions content/200-concepts/100-components/02-prisma-client/030-crud.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: 'CRUD'
metaTitle: 'CRUD (Reference)'
metaDescription: 'How to perform CRUD with Prisma Client.'
tocDepth: 3
tocDepth: 5
---

<TopBlock>
Expand Down Expand Up @@ -246,7 +246,7 @@ const user = await prisma.user.findUnique({

### Get record by compound ID or unique identifier

The following examples demonstrate how to retrieve records by a compound ID or unique identifier, defined by [`@@id`](../../../reference/api-reference/prisma-schema-reference#id-2) <span class="api"></span> or [`@@unique`](../../../reference/api-reference/prisma-schema-reference#unique-2) <span class="api"></span>.
The following examples demonstrate how to retrieve records by a compound ID or unique identifier, defined by [`@@id`](../../../reference/api-reference/prisma-schema-reference#id-2) <span class="api"></span> or [`@@unique`](../../../reference/api-reference/prisma-schema-reference#unique-2) <span class="api"></span>.

The following Prisma model defines an compound ID:

Expand All @@ -267,9 +267,9 @@ const timePeriod = await prisma.timePeriod.findUnique({
where: {
year_quarter: {
quarter: 4,
year: 2020
}
}
year: 2020,
},
},
})
```

Expand All @@ -292,9 +292,9 @@ const timePeriod = await prisma.timePeriod.findUnique({
where: {
timePeriodId: {
quarter: 4,
year: 2020
}
}
year: 2020,
},
},
})
```

Expand Down Expand Up @@ -768,6 +768,76 @@ To resolve this error, you can:
const transaction = await prisma.$transaction([deletePosts, deleteUser])
```
### Delete all records from all tables
Sometimes you want to remove all data from all tables but keep the actual tables. This can be particularly useful in a development environment. In the following two sections, you can learn how to delete all records from all tables with Prisma Client and with Prisma Migrate.
The following examples show how to remove all data (including relations) from all tables in your PostgreSQL, SQLite and MySQL databases.
The MySQL example uses a [`$transaction`](../../../guides/prisma-guides/prisma-client-transactions-guide/) to batch the queries together so that they are executed on the same connection.
The SQLite example uses [`deleteMany`](../../../reference/api-reference/prisma-client-reference#deletemany) in combination with a [`$transaction`](../../../guides/prisma-guides/prisma-client-transactions-guide/) to synchronously delete each tables data.
> **Note**: The SQLite `$transaction` performs a cascading delete on each models table so they have to be called in order.
<TabbedContent tabs={[<FileWithIcon text="PostgreSQL" icon="database"/>, <FileWithIcon text="SQLite" icon="database"/>, <FileWithIcon text="MySQL" icon="database"/>]}>
<tab>
```ts
// Special fast path to drop data from a postgres database.
// This is an optimization which is particularly crucial in a unit testing context.
// This code path takes milliseconds, vs ~7 seconds for a migrate reset + db push
for (const { tablename } of await this.prisma
.$queryRaw`SELECT tablename FROM pg_tables WHERE schemaname='${this.dbSchemaName}'`) {
await this.prisma.$queryRaw`TRUNCATE TABLE \"${this.dbSchemaName}\".\"${tablename}\" CASCADE;`
}
for (const { relname } of await this.prisma
.$queryRaw`SELECT c.relname FROM pg_class AS c JOIN pg_namespace AS n ON c.relnamespace = n.oid WHERE c.relkind='S' AND n.nspname='${this.dbSchemaName}';`) {
await this.prisma
.$queryRaw`ALTER SEQUENCE \"${this.dbSchemaName}\".\"${relname}\" RESTART WITH 1;`
}
```
</tab>
<tab>
```ts
const deletePosts = prisma.post.deleteMany()
const deleteProfile = prisma.profile.deleteMany()
const deleteUsers = prisma.user.deleteMany()

// The transaction runs synchronously so deleteUsers must run last.
await prisma.$transaction([deleteProfile, deletePosts, deleteUsers])
```
</tab>
<tab>
```ts
const [numberOfRowsDeleted] = await prisma.$transaction([
prisma.$executeRaw`SET FOREIGN_KEY_CHECKS = 0;`,
prisma.$executeRaw`TRUNCATE TABLE teams;`,
prisma.$executeRaw`TRUNCATE TABLE players;`,
prisma.$executeRaw`SET FOREIGN_KEY_CHECKS = 1;`,
])
```
</tab>
</TabbedContent>
#### Deleting all records with Prisma Migrate
If you use Prisma Migrate, you can use `migrate reset`, this will:
1. Drop the database
2. Create a new database
3. Apply migrations
4. Seed the database with data
## Advanced query examples
### Create a deeply nested tree of records
Expand Down

0 comments on commit 0548375

Please sign in to comment.