Package: prisma-client
Prisma Client PythonType-safe database access for PythonWhat is Prisma Client Python?Prisma Client Python is an unofficial implementation ofPrismawhich is anext-generation ORMthat comes bundled with tools, such asPrisma Migrate, which make working with databases as easy as possible.Prisma Client Python can be used inanyPython backend application. This can be a REST API, a GraphQL API oranythingelse that needs a database.Why should you use Prisma Client Python?Unlike other Python ORMs, Prisma Client Python isfully type safeand offers native support for usagewith and withoutasync. All you have to do isspecify the type of clientyou would like to use for your project in thePrisma schema file.Core features:Full type safetyWith / without asyncRecursive and pseudo-recursive typesAtomic updatesComplex cross-relational queriesPartial type generationBatching write queriesSupported database providers:PostgreSQLMySQLSQLiteMongoDB (experimental)SQL Server (experimental)How does Prisma work?This section provides a high-level overview of how Prisma works and its most important technical components. For a more thorough introduction, visit thedocumentation.The Prisma schemaEvery project that uses a tool from the Prisma toolkit starts with aPrisma schema file. The Prisma schema allows developers to define theirapplication modelsin an intuitive data modeling language. It also contains the connection to a database and defines agenerator:// database
datasource db {
  provider = "sqlite"
  url      = "file:database.db"
}

// generator
generator client {
  provider = "prisma-client-py"
}

// data models
model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  views     Int     @default(0)
  published Boolean @default(false)
  author    User?   @relation(fields: [author_id], references: [id])
  author_id Int?
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}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 sourcesandData modelson their respective documentation pages.Prisma generatorA prisma schema can define one or more generators, defined by thegeneratorblock.A generator determines what assets are created when you run theprisma generatecommand. Theprovidervalue defines which Prisma Client will be created. In this case, as we want to generate Prisma Client Python, we use theprisma-client-pyvalue.You can also define where the client will be generated to with theoutputoption. By default Prisma Client Python will be generated to the same location it was installed to, whether thats 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.Accessing your database with Prisma Client PythonJust want to play around with Prisma Client Python and not worry about any setup? You can try it out online ongitpod.Installing Prisma Client PythonThe 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.pipinstall-Uprisma-clientGenerating Prisma Client PythonNow 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.prismafile in the root directory of your project and run:prismadbpushThis command will add the data models to your database and generate the client, you should see something like this:Prisma schema loaded from schema.prisma
Datasource "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 265msIt should be noted that whenever you make changes to yourschema.prismafile you will have to re-generate the client, you can do this automatically by runningprisma generate --watch.The simplest asynchronous Prisma Client Python application looks something like this:importasynciofromprismaimportClientasyncdefmain()->None:client=Client()awaitclient.connect()# write your queries hereawaitclient.disconnect()if__name__=='__main__':asyncio.get_event_loop().run_until_complete(main())Query examplesFor a more complete list of queries you can perform with Prisma Client Python see thedocumentation.All query methods returnpydantic models.Retrieve allUserrecords from the databaseusers=awaitclient.user.find_many()Include thepostsrelation on each returnedUserobjectusers=awaitclient.user.find_many(include={'posts':True,},)Retrieve allPostrecords that contain"prisma"posts=awaitclient.post.find_many(where={'OR':[{'title':{'contains':'prisma'}},{'content':{'contains':'prisma'}},]})Create a newUserand a newPostrecord in the same queryuser=awaitclient.user.create(data={'name':'Robert','email':'robert@craigie.dev','posts':{'create':{'title':'My first post from Prisma!',},},},)Update an existingPostrecordpost=awaitclient.post.update(where={'id':42,},data={'views':{'increment':1,},},)Usage with static type checkersAll 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.Room for improvementPrisma Client Python is a new project and as such there are some features that are missing or incomplete.Auto completion for query argumentsPrisma Client Python query arguments make use ofTypedDicttypes. While there is very limited support for completion of these types within the Python ecosystem some editors do support it.Supported editors / extensions:VSCode withpylancev2021.9.4 or higherSublime Text withLSP-Pyrightv1.1.96 or higheruser=awaitclient.user.find_first(where={'|'})Given the cursor is where the|is, an IDE should suggest the following completions:idemailnamepostsPerformanceThere has currently not been any work done on improving the performance of Prisma Client Python queries, this is something that will be worked on in the future and there is room for massive improvements.Supported platformsOnly MacOS and Linux are officially supported.Windows is unofficially supported as tests are not currently ran on windows.Version guaranteesPrisma Client Python isnotstable.Breaking changes will be documented and released under a newMINORversion following this format.MAJOR.MINOR.PATCHContributingWe useconventional commits(also known as semantic commits) to ensure consistent and descriptive commit messages.See thecontributing documentationfor more information.AttributionsThis project would not be possible without the work of the amazing folks over atprisma.Massive h/t to@steebchenfor his work onprisma-client-gowhich was incredibly helpful in the creation of this project.This README is also heavily inspired by the README in theprisma/prismarepository.