Skip to content

Commit

Permalink
Merge branch 'main' into turso-guide
Browse files Browse the repository at this point in the history
  • Loading branch information
ruheni authored Oct 31, 2023
2 parents 037469d + 9a55991 commit c38e6af
Show file tree
Hide file tree
Showing 6 changed files with 291 additions and 21 deletions.
68 changes: 60 additions & 8 deletions content/400-reference/200-api-reference/200-command-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -306,13 +306,13 @@ The `init` command does not interpret any existing files. Instead, it creates a

#### Arguments

| Argument | Required | Description | Default |
|-------------------------|----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------|
| `--datasource-provider` | No | Specifies the default value for the `provider` field in the `datasource` block. Options are `sqlite`, `postgresql`, `mysql`, `sqlserver`, `mongodb` and `cockroachdb`. | `postgresql` |
| `--url` | No | Define a custom datasource url. | |
| `--generator-provider` | No | Define the default generator provider to use. | `prisma-client-js` |
| `--preview-features` | No | Define the default Preview features to use. [Learn more](/concepts/components/preview-features) | |
| `--output` | No | Specifies the default output location for the generated client. [Learn more](/concepts/components/prisma-client/working-with-prismaclient/generating-prisma-client#using-a-custom-output-path) | `node_modules/.prisma/client` |
| Argument | Required | Description | Default |
| ----------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `--datasource-provider` | No | Specifies the value for the `provider` field in the `datasource` block. Options are `sqlite`, `postgresql`, `mysql`, `sqlserver`, `mongodb` and `cockroachdb`. | `postgresql` |
| `--url` | No | Define a custom datasource url. | |
| `--generator-provider` | No | Define the generator provider to use. | `prisma-client-js` |
| `--preview-feature` | No | Define the [Preview features](/concepts/components/preview-features) to use. To define multiple Preview features, you have to provide the flag multiple times for each Preview feature. [See example](#run-prisma-init---preview-feature) | |
| `--output` | No | Specifies the [output location for the generated client](/concepts/components/prisma-client/working-with-prismaclient/generating-prisma-client#using-a-custom-output-path). | `node_modules/.prisma/client` |

#### Examples

Expand Down Expand Up @@ -356,6 +356,58 @@ prisma init --datasource-provider sqlite

The command output contains helpful information on how to use the generated files and begin using Prisma with your project.

#### Run `prisma init --preview-feature`

<CodeWithResult outputResultText="Prisma schema" expanded={true}>

<cmd>```terminal prisma init --preview-feature multiSchema```</cmd>

<cmdResult>

```prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["multiSchema"]
}
```

</cmdResult>

</CodeWithResult>

<CodeWithResult outputResultText="Prisma schema" expanded={true}>

<cmd>

```terminal
prisma init --preview-feature multiSchema --preview-feature metrics
```

</cmd>

<cmdResult>

```prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["multiSchema", "metrics"]
}
```

</cmdResult>

</CodeWithResult>

#### Generated Assets

**`prisma/schema.prisma`**
Expand Down Expand Up @@ -997,7 +1049,7 @@ Other options:
- Take the SQL script from standard input and execute it on the database specified by the data source URL given in the `DATABASE_URL` environment variable:

```terminal wrap
$ echo 'TRUNCATE TABLE dev;' | prisma db execute --stdin --url="$DATABASE_URL"
echo 'TRUNCATE TABLE dev;' | prisma db execute --stdin --url="$DATABASE_URL"
```

## Prisma Migrate
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,10 @@ The goal of Accelerate is to improve response times and reduce database load. It

While Accelerate is beneficial for all types of applications, being at the edge provides additional benefits to edge function environments like [Vercel Edge Functions](https://vercel.com/docs/concepts/functions/edge-functions), [Cloudflare Workers](https://workers.cloudflare.com/), and [Deno Deploy](https://deno.com/deploy). Cache hits can be served from data centers near the user regardless of the region of the database.

<Admonition type="info">

Accelerate is in Preview. While we have high confidence in our product, the nature of an Preview product is that significant iterations might happen at any time, so we would advise against placing it in a system that requires stability.

</Admonition>

</TopBlock>

## See Accelerate in action

We built a small sample application, [Accelerate Speed Test](https://accelerate-speed-test.prisma.io/). The app compares the performance of cached and uncached queries side by side. The app is [open source](https://github.com/prisma/accelerate-speed-test) and you can clone it to try it yourself.

![Screenshot of the Accelerate Speed Test app showing cached query performance](./images/speed-test.png)
![Screenshot of the Accelerate Speed Test app showing cached query performance](./images/accelerate.png)
228 changes: 228 additions & 0 deletions content/800-data-platform/100-accelerate/550-testing.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
---
title: 'Testing'
metaTitle: 'Accelerate: Testing'
metaDescription: 'Learn about testing Prisma Accelerate.'
tocDepth: 3
toc: true
---

<TopBlock>

Prisma Accelerate optimizes database interactions through advanced connection pooling and global edge caching. Its connection pooler is available in 16 regions and helps applications load-balance and scale database requests based on demand.

Considering the information above, we recommend testing Accelerate with high volume to see it perform under load.

</TopBlock>

## How Accelerate's connection pool optimizes performance under load

Prisma Accelerate employs a dynamic, serverless connection pooling infrastructure. When a request is made, a connection pool is quickly provisioned for the project in the region assigned while configuring Prisma Accelerate. This connection pool remains active, serving many additional requests while reusing established database connections. The connection pool will disconnect after a period of inactivity, so it’s important to test Prisma Accelerate with a consistent stream of traffic.

**Key Benefits:**

- **Optimized Query Performance:** The serverless connection pooler adapts to the query load, ensuring the database connections are managed efficiently during peak demand.

> Prisma Accelerate’s connection pooler cannot improve the performance of queries in the database. In scenarios where query performance is an issue, we recommend optimizing the Prisma query, applying indexes, or utilizing Accelerate’s edge caching.
- **Maximize Connection Reuse:** Executing a consistent volume of queries helps maintain active instances of Accelerate connection poolers. This increases connection reuse, ensuring faster response times for subsequent queries.

By understanding and harnessing this mechanism, you can ensure that your database queries perform consistently and efficiently at scale.

## Testing Prisma Accelerate connection pooling performance

Below you will find an example of how to test Prisma Accelerate using a sample model:

```prisma
model Notes {
id Int @id @default(autoincrement())
title String
createdAt DateTime @default(now())
updatedAt DateTime? @updatedAt
}
```

```typescript
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

function calculateStatistics(numbers: number[]): {
average: number
p50: number
p75: number
p99: number
} {
if (numbers.length === 0) {
throw new Error('The input array is empty.')
}

// Sort the array in ascending order
numbers.sort((a, b) => a - b)

const sum = numbers.reduce((acc, num) => acc + num, 0)
const count = numbers.length

const average = sum / count
const p50 = getPercentile(numbers, 50)
const p75 = getPercentile(numbers, 75)
const p99 = getPercentile(numbers, 99)

return { average, p50, p75, p99 }
}

function getPercentile(numbers: number[], percentile: number): number {
if (percentile <= 0 || percentile >= 100) {
throw new Error('Percentile must be between 0 and 100.')
}

const index = (percentile / 100) * (numbers.length - 1)
if (Number.isInteger(index)) {
// If the index is an integer, return the corresponding value
return numbers[index]
} else {
// If the index is not an integer, interpolate between two adjacent values
const lowerIndex = Math.floor(index)
const upperIndex = Math.ceil(index)
const lowerValue = numbers[lowerIndex]
const upperValue = numbers[upperIndex]
const interpolationFactor = index - lowerIndex
return lowerValue + (upperValue - lowerValue) * interpolationFactor
}
}

async function main() {
const timings = []

// fire a query before going to the loop
await prisma.notes.findMany({
take: 20,
})

// we recommend testing Prisma Accelerate with a large loop
const LOOP_LENGTH = 10000

for (let i = 0; i < LOOP_LENGTH; i++) {
const start = Date.now()
await prisma.notes.findMany({
take: 20,
})

timings.push(Date.now() - start)
}

const statistics = calculateStatistics(timings)
console.log('Average:', statistics.average)
console.log('P50:', statistics.p50)
console.log('P75:', statistics.p75)
console.log('P99:', statistics.p99)
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch((e) => {
await prisma.$disconnect()
process.exit(1)
})
```

## Testing Prisma Accelerate caching performance

Prisma Accelerate’s edge cache is also optimized for a high volume of queries. The cache automatically optimizes for repeated queries. As a result, the cache hit rate will increase as the query frequency does. Adding a query result to the cache is also non-blocking, so a short burst of queries might not utilize the cache or a sustained load.

To test Accelerate’s edge caching, you can modify the above script with the below:

```typescript
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

function calculateStatistics(numbers: number[]): {
average: number
p50: number
p75: number
p99: number
} {
if (numbers.length === 0) {
throw new Error('The input array is empty.')
}

// Sort the array in ascending order
numbers.sort((a, b) => a - b)

const sum = numbers.reduce((acc, num) => acc + num, 0)
const count = numbers.length

const average = sum / count
const p50 = getPercentile(numbers, 50)
const p75 = getPercentile(numbers, 75)
const p99 = getPercentile(numbers, 99)

return { average, p50, p75, p99 }
}

function getPercentile(numbers: number[], percentile: number): number {
if (percentile <= 0 || percentile >= 100) {
throw new Error('Percentile must be between 0 and 100.')
}

const index = (percentile / 100) * (numbers.length - 1)
if (Number.isInteger(index)) {
// If the index is an integer, return the corresponding value
return numbers[index]
} else {
// If the index is not an integer, interpolate between two adjacent values
const lowerIndex = Math.floor(index)
const upperIndex = Math.ceil(index)
const lowerValue = numbers[lowerIndex]
const upperValue = numbers[upperIndex]
const interpolationFactor = index - lowerIndex
return lowerValue + (upperValue - lowerValue) * interpolationFactor
}
}

async function main() {
const timings = []

// fire a query before going to the loop
await prisma.notes.findMany({
take: 20,
cacheStrategy: {
ttl: 30,
},
})

// we recommend testing Prisma Accelerate with a large loop
const LOOP_LENGTH = 10000

for (let i = 0; i < LOOP_LENGTH; i++) {
const start = Date.now()
await prisma.notes.findMany({
take: 20,
cacheStrategy: {
ttl: 30,
},
})

timings.push(Date.now() - start)
}

const statistics = calculateStatistics(timings)
console.log('Average:', statistics.average)
console.log('P50:', statistics.p50)
console.log('P75:', statistics.p75)
console.log('P99:', statistics.p99)
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch((e) => {
await prisma.$disconnect()
process.exit(1)
})
```
6 changes: 1 addition & 5 deletions content/800-data-platform/100-accelerate/600-faq.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,9 @@ Accelerate's cache performs best when it observes a higher load from a project.

Prisma operations are sent to Accelerate over HTTP. As a result, the first request to Accelerate must establish an HTTP handshake and may have additional latency as a result. We're exploring ways to reduce this initial request latency in the future.

## What happens to my Scale plan subscription if I switch to Accelerate?

While Accelerate is in Preview, you do not need a subscription or a monthly plan. With Accelerate, you can use the same Data Proxy [connection pooling features](/data-platform/accelerate/getting-started#no-cache-strategy-to-only-use-connection-pool) on top of the Accelerate global cache.

## What is the pricing of Accelerate?

When we officially launch Accelerate and make it generally available, we will provide pricing details.
You can find more details on our [Accelerate pricing page](https://www.prisma.io/pricing)

## VS Code does not recognize the `$extends` method

Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ SELECT pg_reload_conf();

## 2. Enable Pulse in a Cloud Project

Follow the steps described [here](/data-platform/cloud-projects/platform/projects#configure-pulse) to configure Pulse in a Cloud Project.
Log into the [Prisma Data Platform](https://console.prisma.io/login), create a new Cloud Project and enable Pulse for that new project.

## 3. Use Pulse in your application

Expand Down

0 comments on commit c38e6af

Please sign in to comment.