Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork83
Prisma Client Python is an auto-generated and fully type-safe database client designed for ease of use
License
RobertCraigie/prisma-client-py
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Warning
Prisma Client Python is no longer being maintained. Seethis issue for more information.
Prisma Client Python is a next-generation ORM built on top ofPrisma that has been designed from the ground up for ease of use and correctness.
Prisma is a TypeScript ORM with zero-cost type safety for your database, although don't worry, Prisma Client Pythoninterfaces with Prisma using Rust, you don't need Node or TypeScript.
Prisma Client Python can be used inany Python backend application. This can be a REST API, a GraphQL API oranything else that needs a database.
Note that the only language server that is known to support this form of autocompletion is Pylance / Pyright.
Unlike other Python ORMs, Prisma Client Python isfully type safe and offers native support for usagewith and withoutasync
. All you have to do isspecify the type of client you would like to use for your project in thePrisma schema file.
However, the arguably best feature that Prisma Client Python provides isautocompletion support (see the GIF above). This makes writing database queries easier than ever!
Core features:
- Prisma Migrate
- Full type safety
- With / without async
- Recursive and pseudo-recursive types
- Atomic updates
- Complex cross-relational queries
- Partial type generation
- Batching write queries
Supported database providers:
- PostgreSQL
- MySQL
- SQLite
- CockroachDB
- MongoDB (experimental)
- SQL Server (experimental)
Have any questions or need help using Prisma? Join thecommunity discord!
If you don't want to join the discord you can also:
- Create a newdiscussion
- Ping me on thePrisma Slack
@Robert Craigie
This section provides a high-level overview of how Prisma works and its most important technical components. For a more thorough introduction, visit thedocumentation.
Every project that uses a tool from the Prisma toolkit starts with aPrisma schema file. The Prisma schema allows developers to define theirapplication models in an intuitive data modeling language. It also contains the connection to a database and defines agenerator:
// databasedatasourcedb {provider="sqlite"url="file:database.db"}// generatorgeneratorclient {provider="prisma-client-py"recursive_type_depth=5}// data modelsmodelPost {idInt@id@default(autoincrement())titleStringcontentString?viewsInt@default(0)publishedBoolean@default(false)authorUser?@relation(fields:[author_id],references:[id])author_idInt?}modelUser {idInt@id@default(autoincrement())emailString@uniquenameString?postsPost[]}
In this schema, you configure three things:
- Data source: Specifies your database connection. In this case we use a local SQLite database however you can also use an environment variable.
- Generator: Indicates that you want to generate Prisma Client Python.
- Data models: Defines your application models.
On this page, the focus is on the generator as this is the only part of the schema that is specific to Prisma Client Python. You can learn more aboutData sources andData models on their respective documentation pages.
A prisma schema can define one or more generators, defined by thegenerator
block.
A generator determines what assets are created when you run theprisma generate
command. Theprovider
value defines which Prisma Client will be created. In this case, as we want to generate Prisma Client Python, we use theprisma-client-py
value.
You can also define where the client will be generated to with theoutput
option. By default Prisma Client Python will be generated to the same location it was installed to, whether that's inside a virtual environment, the global python installation or anywhere else that python packages can be imported from.
For more options seeconfiguring Prisma Client Python.
Just want to play around with Prisma Client Python and not worry about any setup? You can try it out online ongitpod.
The first step with any python project should be to setup a virtual environment to isolate installed packages from your other python projects, however that is out of the scope for this page.
In this example we'll use an asynchronous client, if you would like to use a synchronous client seesetting up a synchronous client.
pip install -U prisma
Now that we have Prisma Client Python installed we need to actually generate the client to be able to access the database.
Copy the Prisma schema file shown above to aschema.prisma
file in the root directory of your project and run:
prisma db push
This command will add the data models to your database and generate the client, you should see something like this:
Prisma schema loaded from schema.prismaDatasource "db": SQLite database "database.db" at "file:database.db"SQLite database database.db created at file:database.db🚀 Your database is now in sync with your schema. Done in 26ms✔ Generated Prisma Client Python to ./.venv/lib/python3.9/site-packages/prisma in 265ms
It should be noted that whenever you make changes to yourschema.prisma
file you will have to re-generate the client, you can do this automatically by runningprisma generate --watch
.
The simplest asynchronous Prisma Client Python application will either look something like this:
importasynciofromprismaimportPrismaasyncdefmain()->None:prisma=Prisma()awaitprisma.connect()# write your queries hereuser=awaitprisma.user.create(data={'name':'Robert','email':'robert@craigie.dev' }, )awaitprisma.disconnect()if__name__=='__main__':asyncio.run(main())
or like this:
importasynciofromprismaimportPrismafromprisma.modelsimportUserasyncdefmain()->None:db=Prisma(auto_register=True)awaitdb.connect()# write your queries hereuser=awaitUser.prisma().create(data={'name':'Robert','email':'robert@craigie.dev' }, )awaitdb.disconnect()if__name__=='__main__':asyncio.run(main())
For a more complete list of queries you can perform with Prisma Client Python see thedocumentation.
All query methods returnpydantic models.
Retrieve allUser
records from the database
users=awaitdb.user.find_many()
Include theposts
relation on each returnedUser
object
users=awaitdb.user.find_many(include={'posts':True, },)
Retrieve allPost
records that contain"prisma"
posts=awaitdb.post.find_many(where={'OR': [ {'title': {'contains':'prisma'}}, {'content': {'contains':'prisma'}}, ] })
Create a newUser
and a newPost
record in the same query
user=awaitdb.user.create(data={'name':'Robert','email':'robert@craigie.dev','posts': {'create': {'title':'My first post from Prisma!', }, }, },)
Update an existingPost
record
post=awaitdb.post.update(where={'id':42, },data={'views': {'increment':1, }, },)
All Prisma Client Python methods are fully statically typed, this means you can easily catch bugs in your code without having to run it!
For more details see thedocumentation.
Prisma Client Python connects to the database and executes queries using Prisma's rust-based Query Engine, of which the source code can be found here:https://github.com/prisma/prisma-engines.
Prisma Client Python exposes a CLI interface which wraps thePrisma CLI. This works by downloading a Node binary, if you don't already have Node installed on your machine, installing the CLI withnpm
and running the CLI using Node.
The CLI interface is the exact same as the standardPrisma CLI withsome additional commands.
Prisma Client Python isnot an official Prisma product although it is very generously sponsored by Prisma.
Prisma Client Python is a fairly new project and as such there are some features that are missing or incomplete.
Prisma Client Python query arguments make use ofTypedDict
types. Support for completion of these types within the Python ecosystem is now fairly widespread. This section is only here for documenting support.
Supported editors / extensions:
- VSCode withpylance v2021.9.4 or higher
- Sublime Text withLSP-Pyright v1.1.196 or higher
- PyCharm2022.1 EAP 3 added support for completing
TypedDict
s- This does not yet work for Prisma Client Python unfortunately, seethis issue
- Any editor that supports the Language Server Protocol and has an extension supporting Pyright v1.1.196 or higher
user=awaitdb.user.find_first(where={'|' })
Given the cursor is where the|
is, an IDE should suggest the following completions:
- id
- name
- posts
While there has currently not been any work done on improving the performance of Prisma Client Python queries, they should be reasonably fast as the core query building and connection handling is performed by Prisma.Performance is something that will be worked on in the future and there is room for massive improvements.
Windows, MacOS and Linux are all officially supported.
Prisma Client Python isnot stable.
Breaking changes will be documented and released under a newMINOR version following this format.
MAJOR
.MINOR
.PATCH
New releases are scheduled bi-weekly, however as this is a solo project, no guarantees are made that this schedule will be stuck to.
We useconventional commits (also known as semantic commits) to ensure consistent and descriptive commit messages.
See thecontributing documentation for more information.
This project would not be possible without the work of the amazing folks over atprisma.
Massive h/t to@steebchen for his work onprisma-client-go which was incredibly helpful in the creation of this project.
This README is also heavily inspired by the README in theprisma/prisma repository.
About
Prisma Client Python is an auto-generated and fully type-safe database client designed for ease of use
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.