### Install Prisma Client Python Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/setup Installs the Prisma Client Python package from PyPi using pip. This is the initial step before configuring or generating the client. ```bash pip install prisma ``` -------------------------------- ### Database Connection URLs Example Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Example environment variables for setting up database connection URLs. These are required to run database tests for different providers. Ensure these variables are set according to your database setup. ```bash SQLITE_URL='file:dev.db' POSTGRES_URL='postgresql://<...>' ``` -------------------------------- ### Clone Repository and Setup Development Environment Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Steps to clone the prisma-client-py repository and set up a local development environment. This includes cloning the Git repository, creating and activating a virtual environment using venv, and bootstrapping the project with necessary installations and database setup. ```bash git clone https://github.com/RobertCraigie/prisma-client-py.git cd prisma-client-py python3 -m venv .venv source .venv/bin/activate make bootstrap ``` -------------------------------- ### Integration Test Setup Script (Bash) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing This script sets up a Python virtual environment and activates it for integration tests. It ensures that necessary packages are installed, including the Prisma client itself. ```bash #!/bin/bash set -eux python3 -m venv .venv set +x source .venv/bin/activate set -x ``` -------------------------------- ### Configure Pyright with pyproject.toml Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/quickstart Sets up Pyright's configuration using a `pyproject.toml` file. This example specifies which files to include for type checking (`main.py`) and sets the type checking mode to 'strict', which enforces stricter type checking rules. ```toml [tool.pyright] include = [ "main.py", ] typeCheckingMode = "strict" ``` -------------------------------- ### Synchronous Prisma Client Boilerplate Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/setup Provides the minimum Python code required to initialize, connect, and disconnect a synchronous Prisma Client. It demonstrates the basic structure for a synchronous application interacting with the database. ```python from prisma import Prisma def main() -> None: db = Prisma() db.connect() # write your queries here db.disconnect() if __name__ == '__main__': main() ``` -------------------------------- ### Prisma Client Python CRUD Operations (Asyncio) Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/quickstart Demonstrates asynchronous creation and retrieval of a 'Post' record using Prisma Client Python. It connects to the database, creates a new post, fetches it back using its ID, and then disconnects. This example utilizes Python's `asyncio` for non-blocking I/O operations. ```python import asyncio from prisma import Prisma async def main() -> None: db = Prisma() await db.connect() post = await db.post.create( { 'title': 'Hello from prisma!', 'desc': 'Prisma is a database toolkit and makes databases easy.', 'published': True, } ) print(f'created post: {post.json(indent=2, sort_keys=True)}') found = await db.post.find_unique(where={'id': post.id}) assert found is not None print(f'found post: {found.json(indent=2, sort_keys=True)}') await db.disconnect() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Serve Documentation Locally Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Command to start a local development server for the project's documentation. This allows for live preview of documentation changes as they are made, utilizing mkdocs and the mkdocs-material theme. ```bash make docs-serve ``` -------------------------------- ### Asyncio Prisma Client Boilerplate Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/setup Provides the minimum Python code required to initialize, connect, and disconnect an asynchronous Prisma Client. It demonstrates the basic structure for an asyncio application interacting with the database. ```python import asyncio from prisma import Prisma async def main() -> None: db = Prisma() await db.connect() # write your queries here await db.disconnect() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Installing Prisma in Integration Tests (Bash) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Commands to install the Prisma client package within an integration test environment. It supports installing from requirements files or directly from a cached wheel file. ```bash pip install -U -r ../../../requirements/.txt pip install -U --force-reinstall ../../../.tests_cache/dist/*.whl ``` -------------------------------- ### Basic Unit Test Example (Python) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing A fundamental example of a unit test for Prisma Client Python using `pytest`. It demonstrates how to use the `Prisma` client within an asynchronous test function. ```python import pytest from prisma import Prisma @pytest.mark.asyncio async def test_example(client: Prisma) -> None: """Test docstring""" ... ``` -------------------------------- ### Create Python Virtual Environment Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/quickstart This snippet demonstrates how to create and activate a Python virtual environment for isolating project dependencies. It's a standard practice for managing Python projects. ```bash mkdir demo && cd demo python3 -m venv .venv ``` -------------------------------- ### Install Prisma Client Python Source: https://prisma-client-py.readthedocs.io/en/stable/index Installs the Prisma Client Python library using pip. This command ensures that the necessary package is available in your Python environment for database interactions. ```bash pip install -U prisma ``` -------------------------------- ### Generate Prisma Client Manually Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/quickstart Generates the Prisma Client without modifying the database. This is useful when you only need to update the client code based on schema changes. ```bash prisma generate ``` -------------------------------- ### Install Pyright using npm Source: https://prisma-client-py.readthedocs.io/en/stable/reference/type_checkers/pyright Installs the official version of Pyright globally using npm. This method is suitable for JavaScript/Node.js environments or when a global installation is preferred. ```bash npm install -g pyright ``` -------------------------------- ### Install Pyright using pip Source: https://prisma-client-py.readthedocs.io/en/stable/reference/type_checkers/pyright Installs the pyright package, a wrapper over the official version, using pip. This is the recommended method for Python environments. ```bash pip install pyright ``` -------------------------------- ### Prisma Client Python Type Hinting Example Source: https://prisma-client-py.readthedocs.io/en/stable/index Demonstrates how Prisma Client Python leverages static typing for query arguments, providing auto-completion suggestions within IDEs for model fields. ```python user = await db.user.find_first( where={ '|' } ) ``` -------------------------------- ### Running Snapshot Tests with Nox (Bash) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Examples of how to run snapshot tests using `nox`. These commands are used for creating or fixing inline snapshots and updating standalone snapshots managed by `syrupy`. ```bash nox -s test -p 3.9 -- --inline-snapshot=fix nox -s test -p 3.9 -- --snapshot-update tests/test_generation/exhaustive ``` -------------------------------- ### Example GraphQL Query for findUniqueUser Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/architecture An example of a GraphQL query structure used to fetch a single user record based on a unique identifier. This query is constructed by the rendered 'builder.py' file. ```graphql query { result: findUniqueUser ( where: { id: "ckq23ky3003510r8zll5m2hma" } ) { id name profile { id user_id bio } } } ``` -------------------------------- ### Model-Based Unit Test Example (Python) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing An example of a unit test that utilizes model-based access in Prisma Client Python. It requires specific markers (`@pytest.mark.prisma` and `@pytest.mark.asyncio`) to be applied. ```python import pytest @pytest.mark.prisma @pytest.mark.asyncio async def test_example() -> None: """Test docstring""" ... ``` -------------------------------- ### Sync Interactive Transaction Example - Prisma Source: https://prisma-client-py.readthedocs.io/en/stable/reference/transactions Illustrates how to perform a synchronous interactive transaction using Prisma Client Python. This example mirrors the async version, updating user balances and handling potential overdrafts within a transaction context. ```python from prisma import Prisma prisma = Prisma() prisma.connect() with prisma.tx() as transaction: user = transaction.user.update( where={'id': from_user_id}, data={'balance': {'decrement': 50}} ) if user.balance < 0: raise ValueError(f'{user.name} does not have enough balance') transaction.user.update( where={'id': to_user_id}, data={'balance': {'increment': 50}} ) ``` -------------------------------- ### Example Markdown Schema Generator Source: https://prisma-client-py.readthedocs.io/en/stable/reference/custom-generators A complete example of a Prisma generator that creates a markdown file summarizing the Prisma schema. It utilizes template strings and processes the DMMF to dynamically generate content for each model. ```python from pathlib import Path from prisma.generator import Manifest, DefaultData, BaseGenerator TEMPLATE = """ # My Prisma Schema This file is automatically generated every time `prisma generate` is ran. """ MODEL_TEMPLATE = """ ## {0.name} Model """ class MyGenerator(BaseGenerator): def get_manifest(self) -> Manifest: return Manifest( name='My Cool Generator', default_output='schema.md', ) def generate(self, data: DefaultData) -> None: content = TEMPLATE for model in data.dmmf.datamodel.models: content += MODEL_TEMPLATE.format(model) # make sure you use the output value given in the Prisma DMMF # as the output location can be customised! file = Path(data.generator.output.value) file.write_text(content) if __name__ == '__main__': MyGenerator.invoke() ``` -------------------------------- ### Watch Prisma Schema Changes and Regenerate Client Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/quickstart Continuously monitors the `schema.prisma` file for changes and automatically regenerates the Prisma Client. This streamlines the development workflow by ensuring the client stays synchronized with the schema. ```bash prisma generate --watch ``` -------------------------------- ### Push Prisma Schema to Database Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/quickstart Applies the database schema defined in `schema.prisma` to your database and generates the Prisma Client. This command is essential for creating database tables and synchronizing your schema with the database. Rerun this command whenever schema changes are made. ```bash prisma db push ``` -------------------------------- ### Run Pyright Source: https://prisma-client-py.readthedocs.io/en/stable/reference/type_checkers/pyright Executes the Pyright static type checker. This command assumes Pyright has been installed and is available in the system's PATH. ```bash pyright ``` -------------------------------- ### Configure Synchronous Prisma Client Schema Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/setup Defines the schema generator configuration for a synchronous Prisma Client Python. It specifies the provider as 'prisma-client-py' and the interface as 'sync'. The 'recursive_type_depth' controls the depth of recursive type generation. ```prisma generator client { provider = "prisma-client-py" interface = "sync" recursive_type_depth = 5 } ``` -------------------------------- ### Running Integration Tests with Nox (Bash) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Command to execute integration tests using `nox`. This example runs all tests in the `tests/integrations` directory for Python 3.9, or a specific subset like PostgreSQL tests. ```bash nox -s test -p 3.9 -- tests/integrations/ nox -s test -p 3.9 -- --confcutdir . tests/integrations/postgresql ``` -------------------------------- ### Configure Asyncio Prisma Client Schema Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/setup Defines the schema generator configuration for an asynchronous Prisma Client Python. It specifies the provider as 'prisma-client-py' and the interface as 'asyncio'. The 'recursive_type_depth' controls the depth of recursive type generation. ```prisma generator client { provider = "prisma-client-py" interface = "asyncio" recursive_type_depth = 5 } ``` -------------------------------- ### Limited Recursive Type Depth Example Source: https://prisma-client-py.readthedocs.io/en/stable/reference/config Shows a query example when `recursive_type_depth` is set to 2. This results in a shallower type generation, reducing the load on static type checkers while still allowing for some recursive relationships. ```python user = await db.user.find_unique( where={'id': user_id}, include={ 'profile': True, 'posts': True, }, ) ``` -------------------------------- ### Prisma Client Python Query Examples Source: https://prisma-client-py.readthedocs.io/en/stable/index Illustrates common database operations using Prisma Client Python, including retrieving multiple records, filtering with relations, searching by text, creating nested records, and updating existing records. ```python users = await db.user.find_many() ``` ```python users = await db.user.find_many( include={ 'posts': True, }, ) ``` ```python posts = await db.post.find_many( where={ 'OR': [ {'title': {'contains': 'prisma'}}, {'content': {'contains': 'prisma'}}, ] } ) ``` ```python user = await db.user.create( data={ 'name': 'Robert', 'email': 'robert@craigie.dev', 'posts': { 'create': { 'title': 'My first post from Prisma!', }, }, }, ) ``` ```python post = await db.post.update( where={ 'id': 42, }, data={ 'views': { 'increment': 1, }, }, ) ``` -------------------------------- ### Clean Up Corrupted Prisma Client Python Installation Source: https://prisma-client-py.readthedocs.io/en/stable/reference/troubleshooting This utility helps resolve issues where the Prisma Client Python installation may be corrupted, often after version upgrades. It can be run from the command line or programmatically. ```python python -m prisma_cleanup ``` ```python from prisma_cleanup import cleanup cleanup() ``` -------------------------------- ### Basic Generator Configuration Source: https://prisma-client-py.readthedocs.io/en/stable/reference/config A basic example of a `generator` block in `schema.prisma` to configure Prisma Client Python. This block specifies the provider and can include custom configuration options. ```prisma generator db { provider = "prisma-client-py" config_option = "value" } ``` -------------------------------- ### Synchronous Interface Usage Source: https://prisma-client-py.readthedocs.io/en/stable/reference/config Demonstrates how to use the Prisma Client Python with a synchronous interface, typically configured with `interface = "sync"`. Code examples show direct method calls for database operations. ```python user = db.user.find_unique( where={'id': 'user_id'} ) ``` -------------------------------- ### Execute Raw SQL Write Query Source: https://prisma-client-py.readthedocs.io/en/stable/reference/operations Executes a raw SQL query directly against the database. This example shows a 'SELECT' query, and results are raw dictionaries by default. ```python total = await db.execute_raw( ''' SELECT * FROM User WHERE User.id = ? ''', 'cksca3xm80035f08zjonuubik' ) ``` -------------------------------- ### Asyncio Interface Usage Source: https://prisma-client-py.readthedocs.io/en/stable/reference/config Demonstrates how to use the Prisma Client Python with an asynchronous interface, typically configured with `interface = "asyncio"`. Code examples show asynchronous operations using `await`. ```python user = await db.user.find_unique( where={'id': 'user_id'} ) ``` -------------------------------- ### Prisma Mypy Plugin Configuration Options Source: https://prisma-client-py.readthedocs.io/en/stable/reference/type_checkers/mypy This snippet demonstrates how to configure specific options for the Prisma mypy plugin within the `mypy.ini` file. Options are set under the `[prisma-mypy]` section. The example shows setting a generic `option` to `True`. ```ini [prisma-mypy] option = True ``` -------------------------------- ### Define Prisma Schema for SQLite Source: https://prisma-client-py.readthedocs.io/en/stable/getting_started/quickstart Defines a database schema using Prisma's declarative language, targeting an SQLite database. It includes a `datasource` block for database connection and a `generator` block for the Prisma Client Python. A `Post` model is defined with various fields, including a unique ID, timestamps, title, and a boolean published status. ```prisma datasource db { provider = "sqlite" url = "file:dev.db" } generator db { provider = "prisma-client-py" interface = "asyncio" recursive_type_depth = 5 } model Post { id String @id @default(cuid()) created_at DateTime @default(now()) updated_at DateTime @updatedAt title String published Boolean desc String? } ``` -------------------------------- ### Manual Connection and Disconnection Source: https://prisma-client-py.readthedocs.io/en/stable/reference/client Provides an example of manually connecting to and disconnecting from the Prisma Client using a `try...finally` block. This ensures the database connection is properly closed even if errors occur. ```python from prisma import Prisma db = Prisma() try: await db.connect() await db.user.create( data={ 'name': 'Robert', }, ) finally: if db.is_connected(): await db.disconnect() ``` -------------------------------- ### Default Recursive Type Depth Example Source: https://prisma-client-py.readthedocs.io/en/stable/reference/config Illustrates a typical query when using the default `recursive_type_depth` (which is 5). This shows a nested `include` structure for fetching related models, demonstrating the depth of type generation. ```python user = await db.user.find_unique( where={'id': user_id}, include={ 'profile': True, 'posts': { 'include': { 'categories': { 'include': { 'posts': True } } } }, }, ) ``` -------------------------------- ### Example of Deeply Nested Recursive Type Query Source: https://prisma-client-py.readthedocs.io/en/stable/reference/config Illustrates a complex query involving deeply nested recursive types, demonstrating the scenario where `recursive_type_depth` becomes relevant. This query structure highlights potential performance considerations. ```python user = await db.user.find_unique( where={'id': user_id}, include={ 'profile': True, 'posts': { 'include': { 'categories': { 'include': { 'posts': { 'include': { 'categories': True } } } } } }, }, ) ``` -------------------------------- ### Async Interactive Transaction with Model Queries - Prisma Source: https://prisma-client-py.readthedocs.io/en/stable/reference/transactions Shows how to use interactive transactions with model-based queries in an asynchronous context. This example updates user balances via the `User` model, passing the transaction object to `User.prisma()`. ```python from prisma import Prisma from prisma.models import User prisma = Prisma(auto_register=True) await prisma.connect() async with prisma.tx() as transaction: user = await User.prisma(transaction).update( where={'id': from_user_id}, data={'balance': {'decrement': 50}} ) if user.balance < 0: raise ValueError(f'{user.name} does not have enough balance') user = await User.prisma(transaction).update( where={'id': to_user_id}, data={'balance': {'increment': 50}} ) ``` -------------------------------- ### Configuring Transaction Timeouts - Prisma Source: https://prisma-client-py.readthedocs.io/en/stable/reference/transactions Example of how to configure `max_wait` and `timeout` options for interactive transactions in Prisma Client Python. This allows control over how long Prisma waits to acquire a transaction and the maximum duration a transaction can run. ```python from datetime import timedelta prisma.tx( max_wait=timedelta(seconds=2), timeout=timedelta(seconds=10), ) ``` -------------------------------- ### Prisma Client Python HTTP Configuration Type Source: https://prisma-client-py.readthedocs.io/en/stable/reference/client Defines the type hint for HTTP configuration options in Prisma Client Python. This is an illustrative example of supported HTTPX client options, not directly executable code for client initialization. ```python from typing import TypedDict, Callable, Mapping, Any, Union import httpx class HttpConfig(TypedDict, total=False): app: Callable[[Mapping[str, Any], Any], Any] http1: bool http2: bool limits: httpx.Limits timeout: Union[None, float, httpx.Timeout] trust_env: bool max_redirects: int ``` -------------------------------- ### Async Interactive Transaction Example - Prisma Source: https://prisma-client-py.readthedocs.io/en/stable/reference/transactions Demonstrates how to perform an asynchronous interactive transaction using Prisma Client Python. This code updates a user's balance, checks for insufficient funds, and then updates another user's balance. If an error occurs, the transaction is rolled back. ```python from prisma import Prisma prisma = Prisma() await prisma.connect() async with prisma.tx() as transaction: user = await transaction.user.update( where={'id': from_user_id}, data={'balance': {'decrement': 50}} ) if user.balance < 0: raise ValueError(f'{user.name} does not have enough balance') await transaction.user.update( where={'id': to_user_id}, data={'balance': {'increment': 50}} ) ``` -------------------------------- ### Building Docker Image for Multi-Platform Testing (Bash) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Command to build a Docker image locally using `make docker`. This is essential for testing across different CPU architectures by leveraging Docker's QEMU support. ```bash make docker ``` -------------------------------- ### Create and Connect Prisma Client Instance Source: https://prisma-client-py.readthedocs.io/en/stable/reference/client Demonstrates the basic steps to create a Prisma Client Python instance, connect to the database, and perform a user creation query. This is the fundamental way to interact with the database. ```python from prisma import Prisma db = Prisma() await db.connect() await db.user.create( data={ 'name': 'Robert', }, ) ``` -------------------------------- ### Basic Asynchronous Prisma Client Python Application Source: https://prisma-client-py.readthedocs.io/en/stable/index Demonstrates the fundamental structure of an asynchronous Prisma Client Python application, including connecting, performing a user creation query, and disconnecting. ```python import asyncio from prisma import Prisma async def main() -> None: prisma = Prisma() await prisma.connect() # write your queries here user = await prisma.user.create( data={ 'name': 'Robert', 'email': 'robert@craigie.dev' }, ) await prisma.disconnect() if __name__ == '__main__': asyncio.run(main()) ``` ```python import asyncio from prisma import Prisma from prisma.models import User async def main() -> None: db = Prisma(auto_register=True) await db.connect() # write your queries here user = await User.prisma().create( data={ 'name': 'Robert', 'email': 'robert@craigie.dev' }, ) await db.disconnect() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Grouping Records - Valid Order Argument Example (Python) Source: https://prisma-client-py.readthedocs.io/en/stable/reference/limitations Provides a correct example of using the `order` argument within the `group_by` method when grouping records. This code adheres to the limitation of only ordering by fields present in the `by` argument. It assumes a `Profile` model. ```python results = await Profile.prisma().group_by( by=['city'], order={ 'city': 'asc', }, ) ``` -------------------------------- ### Grouping Records - Having Argument Limitation (Python) Source: https://prisma-client-py.readthedocs.io/en/stable/reference/limitations Demonstrates a limitation with the `having` argument in `group_by`. It can only accept fields present in the `by` argument or aggregation filters. The first example will pass type checks but fail at runtime as 'views' is not in `by`. The second example shows a valid use case. ```python # this will pass type checks but will raise an error at runtime # as 'views' is not present in the `by` argument await Profile.prisma().group_by( by=['country'], count=True, having={ 'views': { 'gt': 50, }, }, ) # however this will pass both type checks and at runtime! await Profile.prisma().group_by( by=['country'], count=True, having={ 'views': { '_avg': { 'gt': 50, }, }, }, ) ``` -------------------------------- ### Optional Relational Field Example Source: https://prisma-client-py.readthedocs.io/en/stable/reference/type_checkers/mypy This Python snippet illustrates a case where a relational field, even when included, remains typed as `Optional` if it is optional in the Prisma schema. The example shows including 'profile', which can be `None` if not present, leading to a potential error if accessed directly without checking for `None`. ```python user = await db.user.find_unique( where={ 'id': 'user_id', }, include={ 'profile': True, } ) print(f'User {user.name}, bio: {user.profile.bio}') ``` -------------------------------- ### Async Batching with Context Manager - Python Source: https://prisma-client-py.readthedocs.io/en/stable/reference/batching Demonstrates how to use an asynchronous context manager to batch multiple user creation queries. Queries are automatically committed when the context manager exits. ```python async with db.batch_() as batcher: batcher.user.create({'name': 'Robert'}) batcher.user.create({'name': 'Tegan'}) ``` -------------------------------- ### Get Metrics (Prometheus Format) Source: https://prisma-client-py.readthedocs.io/en/stable/reference/metrics Retrieves database interaction metrics in Prometheus format. This format returns a string that is compatible with Prometheus data collection. ```APIDOC ## GET /metrics?format=prometheus ### Description Retrieves database interaction metrics in Prometheus format. This format returns a string compatible with Prometheus data collection. ### Method GET ### Endpoint /metrics ### Parameters #### Query Parameters - **format** (string) - Required - Specifies the output format. Must be set to 'prometheus'. ### Request Example ```json { "format": "prometheus" } ``` ### Response #### Success Response (200) - **metrics_data** (string) - A string containing metrics in Prometheus exposition format. #### Response Example ``` # HELP prisma_query_total Total number of queries executed. # TYPE prisma_query_total counter prisma_query_total 150 ``` ``` -------------------------------- ### Manual Batching Commit - Python Source: https://prisma-client-py.readthedocs.io/en/stable/reference/batching Shows how to manually create a batcher instance, add multiple user creation queries, and then explicitly commit them using `await batcher.commit()`. This provides more control over when the queries are executed. ```python batcher = db.batch_() batcher.user.create({'name': 'Robert'}) batcher.user.create({'name': 'Tegan'}) await batcher.commit() ``` -------------------------------- ### Use Context Manager for Connection Handling Source: https://prisma-client-py.readthedocs.io/en/stable/reference/client Demonstrates using a context manager (`async with`) to automatically handle connecting and disconnecting from the database. This simplifies resource management for short scripts. ```python from prisma import Prisma async with Prisma() as db: await db.user.create( data={ 'name': 'Robert', }, ) ``` -------------------------------- ### Run Database Tests with Nox Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Command to execute the database tests using nox. This command runs the custom testing suite against multiple database providers. Options include running tests in place for easier inspection and specifying asynchronous or synchronous tests. ```bash # Run all database tests (asynchronous by default) nox -s databases -- test --inplace # Run synchronous database tests nox -s databases -- test --inplace --for-async=false # Run tests against a specific database provider nox -s databases -- test --databases=postgresql ``` -------------------------------- ### Generate Assets from DMMF Source: https://prisma-client-py.readthedocs.io/en/stable/reference/custom-generators Generates assets based on the Prisma Schema DMMF (AST) provided during the generation step. This example extracts model names and writes them to a file specified in `data.generator.output.value`. ```python from pathlib import Path from prisma.generator import BaseGenerator, DefaultData class MyGenerator(BaseGenerator): # some code has been ommited from this example for brevity # the full boilerplate example can be found below def generate(self, data: DefaultData) -> None: content = [ model.name for model in data.dmmf.datamodel.models ] file = Path(data.generator.output.value) file.write_text('\n'.join(content)) ``` -------------------------------- ### Get Metrics (JSON Format) Source: https://prisma-client-py.readthedocs.io/en/stable/reference/metrics Retrieves database interaction metrics in JSON format. The default format returns a prisma.Metrics instance, providing structured data about counters and other metrics. ```APIDOC ## GET /metrics ### Description Retrieves database interaction metrics in JSON format. ### Method GET ### Endpoint /metrics ### Parameters #### Query Parameters - **format** (string) - Optional - Specifies the output format. Defaults to 'json'. ### Request Example ```json { "format": "json" } ``` ### Response #### Success Response (200) - **metrics** (prisma.Metrics) - An instance containing detailed metrics data. - **counters** (list) - A list of counter metrics. #### Response Example ```json { "counters": [ { "name": "prisma.query.total", "value": 150 } ] } ``` ``` -------------------------------- ### Combining Prisma Query Filters using NOT Source: https://prisma-client-py.readthedocs.io/en/stable/reference/operations Shows how to use the `NOT` logical operator in Prisma to exclude records that match a specific condition. Example filters out posts with a specific title. ```python post = await db.post.find_first( where={ 'NOT' [ { 'title': 'My test post', }, ], }, ) ``` -------------------------------- ### Adding Pyright Type Test (Bash) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Instructions for adding a new Pyright type test. This involves creating a `.py` file in the `typesafety/pyright` directory and then running a specific `nox` command. ```bash nox -s typesafety-pyright ``` -------------------------------- ### Updating a Unique Record in Prisma Source: https://prisma-client-py.readthedocs.io/en/stable/reference/operations Shows how to update a single record in Prisma based on its unique identifier. Includes an example of atomically incrementing a field and including related data in the response. ```python post = await db.post.update( where={ 'id': 'cksc9lp7w0014f08zdkz0mdnn', }, data={ 'views': { 'increment': 1, } }, include={ 'categories': True, } ) ``` -------------------------------- ### Running Unit Tests with Nox (Bash) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Commands to run unit tests using `nox`. This includes running all tests and passing arguments directly to `pytest`, such as disabling integration tests. ```bash nox -s test -p 3.9 nox -s test -p 3.9 -- -x --ignore=tests/integrations ``` -------------------------------- ### Filtering by Field Values Source: https://prisma-client-py.readthedocs.io/en/stable/reference/operations Provides examples and explanations for filtering records based on the values of various field types, including string, integer, float, DateTime, Boolean, and JSON fields. ```APIDOC ## Filtering by Field Values This section covers filtering records based on the values of individual fields. Various operators are available for different data types. ### String Fields Filter string fields using exact matches or various operators like `equals`, `contains`, `startswith`, `endswith`, `in`, `not_in`, and `mode` for case-insensitivity (PostgreSQL/MongoDB). Full-text search (`search`) is available on PostgreSQL and MySQL. ```python post = await db.post.find_first( where={ 'description': 'Must be exact match', # or 'description': { 'equals': 'example_string', 'not_in': ['ignore_string_1', 'ignore_string_2'], 'lt': 'z', 'lte': 'y', 'gt': 'a', 'gte': 'b', 'contains': 'string must be present', 'startswith': 'must start with string', 'endswith': 'must end with string', 'in': ['find_string_1', 'find_string_2'], 'mode': 'insensitive', # Only for PostgreSQL and MongoDB 'search': 'full-text query', # Only for PostgreSQL and MySQL 'not': { 'contains': 'string must not be present', 'mode': 'default', ... }, }, }, ) ``` ### Integer Fields Filter integer fields using exact matches or operators like `equals`, `in`, `not_in`, `lt`, `lte`, `gt`, `gte`, and `not`. ```python post = await db.post.find_first( where={ 'views': 10, # or 'views': { 'equals': 1, 'in': [1, 2, 3], 'not_in': [4, 5, 6], 'lt': 10, 'lte': 9, 'gt': 0, 'gte': 1, 'not': { 'gt': 10, ... }, }, }, ) ``` ### Float Fields Filter float fields using exact matches or operators like `equals`, `in`, `not_in`, `lt`, `lte`, `gt`, `gte`, and `not`. ```python user = await db.user.find_first( where={ 'points': 10.0, # or 'points': { 'equals': 10.0, 'in': [1.2, 1.3, 1.4], 'not_in': [4.7, 53.4, 6.8], 'lt': 100.5, 'lte': 9.9, 'gt': 0.0, 'gte': 1.2, 'not': { 'gt': 10.0, ... }, }, }, ) ``` ### DateTime Fields Filter DateTime fields using exact matches or operators like `equals`, `in`, `not_in`, `lt`, `lte`, `gt`, `gte`, and `not`. Requires importing `datetime`. ```python from datetime import datetime post = await db.post.find_first( where={ 'updated_at': datetime.now(), # or 'updated_at': { 'equals': datetime.now(), 'not_in': [datetime.now(), datetime.utcnow()], 'lt': datetime.now(), 'lte': datetime.now(), 'gt': datetime.now(), 'gte': datetime.now(), 'in': [datetime.now(), datetime.utcnow()], 'not': { 'equals': datetime.now(), ... }, }, }, ) ``` ### Boolean Fields Filter boolean fields using `equals` and `not` operators. ```python post = await db.post.find_first( where={ 'published': True, # or 'published': { 'equals': True, 'not': False, }, }, ) ``` ### Json Fields Filter JSON fields using exact matches (`equals`) or `not`. JSON fields must match exactly and are not supported on SQLite. Requires importing `Json` from `prisma`. ```python from prisma import Json user = await db.user.find_first( where={ 'meta': Json({'country': 'Scotland'}) # or 'meta': { 'equals': Json.keys(country='Scotland'), 'not': Json(['foo']) } } ) ``` ``` -------------------------------- ### Running Type Safety Tests (Bash) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Command to execute type safety checks using `make typesafety`, which leverages `pytest-pyright` and `pytest-mypy-plugins`. ```bash make typesafety ``` -------------------------------- ### Query Directly from Model Classes Source: https://prisma-client-py.readthedocs.io/en/stable/reference/client Shows how to perform database operations directly using model classes, such as creating a user. This approach simplifies queries by providing a more object-oriented interface. ```python from prisma.models import User user = await User.prisma().create( data={ 'name': 'Robert', }, ) ``` -------------------------------- ### Configure Mypy Plugin Source: https://prisma-client-py.readthedocs.io/en/stable/reference/type_checkers/mypy This snippet shows how to configure the mypy plugin by adding the `prisma.mypy` path to the `plugins` setting in your `mypy.ini` configuration file. This enables Prisma's type checking extensions. ```ini [mypy] plugins = prisma.mypy ``` -------------------------------- ### Get Prisma Metrics in Prometheus Format (Python) Source: https://prisma-client-py.readthedocs.io/en/stable/reference/metrics Retrieves Prisma metrics in Prometheus format as a string using `Prisma.get_metrics(format='prometheus')`. This output is suitable for Prometheus monitoring systems. Requires the Prisma library. ```python from prisma import Prisma client = Prisma() metrics = client.get_metrics(format='prometheus') print(metrics) ``` -------------------------------- ### Prisma Generator Configuration Options Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/architecture Demonstrates different ways to configure the 'prisma-client-py' provider in a Prisma schema file. These options are functionally equivalent and point to the same underlying generation logic. ```prisma generator client { provider = "prisma-client-py" } ``` ```prisma generator client { provider = "python3 -m prisma" } ``` ```prisma generator client { provider = "python3 -c 'from prisma.cli import main; main()'" } ``` -------------------------------- ### Decimal Fields Handling Source: https://prisma-client-py.readthedocs.io/en/stable/reference/operations Illustrates how to work with Decimal fields, including exact matching and range-based queries. ```APIDOC ## Decimal Fields ```python from decimal import Decimal user = await db.user.find_first( where={ 'number': Decimal(1), # or 'number': { 'equals': Decimal('1.23823923283'), 'in': [Decimal('1.3'), Decimal('5.6')], 'not_in': [Decimal(10), Decimal(20)], 'gte': Decimal(5), 'gt': Decimal(11), 'lt': Decimal(4), 'lte': Decimal(3), 'not': Decimal('123456.28'), # or 'not': { # recursive type ... } }, }, ) ``` ``` -------------------------------- ### Deleting a Unique Record in Prisma Source: https://prisma-client-py.readthedocs.io/en/stable/reference/operations Provides code examples for deleting a single record from a Prisma database table using its unique identifier. It shows a basic delete and one that includes related records. ```python post = await db.post.delete( where={ 'id': 'cksc9m7un0028f08zwycxtjr1', }, ) ``` ```python post = await db.post.delete( where={ 'id': 'cksc9m1vu0021f08zq0066pnz', }, include={ 'categories': True, } ) ``` -------------------------------- ### Adding Mypy Type Test (Bash) Source: https://prisma-client-py.readthedocs.io/en/stable/contributing/contributing Instructions for adding a new Mypy type test. This involves creating a `test_*.yml` file in the `typesafety` directory and then running a specific `nox` command. ```bash nox -s typesafety-mypy ``` -------------------------------- ### Generate Prisma Client Python Source: https://prisma-client-py.readthedocs.io/en/stable/index Command to push the Prisma schema to the database and generate the Prisma Client Python. Re-run this command or use `prisma generate --watch` when the schema file changes. ```bash prisma db push ``` ```bash prisma generate --watch ``` -------------------------------- ### Grouping Records - Valid Having Argument Example (Python) Source: https://prisma-client-py.readthedocs.io/en/stable/reference/limitations Illustrates a valid use case for the `having` argument in the `group_by` method, where the field is present in the `by` argument. This ensures both type checking and runtime success. It assumes a `Profile` model. ```python results = await Profile.prisma().group_by( by=['city'], having={ 'city': { 'gt': 'a', }, }, ) ``` -------------------------------- ### Configure Prisma Client Python via pyproject.toml Source: https://prisma-client-py.readthedocs.io/en/stable/reference/config Demonstrates how to set configuration options for Prisma Client Python within the `pyproject.toml` file under the `tool.prisma` key. This method is suitable for project-specific settings. ```toml [tool.prisma] # cache engine binaries in a directory relative to your project binary_cache_dir = ".binaries" ``` -------------------------------- ### Create Partial Model with Required Fields - Python Source: https://prisma-client-py.readthedocs.io/en/stable/reference/partials This Python example demonstrates how to ensure specific fields are required in a generated partial type using the `required` parameter in `User.create_partial`. Fields listed here will not be marked as `Optional`. ```python from prisma.models import User # Create a partial type named 'UserRequiredEmail' making the 'email' field required User.create_partial('UserRequiredEmail', required={'email'}) ```